refix_message/value/
time_precision.rs1#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
3pub struct TimePrecision(u8);
4
5impl TimePrecision {
6 pub const SECONDS: Self = Self(0);
8 pub const MILLIS: Self = Self(3);
10 pub const MICROS: Self = Self(6);
12 pub const NANOS: Self = Self(9);
14
15 pub const fn from_fraction_digits(count: u8) -> Option<Self> {
17 if count <= 9 { Some(Self(count)) } else { None }
18 }
19
20 pub const fn fraction_digits(self) -> u8 {
22 self.0
23 }
24
25 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}