Skip to main content

influxdb3_client/
precision.rs

1use std::fmt;
2
3/// Timestamp precision for write operations.
4///
5/// Matches the precision values accepted by the InfluxDB 3 write API.
6/// The default is [`Precision::Nanosecond`].
7#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
8pub enum Precision {
9    /// Nanoseconds (default)
10    #[default]
11    Nanosecond,
12    /// Microseconds
13    Microsecond,
14    /// Milliseconds
15    Millisecond,
16    /// Seconds
17    Second,
18}
19
20impl Precision {
21    /// Returns the API query-parameter string for this precision.
22    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    /// Number of nanoseconds in one unit of this precision.
32    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    /// Convert a nanosecond epoch timestamp to this precision.
42    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}