Debian Codegraph @

debian/rust-vendor/parse_datetime/src/items/epoch.rs

raw
1 // For the full copyright and license information, please view the LICENSE
2 // file that was distributed with this source code.
3
4 //! Parse a timestamp item.
5 //!
6 //! From the GNU docs:
7 //!
8 //! > If you precede a number with ‘@’, it represents an internal timestamp as
9 //! > a count of seconds. The number can contain an internal decimal point
10 //! > (either ‘.’ or ‘,’); any excess precision not supported by the internal
11 //! > representation is truncated toward minus infinity. Such a number cannot
12 //! > be combined with any other date item, as it specifies a complete
13 //! > timestamp.
14 //! >
15 //! > On most hosts, these counts ignore the presence of leap seconds. For
16 //! > example, on most hosts ‘@1483228799’ represents 2016-12-31 23:59:59 UTC,
17 //! > ‘@1483228800’ represents 2017-01-01 00:00:00 UTC, and there is no way to
18 //! > represent the intervening leap second 2016-12-31 23:59:60 UTC.
19
20 use winnow::{
21 ascii::digit1,
22 combinator::{opt, preceded},
23 token::one_of,
24 ModalResult, Parser,
25 };
26
27 use super::primitive::{dec_uint, plus_or_minus, s};
28
29 /// Represents a timestamp with nanosecond accuracy.
30 ///
31 /// # Invariants
32 ///
33 /// - `nanosecond` is always in the range of `0..1_000_000_000`.
34 /// - Negative timestamps are represented by a negative `second` value and a
35 /// positive `nanosecond` value.
36 #[derive(Debug, PartialEq, Clone, Copy)]
37 pub(super) struct Timestamp {
38 second: i64,
39 nanosecond: u32,
40 }
41
42 impl TryFrom<Timestamp> for jiff::Timestamp {
43 type Error = &'static str;
44
45 fn try_from(ts: Timestamp) -> Result<Self, Self::Error> {
46 jiff::Timestamp::new(
47 ts.second,
48 i32::try_from(ts.nanosecond).map_err(|_| "nanosecond in timestamp exceeds i32::MAX")?,
49 )
50 .map_err(|_| "timestamp value is out of valid range")
51 }
52 }
53
54 /// Parse a timestamp in the form of `@1234567890` or `@-1234567890.12345` or
55 /// `@1234567890,12345`.
56 pub(super) fn parse(input: &mut &str) -> ModalResult<Timestamp> {
57 (s("@"), opt(plus_or_minus), s(sec_and_nsec))
58 .verify_map(|(_, sign, (sec, nsec))| {
59 let sec = i64::try_from(sec).ok()?;
60 let (second, nanosecond) = match (sign, nsec) {
61 (Some('-'), 0) => (-sec, 0),
62 // Truncate towards minus infinity.
63 (Some('-'), _) => ((-sec).checked_sub(1)?, 1_000_000_000 - nsec),
64 _ => (sec, nsec),
65 };
66 Some(Timestamp { second, nanosecond })
67 })
68 .parse_next(input)
69 }
70
71 /// Parse a second value in the form of `1234567890` or `1234567890.12345` or
72 /// `1234567890,12345`.
73 ///
74 /// The first part represents whole seconds. The optional second part represents
75 /// fractional seconds, parsed as a nanosecond value from up to 9 digits
76 /// (padded with zeros on the right if fewer digits are present). If the second
77 /// part is omitted, it defaults to 0 nanoseconds.
78 pub(super) fn sec_and_nsec(input: &mut &str) -> ModalResult<(u64, u32)> {
79 (dec_uint, opt(preceded(one_of(['.', ',']), digit1)))
80 .verify_map(|(sec, opt_nsec_str)| match opt_nsec_str {
81 Some(nsec_str) if nsec_str.len() >= 9 => Some((sec, nsec_str[..9].parse().ok()?)),
82 Some(nsec_str) => {
83 let multiplier = 10_u32.pow(9 - nsec_str.len() as u32);
84 Some((sec, nsec_str.parse::<u32>().ok()?.checked_mul(multiplier)?))
85 }
86 None => Some((sec, 0)),
87 })
88 .parse_next(input)
89 }
90
91 #[cfg(test)]
92 mod tests {
93 use super::*;
94
95 fn ts(second: i64, nanosecond: u32) -> Timestamp {
96 Timestamp { second, nanosecond }
97 }
98
99 #[test]
100 fn parse_sec_and_nsec() {
101 for (input, expected) in [
102 ("1234567890", (1234567890, 0)), // only seconds
103 ("1234567890.12345", (1234567890, 123450000)), // seconds and nanoseconds, '.' as floating point
104 ("1234567890,12345", (1234567890, 123450000)), // seconds and nanoseconds, ',' as floating point
105 ("1234567890.1234567890123", (1234567890, 123456789)), // nanoseconds with more than 9 digits, truncated
106 ] {
107 let mut s = input;
108 assert_eq!(sec_and_nsec(&mut s).unwrap(), expected, "{input}");
109 }
110
111 for input in [
112 ".1234567890", // invalid: no leading seconds
113 "-1234567890", // invalid: negative input not allowed
114 ] {
115 let mut s = input;
116 assert!(sec_and_nsec(&mut s).is_err(), "{input}");
117 }
118 }
119
120 #[test]
121 fn timestamp() {
122 for (input, expected) in [
123 ("@1234567890", ts(1234567890, 0)), // positive seconds, no nanoseconds
124 ("@ 1234567890", ts(1234567890, 0)), // space after '@', positive seconds, no nanoseconds
125 ("@-1234567890", ts(-1234567890, 0)), // negative seconds, no nanoseconds
126 ("@ -1234567890", ts(-1234567890, 0)), // space after '@', negative seconds, no nanoseconds
127 ("@ - 1234567890", ts(-1234567890, 0)), // space after '@' and after '-', negative seconds, no nanoseconds
128 ("@1234567890.12345", ts(1234567890, 123450000)), // positive seconds with nanoseconds, '.' as floating point
129 ("@1234567890,12345", ts(1234567890, 123450000)), // positive seconds with nanoseconds, ',' as floating point
130 ("@-1234567890.12345", ts(-1234567891, 876550000)), // negative seconds with nanoseconds, '.' as floating point
131 ("@1234567890.1234567890123", ts(1234567890, 123456789)), // nanoseconds with more than 9 digits, truncated
132 ] {
133 let mut s = input;
134 assert_eq!(parse(&mut s).unwrap(), expected, "{input}");
135 }
136 }
137 }