Skip to main content

line_protocol/
timestamp.rs

1use std::fmt::Write;
2use std::time::SystemTime;
3
4#[cfg(feature = "chrono")]
5use chrono::{DateTime, TimeZone};
6
7/// Defines a type that can be written as a line protocol timestamp.
8pub trait LineProtocolTimestamp {
9    /// Writes the value pair with a leading space.
10    fn write_value_with_space(&self, buffer: &mut String);
11}
12
13impl LineProtocolTimestamp for SystemTime {
14    fn write_value_with_space(&self, buffer: &mut String) {
15        let timestamp = self.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_nanos();
16        write!(buffer, " {}", timestamp).unwrap();
17    }
18}
19
20#[cfg(feature = "chrono")]
21impl<Tz> LineProtocolTimestamp for DateTime<Tz>
22where
23    Tz: TimeZone,
24{
25    fn write_value_with_space(&self, buffer: &mut String) {
26        let timestamp = self.timestamp_nanos_opt().unwrap();
27        write!(buffer, " {}", timestamp).unwrap();
28    }
29}