Skip to content

Commit

Permalink
Implement Add<Duration> and Sub<Duration> for Time
Browse files Browse the repository at this point in the history
Signed-off-by: Luca Della Vedova <lucadv@intrinsic.ai>
  • Loading branch information
luca-della-vedova committed Aug 4, 2023
1 parent 9c3d987 commit 99401aa
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 3 deletions.
41 changes: 39 additions & 2 deletions rclrs/src/time.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
use crate::rcl_bindings::*;
use std::ops::{Add, Sub};
use std::sync::{Mutex, Weak};
use std::time::Duration;

/// Struct that represents time.
#[derive(Debug)]
#[derive(Clone, Debug)]
pub struct Time {
/// Timestamp in nanoseconds.
pub nsec: i64,
Expand All @@ -23,9 +25,34 @@ impl Time {
}
}

impl Add<Duration> for Time {
type Output = Self;

fn add(self, other: Duration) -> Self {
let dur_ns = i64::try_from(other.as_nanos()).unwrap();
Time {
nsec: self.nsec.checked_add(dur_ns).unwrap(),
clock: self.clock.clone(),
}
}
}

impl Sub<Duration> for Time {
type Output = Self;

fn sub(self, other: Duration) -> Self {
let dur_ns = i64::try_from(other.as_nanos()).unwrap();
Time {
nsec: self.nsec.checked_sub(dur_ns).unwrap(),
clock: self.clock.clone(),
}
}
}

#[cfg(test)]
mod tests {
use crate::clock::Clock;
use super::*;
use crate::Clock;

#[test]
fn compare_times_from_same_clock() {
Expand All @@ -47,4 +74,14 @@ mod tests {
assert!(t2.compare_with(&t1, |_, _| ()).is_none());
assert!(t1.compare_with(&t2, |_, _| ()).is_none());
}

#[test]
fn add_duration_to_time() {
let (clock, _) = Clock::with_source().unwrap();
let t = clock.now();
let t2 = t.clone() + Duration::from_secs(1);
assert_eq!(t2.nsec - t.nsec, 1_000_000_000i64);
let t3 = t2 - Duration::from_secs(1);
assert_eq!(t3.nsec, t.nsec);
}
}
7 changes: 6 additions & 1 deletion rclrs/src/time_source.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,11 +102,16 @@ impl fmt::Display for ClockMismatchError {
}

impl TimeSource {
/// Creates a new time source with default parameters.
/// Creates a new `TimeSource` with default parameters.
pub fn new(node: Arc<Node>, clock: ClockSource) -> Self {
TimeSourceBuilder::new(node, clock).build().unwrap()
}

/// Creates a new `TimeSourceBuilder` with default parameters.
pub fn builder(node: Arc<Node>, clock: ClockSource) -> TimeSourceBuilder {
TimeSourceBuilder::new(node, clock)
}

/// Attaches the given clock to the `TimeSource`, enabling the `TimeSource` to control it.
pub fn attach_clock(&self, clock: ClockSource) {
if let Some(last_msg) = self._last_time_msg.lock().unwrap().as_ref() {
Expand Down

0 comments on commit 99401aa

Please sign in to comment.