influxdb3_client/
precision.rs1use std::fmt;
2
3#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
8pub enum Precision {
9 #[default]
11 Nanosecond,
12 Microsecond,
14 Millisecond,
16 Second,
18}
19
20impl Precision {
21 pub fn as_str(self) -> &'static str {
23 match self {
24 Precision::Nanosecond => "nanosecond",
25 Precision::Microsecond => "microsecond",
26 Precision::Millisecond => "millisecond",
27 Precision::Second => "second",
28 }
29 }
30
31 pub(crate) fn nanos_per_unit(self) -> i64 {
33 match self {
34 Precision::Nanosecond => 1,
35 Precision::Microsecond => 1_000,
36 Precision::Millisecond => 1_000_000,
37 Precision::Second => 1_000_000_000,
38 }
39 }
40
41 pub(crate) fn scale_timestamp(self, nanos: i64) -> i64 {
43 nanos / self.nanos_per_unit()
44 }
45}
46
47impl fmt::Display for Precision {
48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49 f.write_str(self.as_str())
50 }
51}
52
53impl std::str::FromStr for Precision {
54 type Err = String;
55 fn from_str(s: &str) -> Result<Self, Self::Err> {
56 match s {
57 "nanosecond" | "ns" => Ok(Precision::Nanosecond),
58 "microsecond" | "us" | "µs" => Ok(Precision::Microsecond),
59 "millisecond" | "ms" => Ok(Precision::Millisecond),
60 "second" | "s" => Ok(Precision::Second),
61 other => Err(format!("unknown precision: {other}")),
62 }
63 }
64}
65
66#[cfg(test)]
67mod tests {
68 use super::*;
69
70 #[test]
71 fn api() {
72 let ns: i64 = 1_700_000_000_123_456_789;
73 for (p, scaled) in [
74 (Precision::Nanosecond, ns),
75 (Precision::Microsecond, ns / 1_000),
76 (Precision::Millisecond, ns / 1_000_000),
77 (Precision::Second, ns / 1_000_000_000),
78 ] {
79 assert_eq!(p.as_str().parse::<Precision>().unwrap(), p);
80 assert_eq!(p.scale_timestamp(ns), scaled);
81 }
82 }
83}