Skip to main content

refix_message/value/
time_precision.rs

1/// How finely a time is written, as its count of fraction digits.
2#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
3pub struct TimePrecision(u8);
4
5impl TimePrecision {
6    /// No fraction, as in `14:29:51`.
7    pub const SECONDS: Self = Self(0);
8    /// Three digits, as in `14:29:51.123`.
9    pub const MILLIS: Self = Self(3);
10    /// Six digits.
11    pub const MICROS: Self = Self(6);
12    /// Nine digits.
13    pub const NANOS: Self = Self(9);
14
15    /// The precision of a fraction with `count` digits, up to nine.
16    pub const fn from_fraction_digits(count: u8) -> Option<Self> {
17        if count <= 9 { Some(Self(count)) } else { None }
18    }
19
20    /// The number of fraction digits, such as `3` for `MILLIS`.
21    pub const fn fraction_digits(self) -> u8 {
22        self.0
23    }
24
25    /// Nanoseconds in one unit, such as `1_000_000` for `MILLIS`.
26    pub(crate) const fn unit_nanos(self) -> i64 {
27        10_i64.pow(9 - self.0 as u32)
28    }
29}
30
31#[cfg(test)]
32mod tests {
33    use super::*;
34
35    #[test]
36    fn allows_up_to_nine_digits() {
37        assert_eq!(
38            TimePrecision::from_fraction_digits(9),
39            Some(TimePrecision::NANOS)
40        );
41        assert_eq!(TimePrecision::from_fraction_digits(10), None);
42    }
43
44    #[test]
45    fn names_the_common_precisions() {
46        for (precision, digits) in [
47            (TimePrecision::SECONDS, 0),
48            (TimePrecision::MILLIS, 3),
49            (TimePrecision::MICROS, 6),
50            (TimePrecision::NANOS, 9),
51        ] {
52            assert_eq!(precision.fraction_digits(), digits);
53        }
54    }
55
56    #[test]
57    fn scales_one_unit_to_nanos() {
58        let tenths_of_millis = TimePrecision::from_fraction_digits(4).unwrap();
59        assert_eq!(TimePrecision::SECONDS.unit_nanos(), 1_000_000_000);
60        assert_eq!(tenths_of_millis.unit_nanos(), 100_000);
61        assert_eq!(TimePrecision::NANOS.unit_nanos(), 1);
62    }
63}