Skip to main content

nros_core/
time.rs

1//! ROS time types.
2//!
3//! Provides [`Time`] (seconds + nanoseconds) and [`Duration`] with
4//! arithmetic, conversions, and CDR serialization. All types are `no_std`
5//! compatible and use integer arithmetic only (no `f64::floor`/`f64::abs`).
6
7use core::ops::{Add, Sub};
8use nros_serdes::{CdrReader, CdrWriter, DeserError, Deserialize, SerError, Serialize};
9
10/// Nanoseconds per second
11const NANOS_PER_SEC: i64 = 1_000_000_000;
12
13/// Split a float seconds value into (sec, nanosec) without using `f64::floor()`/`f64::abs()`
14/// which require `std`. Uses integer truncation with correction for negative values.
15fn split_secs_f64(secs: f64) -> (i32, u32) {
16    let truncated = secs as i32;
17    // `as i32` truncates toward zero; floor rounds toward negative infinity.
18    // Correct for negative values with a fractional part.
19    let sec = if (truncated as f64) > secs {
20        truncated - 1
21    } else {
22        truncated
23    };
24    let frac = secs - sec as f64;
25    // frac should be in [0, 1), but guard against float imprecision
26    let frac = if frac < 0.0 { -frac } else { frac };
27    let nanosec = (frac * NANOS_PER_SEC as f64) as u32;
28    (sec, nanosec)
29}
30
31/// A generated message whose field set is `{ sec: i32, nanosec: u32 }` —
32/// `builtin_interfaces/msg/Time` and its `Duration` twin.
33///
34/// **This is the Rust substitute for a C++ template parameter.** `nros-cpp`
35/// spells the same conversion as
36/// `template <typename TimeMsgT> void Time::to_msg(TimeMsgT&)`
37/// (`packages/api/nros-cpp/include/rclcpp/time.hpp`), which binds structurally to
38/// anything carrying `sec` / `nanosec`. Rust has no structural bound, so the same
39/// trick needs an AUTHORED trait that `rosidl-codegen` implements for every
40/// generated message with that exact field set — the same binding set the C++
41/// template has, decided by SHAPE rather than by a hard-coded package name.
42///
43/// Why the trait lives here and the impl does not: `nros-core` can never name a
44/// message type. Every generated message crate depends on `nros-core`, so a
45/// dependency the other way is a cycle, and message types are generated per USER
46/// package — there is no one crate for the client library
47/// to name. The trait is the seam that lets the conversion cross that edge
48/// without an edge.
49///
50/// Implemented by codegen; nothing in this crate implements it.
51pub trait SecNanosecMsg: Sized {
52    /// Build the message from an already-decomposed timestamp.
53    ///
54    /// Infallible by construction — both components are already the message's
55    /// own field types. See [`Time::to_ros_msg`] for why no `Result` appears
56    /// here.
57    fn from_sec_nanosec(sec: i32, nanosec: u32) -> Self;
58}
59
60/// ROS Time representation
61///
62/// Matches `builtin_interfaces/msg/Time`:
63/// - `sec`: Seconds since epoch (signed for pre-epoch times)
64/// - `nanosec`: Nanoseconds within the second (0-999999999)
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PartialOrd, Ord)]
66pub struct Time {
67    /// Seconds component
68    pub sec: i32,
69    /// Nanoseconds component (0-999999999)
70    pub nanosec: u32,
71}
72
73impl Time {
74    /// Create a new Time
75    pub const fn new(sec: i32, nanosec: u32) -> Self {
76        Self { sec, nanosec }
77    }
78
79    /// Create a Time representing zero
80    pub const fn zero() -> Self {
81        Self { sec: 0, nanosec: 0 }
82    }
83
84    /// Check if this time is zero
85    pub const fn is_zero(&self) -> bool {
86        self.sec == 0 && self.nanosec == 0
87    }
88
89    /// Create a Time from nanoseconds since epoch
90    pub const fn from_nanos(nanos: i64) -> Self {
91        let sec = (nanos / NANOS_PER_SEC) as i32;
92        let nanosec = (nanos % NANOS_PER_SEC) as u32;
93        Self { sec, nanosec }
94    }
95
96    /// Convert to total nanoseconds since epoch
97    pub const fn to_nanos(&self) -> i64 {
98        (self.sec as i64) * NANOS_PER_SEC + (self.nanosec as i64)
99    }
100
101    /// Create a Time from a Duration (treating duration as time since epoch)
102    pub const fn from_duration(d: Duration) -> Self {
103        Self {
104            sec: d.sec,
105            nanosec: d.nanosec,
106        }
107    }
108
109    /// Convert to Duration (treating time as duration since epoch)
110    pub const fn as_duration(&self) -> Duration {
111        Duration {
112            sec: self.sec,
113            nanosec: self.nanosec,
114        }
115    }
116
117    /// Create a Time from seconds (float)
118    pub fn from_secs_f64(secs: f64) -> Self {
119        let (sec, nanosec) = split_secs_f64(secs);
120        Self { sec, nanosec }
121    }
122
123    /// Convert to seconds (float)
124    pub fn to_secs_f64(&self) -> f64 {
125        self.sec as f64 + (self.nanosec as f64 / NANOS_PER_SEC as f64)
126    }
127
128    /// Stamp a generated `builtin_interfaces/msg/Time` — the single most common
129    /// thing a publisher does.
130    ///
131    /// ```ignore
132    /// msg.header.stamp = node.now().to_ros_msg();
133    /// ```
134    ///
135    /// The return type is inferred from the call site; any generated message
136    /// with the `{ sec, nanosec }` field set satisfies [`SecNanosecMsg`], which
137    /// is the same binding set the C++ `Time::to_msg` template has.
138    ///
139    /// **INFALLIBLE, deliberately.** `rclrs::Time::to_ros_msg` returns
140    /// `Result<builtin_interfaces::msg::Time, TryFromIntError>` because its
141    /// `Time` holds `i64` nanoseconds and narrowing to `sec: i32` can overflow.
142    /// Ours ALREADY IS `{ sec: i32, nanosec: u32 }`, so this is two field copies
143    /// and cannot fail. Wrapping it in a `Result` so a ported `t.to_ros_msg()?`
144    /// keeps compiling would hide a difference instead of making the compiler
145    /// point at it — the inverse of the rule that a port fails to compile
146    /// rather than compiles and differs. A ported `?` fails to compile,
147    /// locally, with one character to fix.
148    pub fn to_ros_msg<M: SecNanosecMsg>(&self) -> M {
149        M::from_sec_nanosec(self.sec, self.nanosec)
150    }
151}
152
153impl Add<Duration> for Time {
154    type Output = Time;
155
156    fn add(self, rhs: Duration) -> Self::Output {
157        let total_nanos = self.to_nanos() + rhs.to_nanos();
158        Time::from_nanos(total_nanos)
159    }
160}
161
162impl Sub<Duration> for Time {
163    type Output = Time;
164
165    fn sub(self, rhs: Duration) -> Self::Output {
166        let total_nanos = self.to_nanos() - rhs.to_nanos();
167        Time::from_nanos(total_nanos)
168    }
169}
170
171impl Sub<Time> for Time {
172    type Output = Duration;
173
174    fn sub(self, rhs: Time) -> Self::Output {
175        let diff_nanos = self.to_nanos() - rhs.to_nanos();
176        Duration::from_nanos(diff_nanos)
177    }
178}
179
180impl Serialize for Time {
181    fn serialize(&self, writer: &mut CdrWriter) -> Result<(), SerError> {
182        writer.write_i32(self.sec)?;
183        writer.write_u32(self.nanosec)?;
184        Ok(())
185    }
186}
187
188impl Deserialize for Time {
189    fn deserialize(reader: &mut CdrReader) -> Result<Self, DeserError> {
190        Ok(Self {
191            sec: reader.read_i32()?,
192            nanosec: reader.read_u32()?,
193        })
194    }
195}
196
197/// ROS Duration representation
198///
199/// Matches `builtin_interfaces/msg/Duration`:
200/// - `sec`: Seconds (signed for negative durations)
201/// - `nanosec`: Nanoseconds (0-999999999)
202#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, PartialOrd, Ord)]
203pub struct Duration {
204    /// Seconds component
205    pub sec: i32,
206    /// Nanoseconds component (0-999999999)
207    pub nanosec: u32,
208}
209
210impl Duration {
211    /// Create a new Duration
212    pub const fn new(sec: i32, nanosec: u32) -> Self {
213        Self { sec, nanosec }
214    }
215
216    /// Create a Duration representing zero
217    pub const fn zero() -> Self {
218        Self { sec: 0, nanosec: 0 }
219    }
220
221    /// Check if this duration is zero
222    pub const fn is_zero(&self) -> bool {
223        self.sec == 0 && self.nanosec == 0
224    }
225
226    /// Create a Duration from seconds
227    pub const fn from_secs(secs: i32) -> Self {
228        Self {
229            sec: secs,
230            nanosec: 0,
231        }
232    }
233
234    /// Create a Duration from milliseconds
235    pub const fn from_millis(millis: i64) -> Self {
236        let sec = (millis / 1000) as i32;
237        let nanosec = ((millis % 1000) * 1_000_000) as u32;
238        Self { sec, nanosec }
239    }
240
241    /// Create a Duration from nanoseconds
242    pub const fn from_nanos(nanos: i64) -> Self {
243        let sec = (nanos / NANOS_PER_SEC) as i32;
244        let nanosec = (nanos % NANOS_PER_SEC).unsigned_abs() as u32;
245        Self { sec, nanosec }
246    }
247
248    /// Convert to total nanoseconds
249    pub const fn to_nanos(&self) -> i64 {
250        (self.sec as i64) * NANOS_PER_SEC + (self.nanosec as i64)
251    }
252
253    /// Create a Duration from seconds (float)
254    pub fn from_secs_f64(secs: f64) -> Self {
255        let (sec, nanosec) = split_secs_f64(secs);
256        Self { sec, nanosec }
257    }
258
259    /// Convert to seconds (float)
260    pub fn to_secs_f64(&self) -> f64 {
261        self.sec as f64 + (self.nanosec as f64 / NANOS_PER_SEC as f64)
262    }
263}
264
265impl Add for Duration {
266    type Output = Duration;
267
268    fn add(self, rhs: Duration) -> Self::Output {
269        let total_nanos = self.to_nanos() + rhs.to_nanos();
270        Duration::from_nanos(total_nanos)
271    }
272}
273
274impl Sub for Duration {
275    type Output = Duration;
276
277    fn sub(self, rhs: Duration) -> Self::Output {
278        let diff_nanos = self.to_nanos() - rhs.to_nanos();
279        Duration::from_nanos(diff_nanos)
280    }
281}
282
283impl Serialize for Duration {
284    fn serialize(&self, writer: &mut CdrWriter) -> Result<(), SerError> {
285        writer.write_i32(self.sec)?;
286        writer.write_u32(self.nanosec)?;
287        Ok(())
288    }
289}
290
291impl Deserialize for Duration {
292    fn deserialize(reader: &mut CdrReader) -> Result<Self, DeserError> {
293        Ok(Self {
294            sec: reader.read_i32()?,
295            nanosec: reader.read_u32()?,
296        })
297    }
298}
299
300#[cfg(test)]
301mod tests {
302    use super::*;
303
304    /// Stands in for a generated `builtin_interfaces/msg/Time`. This crate
305    /// cannot name the real one — that edge is the whole reason
306    /// [`SecNanosecMsg`] exists — so the trait's contract is checked here and
307    /// the CODEGEN side of it is checked where a generated crate is available
308    /// (`packages/testing/nros-tests/tests/time_to_ros_msg.rs`).
309    #[derive(Debug, PartialEq)]
310    struct FakeTimeMsg {
311        sec: i32,
312        nanosec: u32,
313    }
314
315    impl SecNanosecMsg for FakeTimeMsg {
316        fn from_sec_nanosec(sec: i32, nanosec: u32) -> Self {
317            Self { sec, nanosec }
318        }
319    }
320
321    #[test]
322    fn to_ros_msg_copies_both_fields_and_cannot_fail() {
323        let t = Time::new(1_234_567_890, 123_456_789);
324        // No `?`, no `.unwrap()`: the return type IS the message. Upstream's
325        // `Result` is upstream's `i64` narrowing, which ours does not do.
326        let msg: FakeTimeMsg = t.to_ros_msg();
327        assert_eq!(
328            msg,
329            FakeTimeMsg {
330                sec: 1_234_567_890,
331                nanosec: 123_456_789
332            }
333        );
334    }
335
336    #[test]
337    fn to_ros_msg_carries_a_pre_epoch_stamp_unchanged() {
338        // `sec` is signed and `nanosec` is not; a pre-epoch stamp is two field
339        // copies like any other, with no renormalisation on the way out.
340        let t = Time::new(-5, 999_999_999);
341        let msg: FakeTimeMsg = t.to_ros_msg();
342        assert_eq!(msg.sec, -5);
343        assert_eq!(msg.nanosec, 999_999_999);
344    }
345
346    #[test]
347    fn test_time_roundtrip() {
348        let mut buf = [0u8; 16];
349        let time = Time::new(1234567890, 123456789);
350
351        let mut writer = CdrWriter::new(&mut buf);
352        time.serialize(&mut writer).unwrap();
353
354        let mut reader = CdrReader::new(&buf);
355        let result = Time::deserialize(&mut reader).unwrap();
356        assert_eq!(result, time);
357    }
358
359    #[test]
360    fn test_duration_roundtrip() {
361        let mut buf = [0u8; 16];
362        let duration = Duration::new(-10, 500000000);
363
364        let mut writer = CdrWriter::new(&mut buf);
365        duration.serialize(&mut writer).unwrap();
366
367        let mut reader = CdrReader::new(&buf);
368        let result = Duration::deserialize(&mut reader).unwrap();
369        assert_eq!(result, duration);
370    }
371
372    #[test]
373    fn test_time_from_nanos() {
374        let time = Time::from_nanos(1_500_000_000);
375        assert_eq!(time.sec, 1);
376        assert_eq!(time.nanosec, 500_000_000);
377    }
378
379    #[test]
380    fn test_time_to_nanos() {
381        let time = Time::new(2, 500_000_000);
382        assert_eq!(time.to_nanos(), 2_500_000_000);
383    }
384
385    #[test]
386    fn test_time_add_duration() {
387        let time = Time::new(10, 500_000_000);
388        let duration = Duration::new(5, 700_000_000);
389        let result = time + duration;
390        assert_eq!(result.sec, 16);
391        assert_eq!(result.nanosec, 200_000_000);
392    }
393
394    #[test]
395    fn test_time_sub_duration() {
396        let time = Time::new(10, 500_000_000);
397        let duration = Duration::new(3, 200_000_000);
398        let result = time - duration;
399        assert_eq!(result.sec, 7);
400        assert_eq!(result.nanosec, 300_000_000);
401    }
402
403    #[test]
404    fn test_time_sub_time() {
405        let t1 = Time::new(10, 500_000_000);
406        let t2 = Time::new(7, 200_000_000);
407        let result = t1 - t2;
408        assert_eq!(result.sec, 3);
409        assert_eq!(result.nanosec, 300_000_000);
410    }
411
412    #[test]
413    fn test_time_from_duration() {
414        let duration = Duration::new(5, 123456789);
415        let time = Time::from_duration(duration);
416        assert_eq!(time.sec, 5);
417        assert_eq!(time.nanosec, 123456789);
418    }
419
420    #[test]
421    fn test_time_as_duration() {
422        let time = Time::new(5, 123456789);
423        let duration = time.as_duration();
424        assert_eq!(duration.sec, 5);
425        assert_eq!(duration.nanosec, 123456789);
426    }
427
428    #[test]
429    fn test_time_ordering() {
430        let t1 = Time::new(10, 0);
431        let t2 = Time::new(10, 500_000_000);
432        let t3 = Time::new(11, 0);
433        assert!(t1 < t2);
434        assert!(t2 < t3);
435    }
436
437    #[test]
438    fn test_duration_from_nanos() {
439        let duration = Duration::from_nanos(2_500_000_000);
440        assert_eq!(duration.sec, 2);
441        assert_eq!(duration.nanosec, 500_000_000);
442    }
443
444    #[test]
445    fn test_duration_to_nanos() {
446        let duration = Duration::new(3, 250_000_000);
447        assert_eq!(duration.to_nanos(), 3_250_000_000);
448    }
449
450    #[test]
451    fn test_duration_add() {
452        let d1 = Duration::new(2, 500_000_000);
453        let d2 = Duration::new(1, 700_000_000);
454        let result = d1 + d2;
455        assert_eq!(result.sec, 4);
456        assert_eq!(result.nanosec, 200_000_000);
457    }
458
459    #[test]
460    fn test_duration_sub() {
461        let d1 = Duration::new(5, 500_000_000);
462        let d2 = Duration::new(2, 200_000_000);
463        let result = d1 - d2;
464        assert_eq!(result.sec, 3);
465        assert_eq!(result.nanosec, 300_000_000);
466    }
467
468    #[test]
469    fn test_duration_ordering() {
470        let d1 = Duration::new(1, 0);
471        let d2 = Duration::new(1, 500_000_000);
472        let d3 = Duration::new(2, 0);
473        assert!(d1 < d2);
474        assert!(d2 < d3);
475    }
476
477    #[test]
478    fn test_time_secs_f64() {
479        let time = Time::from_secs_f64(1.5);
480        assert_eq!(time.sec, 1);
481        assert_eq!(time.nanosec, 500_000_000);
482
483        let secs = time.to_secs_f64();
484        assert!((secs - 1.5).abs() < 0.000001);
485    }
486
487    #[test]
488    fn test_duration_secs_f64() {
489        let duration = Duration::from_secs_f64(2.25);
490        assert_eq!(duration.sec, 2);
491        assert_eq!(duration.nanosec, 250_000_000);
492
493        let secs = duration.to_secs_f64();
494        assert!((secs - 2.25).abs() < 0.000001);
495    }
496}
497
498// =============================================================================
499// Kani bounded model checking proofs
500// =============================================================================
501
502#[cfg(kani)]
503mod verification {
504    use super::*;
505
506    // ---- Duration ----
507
508    #[kani::proof]
509    fn duration_from_nanos_no_panic() {
510        let nanos: i64 = kani::any();
511        // Constrain to tractable range for CBMC (i64 div/mod is expensive)
512        kani::assume(nanos >= -10_000_000_000 && nanos <= 10_000_000_000);
513        let dur = Duration::from_nanos(nanos);
514        // nanosec must always be in valid range
515        assert!(dur.nanosec < NANOS_PER_SEC as u32);
516    }
517
518    #[kani::proof]
519    fn duration_roundtrip_nanos() {
520        let nanos: i64 = kani::any();
521        // Constrain to tractable range for CBMC (i64 div/mod is expensive)
522        // Still covers multi-second values to exercise the div/mod logic
523        kani::assume(nanos >= 0 && nanos <= 10_000_000_000);
524        let dur = Duration::from_nanos(nanos);
525        assert_eq!(dur.to_nanos(), nanos);
526    }
527
528    #[kani::proof]
529    fn duration_zero_is_zero() {
530        let dur = Duration::zero();
531        assert!(dur.is_zero());
532        assert_eq!(dur.to_nanos(), 0);
533    }
534
535    #[kani::proof]
536    fn duration_from_secs() {
537        let secs: i32 = kani::any();
538        let dur = Duration::from_secs(secs);
539        assert_eq!(dur.sec, secs);
540        assert_eq!(dur.nanosec, 0);
541    }
542
543    #[kani::proof]
544    #[kani::unwind(5)]
545    fn duration_serialize_roundtrip() {
546        let sec: i32 = kani::any();
547        let nanosec: u32 = kani::any();
548        kani::assume(nanosec < NANOS_PER_SEC as u32);
549        let dur = Duration::new(sec, nanosec);
550
551        let mut buf = [0u8; 16];
552        let len = {
553            let mut writer = CdrWriter::new(&mut buf);
554            dur.serialize(&mut writer).unwrap();
555            writer.position()
556        };
557
558        let mut reader = CdrReader::new(&buf[..len]);
559        let deserialized = Duration::deserialize(&mut reader).unwrap();
560        assert_eq!(dur, deserialized);
561    }
562
563    // ---- Time ----
564
565    #[kani::proof]
566    fn time_from_nanos_no_panic() {
567        let nanos: i64 = kani::any();
568        // Constrain to tractable range for CBMC (i64 div/mod is expensive)
569        // NOTE: Negative nanos cause nanosec wrapping (known bug — Time::from_nanos
570        // lacks .unsigned_abs() unlike Duration::from_nanos). Constrain to >= 0.
571        kani::assume(nanos >= 0 && nanos <= 10_000_000_000);
572        let time = Time::from_nanos(nanos);
573        // nanosec must always be in valid range
574        assert!(time.nanosec < NANOS_PER_SEC as u32);
575    }
576
577    #[kani::proof]
578    fn time_roundtrip_nanos() {
579        let nanos: i64 = kani::any();
580        // Constrain to tractable range for CBMC (i64 div/mod is expensive)
581        kani::assume(nanos >= 0 && nanos <= 10_000_000_000);
582        let time = Time::from_nanos(nanos);
583        assert_eq!(time.to_nanos(), nanos);
584    }
585
586    #[kani::proof]
587    fn time_zero_is_zero() {
588        let time = Time::zero();
589        assert!(time.is_zero());
590        assert_eq!(time.to_nanos(), 0);
591    }
592
593    #[kani::proof]
594    fn time_duration_conversion() {
595        let sec: i32 = kani::any();
596        let nanosec: u32 = kani::any();
597        kani::assume(nanosec < NANOS_PER_SEC as u32);
598        let time = Time::new(sec, nanosec);
599        let dur = time.as_duration();
600        assert_eq!(dur.sec, time.sec);
601        assert_eq!(dur.nanosec, time.nanosec);
602        let back = Time::from_duration(dur);
603        assert_eq!(back, time);
604    }
605
606    #[kani::proof]
607    #[kani::unwind(5)]
608    fn time_serialize_roundtrip() {
609        let sec: i32 = kani::any();
610        let nanosec: u32 = kani::any();
611        kani::assume(nanosec < NANOS_PER_SEC as u32);
612        let time = Time::new(sec, nanosec);
613
614        let mut buf = [0u8; 16];
615        let len = {
616            let mut writer = CdrWriter::new(&mut buf);
617            time.serialize(&mut writer).unwrap();
618            writer.position()
619        };
620
621        let mut reader = CdrReader::new(&buf[..len]);
622        let deserialized = Time::deserialize(&mut reader).unwrap();
623        assert_eq!(time, deserialized);
624    }
625}