foxglove 0.25.0

Foxglove SDK
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
//! Wrappers for protobuf well-known types
//!
//! For some reason, foxglove uses google's well-known types for representing Duration and
//! Timestamp in protobuf, even though we define those types differently. This module provides
//! an infallible translation from the foxglove message type to the underlying protobuf representation.
//!
//! This module lives outside `crate::messages`, because everything under the messages/ directory is
//! generated.

use crate::convert::{RangeError, SaturatingFrom};

#[cfg(feature = "chrono")]
mod chrono;
#[cfg(test)]
mod tests;

/// The result type for [`normalize_nsec`].
#[derive(Debug, PartialEq, Eq)]
enum NormalizeResult {
    /// Nanoseconds already within range.
    Ok(u32),
    /// Nanoseconds overflowed into seconds. Result is `(sec, nsec)`.
    Overflow(u32, u32),
}

/// Normalizes nsec to be on within range `[0, 1_000_000_000)`.
fn normalize_nsec(nsec: u32) -> NormalizeResult {
    if nsec < 1_000_000_000 {
        NormalizeResult::Ok(nsec)
    } else {
        let sec = nsec / 1_000_000_000;
        NormalizeResult::Overflow(sec, nsec % 1_000_000_000)
    }
}

impl NormalizeResult {
    /// Carries the result into an i32 representation of seconds.
    ///
    /// Returns None if the result overflows seconds.
    fn carry_i32(self, sec: i32) -> Option<(i32, u32)> {
        match self {
            Self::Ok(nsec) => Some((sec, nsec)),
            Self::Overflow(extra_sec, nsec) => {
                let Ok(extra_sec) = i32::try_from(extra_sec) else {
                    unreachable!("expected {extra_sec} to be within [0, 4]")
                };
                sec.checked_add(extra_sec).map(|sec| (sec, nsec))
            }
        }
    }

    /// Carries the result into a u32 representation of seconds.
    ///
    /// Returns None if the result overflows seconds.
    fn carry_u32(self, sec: u32) -> Option<(u32, u32)> {
        match self {
            Self::Ok(nsec) => Some((sec, nsec)),
            Self::Overflow(extra_sec, nsec) => sec.checked_add(extra_sec).map(|sec| (sec, nsec)),
        }
    }
}

/// A signed, fixed-length span of time.
///
/// The duration is represented by a count of seconds (which may be negative), and a count of
/// fractional seconds at nanosecond resolution (which are always positive).
///
/// # Example
///
/// ```
/// use foxglove::messages::Duration;
///
/// // A duration of 2.718... seconds.
/// let duration = Duration::new(2, 718_281_828);
///
/// // A duration of -3.14... seconds. Note that nanoseconds are always in the positive
/// // direction.
/// let duration = Duration::new(-4, 858_407_346);
/// ```
///
/// Various conversions are implemented. These conversions may fail with [`RangeError`], because
/// [`Duration`] represents a more restrictive range of values.
///
/// ```
/// # use foxglove::messages::Duration;
/// let duration: Duration = std::time::Duration::from_micros(577_215)
///     .try_into()
///     .unwrap();
/// assert_eq!(duration, Duration::new(0, 577_215_000));
///
/// #[cfg(feature = "chrono")]
/// {
///     let duration: Duration = chrono::TimeDelta::microseconds(1_414_213)
///         .try_into()
///         .unwrap();
///     assert_eq!(duration, Duration::new(1, 414_213_000));
/// }
/// ```
///
/// The [`SaturatingFrom`] and [`SaturatingInto`][crate::convert::SaturatingInto] traits may be
/// used to saturate when the range is exceeded.
///
/// ```
/// # use foxglove::messages::Duration;
/// use foxglove::convert::SaturatingInto;
///
/// let duration: Duration = std::time::Duration::from_secs(u64::MAX).saturating_into();
/// assert_eq!(duration, Duration::MAX);
/// ```
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, prost::Message)]
#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
pub struct Duration {
    /// Seconds offset.
    #[prost(int32, tag = "1")]
    sec: i32,
    /// Nanoseconds offset in the positive direction.
    #[prost(uint32, tag = "2")]
    nsec: u32,
}

impl Duration {
    /// Maximum representable duration.
    pub const MAX: Self = Self {
        sec: i32::MAX,
        nsec: 999_999_999,
    };

    /// Minimum representable duration.
    pub const MIN: Self = Self {
        sec: i32::MIN,
        nsec: 0,
    };

    /// Creates a new normalized duration.
    ///
    /// This constructor normalizes the duration by converting excess nanoseconds into seconds.
    ///
    /// Returns `None` if the attempt to convert excess nanoseconds causes `sec` to overflow.
    pub fn new_checked(sec: i32, nsec: u32) -> Option<Self> {
        normalize_nsec(nsec)
            .carry_i32(sec)
            .map(|(sec, nsec)| Self { sec, nsec })
    }

    /// Creates a new normalized duration.
    ///
    /// This constructor normalizes the duration by converting excess nanoseconds into seconds.
    ///
    /// Panics if the attempt to convert excess nanoseconds causes `sec` to overflow.
    pub fn new(sec: i32, nsec: u32) -> Self {
        Self::new_checked(sec, nsec).unwrap()
    }

    /// Returns the number of seconds in the duration.
    pub fn sec(&self) -> i32 {
        self.sec
    }

    /// Returns the number of fractional seconds in the duration, as nanoseconds.
    pub fn nsec(&self) -> u32 {
        self.nsec
    }

    /// Normalizes a duration.
    ///
    /// This is useful for a duration obtained through deserialization.
    ///
    /// Returns `None` if the attempt to convert excess nanoseconds causes `sec` to overflow.
    pub fn normalize(self) -> Option<Self> {
        Self::new_checked(self.sec, self.nsec)
    }

    /// Creates a `Duration` from `f64` seconds, or fails if the value is unrepresentable.
    pub fn try_from_secs_f64(secs: f64) -> Result<Self, RangeError> {
        if secs < f64::from(i32::MIN) {
            Err(RangeError::LowerBound)
        } else if secs >= f64::from(i32::MAX) + 1.0 {
            Err(RangeError::UpperBound)
        } else {
            let mut sec = secs as i32;
            let mut nsec = ((secs - f64::from(sec)) * 1e9) as i32;
            if nsec < 0 {
                sec -= 1;
                nsec += 1_000_000_000;
            }
            Ok(Self::new(
                sec,
                u32::try_from(nsec).unwrap_or_else(|e| {
                    unreachable!("expected {nsec} to be within [0, 1_000_000_000): {e}")
                }),
            ))
        }
    }

    /// Saturating `Duration` from `f64` seconds.
    pub fn saturating_from_secs_f64(secs: f64) -> Self {
        match Self::try_from_secs_f64(secs) {
            Ok(d) => d,
            Err(RangeError::LowerBound) => Duration::MIN,
            Err(RangeError::UpperBound) => Duration::MAX,
        }
    }
}

impl From<Duration> for prost_types::Duration {
    fn from(v: Duration) -> Self {
        Self {
            seconds: i64::from(v.sec),
            nanos: i32::try_from(v.nsec).unwrap_or_else(|e| {
                unreachable!("expected {} to be within [0, 1_000_000_000): {e}", v.nsec)
            }),
        }
    }
}

impl TryFrom<std::time::Duration> for Duration {
    type Error = RangeError;

    fn try_from(duration: std::time::Duration) -> Result<Self, Self::Error> {
        let Ok(sec) = i32::try_from(duration.as_secs()) else {
            return Err(RangeError::UpperBound);
        };
        let nsec = duration.subsec_nanos();
        Ok(Self { sec, nsec })
    }
}

impl<T> SaturatingFrom<T> for Duration
where
    Self: TryFrom<T, Error = RangeError>,
{
    fn saturating_from(value: T) -> Self {
        match Self::try_from(value) {
            Ok(d) => d,
            Err(RangeError::LowerBound) => Duration::MIN,
            Err(RangeError::UpperBound) => Duration::MAX,
        }
    }
}

/// A timestamp, represented as an offset from a user-defined epoch.
///
/// # Example
///
/// ```
/// use foxglove::messages::Timestamp;
///
/// let timestamp = Timestamp::new(1_548_054_420, 76_657_283);
/// ```
///
/// Various conversions are implemented, which presume the choice of the unix epoch as the
/// reference time. These conversions may fail with [`RangeError`], because [`Timestamp`]
/// represents a more restrictive range of values.
///
/// ```
/// # use foxglove::messages::Timestamp;
/// let timestamp = Timestamp::try_from(std::time::SystemTime::UNIX_EPOCH).unwrap();
/// assert_eq!(timestamp, Timestamp::MIN);
///
/// #[cfg(feature = "chrono")]
/// {
///     let timestamp = Timestamp::try_from(chrono::DateTime::UNIX_EPOCH).unwrap();
///     assert_eq!(timestamp, Timestamp::MIN);
///     let timestamp = Timestamp::try_from(chrono::NaiveDateTime::UNIX_EPOCH).unwrap();
///     assert_eq!(timestamp, Timestamp::MIN);
/// }
/// ```
///
/// The [`SaturatingFrom`] and [`SaturatingInto`][crate::convert::SaturatingInto] traits may be
/// used to saturate when the range is exceeded.
///
/// ```
/// # use foxglove::messages::Timestamp;
/// use foxglove::convert::SaturatingInto;
///
/// let timestamp: Timestamp = std::time::SystemTime::UNIX_EPOCH
///     .checked_sub(std::time::Duration::from_secs(1))
///     .unwrap()
///     .saturating_into();
/// assert_eq!(timestamp, Timestamp::MIN);
/// ```
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, prost::Message)]
#[cfg_attr(feature = "serde", derive(::serde::Serialize, ::serde::Deserialize))]
pub struct Timestamp {
    /// Seconds since epoch.
    #[prost(uint32, tag = "1")]
    sec: u32,
    /// Additional nanoseconds since epoch.
    #[prost(uint32, tag = "2")]
    nsec: u32,
}

impl Timestamp {
    /// Maximum representable timestamp.
    pub const MAX: Self = Self {
        sec: u32::MAX,
        nsec: 999_999_999,
    };

    /// Minimum representable timestamp.
    pub const MIN: Self = Self { sec: 0, nsec: 0 };

    /// Creates a new normalized timestamp.
    ///
    /// This constructor normalizes the timestamp by converting excess nanoseconds into seconds.
    ///
    /// Returns `None` if the attempt to convert excess nanoseconds causes `sec` to overflow.
    pub fn new_checked(sec: u32, nsec: u32) -> Option<Self> {
        normalize_nsec(nsec)
            .carry_u32(sec)
            .map(|(sec, nsec)| Self { sec, nsec })
    }

    /// Creates a new normalized timestamp.
    ///
    /// This constructor normalizes the timestamp by converting excess nanoseconds into seconds.
    ///
    /// Panics if the attempt to convert excess nanoseconds causes `sec` to overflow.
    pub fn new(sec: u32, nsec: u32) -> Self {
        Self::new_checked(sec, nsec).unwrap()
    }

    /// Returns the current timestamp using [`SystemTime::now`][std::time::SystemTime::now].
    pub fn now() -> Self {
        let now = std::time::SystemTime::now();
        Self::try_from(now).expect("timestamp out of range")
    }

    /// Returns the number of seconds in the timestamp.
    pub fn sec(&self) -> u32 {
        self.sec
    }

    /// Returns the number of fractional seconds in the timestamp, as nanoseconds.
    pub fn nsec(&self) -> u32 {
        self.nsec
    }

    /// Returns the Timestamp as the total number of nanoseconds (sec() * 1B + nsec()).
    pub fn total_nanos(&self) -> u64 {
        u64::from(self.sec) * 1_000_000_000 + u64::from(self.nsec)
    }

    /// Normalizes a timestamp.
    ///
    /// This is useful for a timestamp obtained through deserialization.
    ///
    /// Returns `None` if the attempt to convert excess nanoseconds causes `sec` to overflow.
    pub fn normalize(self) -> Option<Self> {
        Self::new_checked(self.sec, self.nsec)
    }

    /// Creates a `Timestamp` from seconds since epoch as an `f64`, or fails if the value is
    /// unrepresentable.
    pub fn try_from_epoch_secs_f64(secs: f64) -> Result<Self, RangeError> {
        if secs < 0.0 {
            Err(RangeError::LowerBound)
        } else if secs >= f64::from(u32::MAX) + 1.0 {
            Err(RangeError::UpperBound)
        } else {
            let sec = secs as u32;
            let nsec = ((secs - f64::from(sec)) * 1e9) as u32;
            Ok(Self::new(sec, nsec))
        }
    }

    /// Saturating `Timestamp` from seconds since epoch as an `f64`.
    pub fn saturating_from_epoch_secs_f64(secs: f64) -> Self {
        match Self::try_from_epoch_secs_f64(secs) {
            Ok(d) => d,
            Err(RangeError::LowerBound) => Timestamp::MIN,
            Err(RangeError::UpperBound) => Timestamp::MAX,
        }
    }
}

impl From<Timestamp> for prost_types::Timestamp {
    fn from(v: Timestamp) -> Self {
        Self {
            seconds: i64::from(v.sec),
            nanos: i32::try_from(v.nsec).unwrap_or_else(|e| {
                unreachable!("expected {} to be within [0, 1_000_000_000): {e}", v.nsec)
            }),
        }
    }
}

impl TryFrom<std::time::SystemTime> for Timestamp {
    type Error = RangeError;

    fn try_from(time: std::time::SystemTime) -> Result<Self, Self::Error> {
        let Ok(duration) = time.duration_since(std::time::UNIX_EPOCH) else {
            return Err(RangeError::LowerBound);
        };
        let Ok(sec) = u32::try_from(duration.as_secs()) else {
            return Err(RangeError::UpperBound);
        };
        let nsec = duration.subsec_nanos();
        Ok(Self::new(sec, nsec))
    }
}

impl<T> SaturatingFrom<T> for Timestamp
where
    Self: TryFrom<T, Error = RangeError>,
{
    fn saturating_from(value: T) -> Self {
        match Self::try_from(value) {
            Ok(d) => d,
            Err(RangeError::LowerBound) => Timestamp::MIN,
            Err(RangeError::UpperBound) => Timestamp::MAX,
        }
    }
}

#[cfg(test)]
mod test {
    use bytes::BytesMut;
    use prost::Message;

    use super::*;

    #[test]
    fn test_timestamp_decode() {
        let timestamp = Timestamp {
            sec: 1750000000,
            nsec: 99999,
        };

        let mut buf = BytesMut::new();
        timestamp.encode(&mut buf).unwrap();
        let decoded = Timestamp::decode(buf).unwrap();

        assert_eq!(timestamp, decoded);
    }

    #[test]
    fn test_duration_decode() {
        let duration = Duration {
            sec: 1,
            nsec: 99999,
        };

        let mut buf = BytesMut::new();
        duration.encode(&mut buf).unwrap();
        let decoded = Duration::decode(buf).unwrap();

        assert_eq!(duration, decoded);
    }
}