Skip to content

Commit c732308

Browse files
committed
feat(time): implement Time (+|-|+=|-=) Duration
1 parent 862d0ab commit c732308

File tree

2 files changed

+50
-3
lines changed

2 files changed

+50
-3
lines changed

src/constance/src/time/time.rs

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use core::{convert::TryInto, fmt};
1+
use core::{convert::TryInto, fmt, ops};
22

33
use crate::{
44
time::Duration,
@@ -159,6 +159,18 @@ impl Time {
159159
.ok()?,
160160
))
161161
}
162+
163+
/// Advance the time by `duration` and return the result.
164+
#[inline]
165+
pub const fn wrapping_add(&self, duration: Duration) -> Self {
166+
Self::from_micros(self.micros.wrapping_add(duration.as_micros() as i64 as u64))
167+
}
168+
169+
/// Put back the time by `duration` and return the result.
170+
#[inline]
171+
pub const fn wrapping_sub(&self, duration: Duration) -> Self {
172+
Self::from_micros(self.micros.wrapping_sub(duration.as_micros() as i64 as u64))
173+
}
162174
}
163175

164176
impl fmt::Debug for Time {
@@ -167,5 +179,41 @@ impl fmt::Debug for Time {
167179
}
168180
}
169181

182+
impl ops::Add<Duration> for Time {
183+
type Output = Self;
184+
185+
/// Advance the time by `duration` and return the result.
186+
#[inline]
187+
fn add(self, rhs: Duration) -> Self::Output {
188+
self.wrapping_add(rhs)
189+
}
190+
}
191+
192+
impl ops::AddAssign<Duration> for Time {
193+
/// Advance the time by `duration` in place.
194+
#[inline]
195+
fn add_assign(&mut self, rhs: Duration) {
196+
*self = *self + rhs;
197+
}
198+
}
199+
200+
impl ops::Sub<Duration> for Time {
201+
type Output = Self;
202+
203+
/// Put back the time by `duration` and return the result.
204+
#[inline]
205+
fn sub(self, rhs: Duration) -> Self::Output {
206+
self.wrapping_sub(rhs)
207+
}
208+
}
209+
210+
impl ops::SubAssign<Duration> for Time {
211+
/// Put back the time by `duration` in place.
212+
#[inline]
213+
fn sub_assign(&mut self, rhs: Duration) {
214+
*self = *self - rhs;
215+
}
216+
}
217+
170218
// TODO: Add more tests
171219
// TODO: Interoperation with `::chrono`

src/constance_test_suite/src/kernel_tests/time_misc.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -66,8 +66,7 @@ fn task_body<System: Kernel, D: Driver<App<System>>>(_: usize) {
6666
log::trace!("sleeping for {:?}", d);
6767
System::sleep(d).unwrap();
6868

69-
// TODO: `impl Add<Duration> for Time`
70-
let now4 = Time::from_micros(now3.as_micros().wrapping_add(d.as_micros() as _));
69+
let now4 = now3 + d;
7170
let now4_got = System::time().unwrap();
7271
log::trace!("time = {:?} (expected >= {:?})", now4_got, now4);
7372
assert!(now4_got.as_micros() >= now4.as_micros());

0 commit comments

Comments
 (0)