Skip to main content

laser_wire/filter/
coerce.rs

1use serde::{Deserialize, Serialize};
2use std::cmp::Ordering;
3
4const MICROS_PER_SECOND: i64 = 1_000_000;
5const MICROS_PER_MILLI: i64 = 1_000;
6const SECONDS_PER_DAY: i64 = 86_400;
7const MAX_DECIMAL_DIGITS: usize = 512;
8
9/// How a timestamp is written in the payload or literal.
10#[derive(
11    Clone,
12    Copy,
13    Debug,
14    PartialEq,
15    Eq,
16    Serialize,
17    Deserialize,
18    strum::Display,
19    strum::EnumString,
20    strum::VariantArray,
21)]
22#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
23#[serde(rename_all = "snake_case")]
24#[strum(serialize_all = "snake_case")]
25pub enum TimestampFormat {
26    /// RFC 3339 text with an explicit `Z` or `+hh:mm` offset. Fractions up to
27    /// nanoseconds are accepted when the digits past microseconds are zero.
28    Rfc3339,
29    /// Whole seconds since the Unix epoch, as a number or an integer string.
30    EpochSeconds,
31    /// Whole milliseconds since the Unix epoch.
32    EpochMillis,
33    /// Whole microseconds since the Unix epoch.
34    EpochMicros,
35}
36
37impl TimestampFormat {
38    /// Microseconds since the Unix epoch for a text value, `None` when the text
39    /// does not parse exactly under this format.
40    pub fn micros_from_text(self, text: &str) -> Option<i64> {
41        match self {
42            Self::Rfc3339 => rfc3339_micros(text),
43            Self::EpochSeconds | Self::EpochMillis | Self::EpochMicros => {
44                let value = parse_integer(text)?;
45                self.micros_from_integer(value)
46            }
47        }
48    }
49
50    /// Microseconds since the Unix epoch for an integer value, `None` for the
51    /// text-only RFC 3339 format and on overflow.
52    pub fn micros_from_integer(self, value: i128) -> Option<i64> {
53        let value = i64::try_from(value).ok()?;
54        match self {
55            Self::Rfc3339 => None,
56            Self::EpochSeconds => value.checked_mul(MICROS_PER_SECOND),
57            Self::EpochMillis => value.checked_mul(MICROS_PER_MILLI),
58            Self::EpochMicros => Some(value),
59        }
60    }
61}
62
63/// An exact decimal number, compared without floating-point rounding.
64///
65/// Built from decimal text (`-12.500`), an integer, or the shortest exact
66/// rendering of a finite `f64`. Leading and trailing zeros are normalized away,
67/// so `1.50` equals `1.5` and `-0` equals `0`.
68#[derive(Clone, Debug, PartialEq, Eq)]
69pub struct ExactDecimal {
70    negative: bool,
71    integer: String,
72    fraction: String,
73}
74
75impl ExactDecimal {
76    /// Parse `[+-]digits[.digits]`. No exponent, no surrounding whitespace, at
77    /// most 512 digits.
78    pub fn parse(text: &str) -> Option<Self> {
79        let (negative, unsigned) = match text.as_bytes().first()? {
80            b'-' => (true, &text[1..]),
81            b'+' => (false, &text[1..]),
82            _ => (false, text),
83        };
84        let (integer, fraction) = match unsigned.split_once('.') {
85            Some((integer, fraction)) => (integer, fraction),
86            None => (unsigned, ""),
87        };
88        if integer.is_empty() && fraction.is_empty() {
89            return None;
90        }
91        if integer.len() + fraction.len() > MAX_DECIMAL_DIGITS
92            || !integer.bytes().all(|byte| byte.is_ascii_digit())
93            || !fraction.bytes().all(|byte| byte.is_ascii_digit())
94            || (unsigned.contains('.') && fraction.is_empty())
95        {
96            return None;
97        }
98        Some(Self::normalized(negative, integer, fraction))
99    }
100
101    pub fn from_integer(value: i128) -> Self {
102        let digits = value.unsigned_abs().to_string();
103        Self::normalized(value < 0, &digits, "")
104    }
105
106    /// The shortest decimal that round-trips a finite double, so a JSON
107    /// number compares at `f64` precision. `None` for infinities and NaN.
108    pub fn from_f64(value: f64) -> Option<Self> {
109        if !value.is_finite() {
110            return None;
111        }
112        Self::parse(&value.to_string())
113    }
114
115    fn normalized(negative: bool, integer: &str, fraction: &str) -> Self {
116        let integer = integer.trim_start_matches('0').to_owned();
117        let fraction = fraction.trim_end_matches('0').to_owned();
118        let negative = negative && !(integer.is_empty() && fraction.is_empty());
119        Self {
120            negative,
121            integer,
122            fraction,
123        }
124    }
125
126    fn magnitude_cmp(&self, other: &Self) -> Ordering {
127        self.integer
128            .len()
129            .cmp(&other.integer.len())
130            .then_with(|| self.integer.cmp(&other.integer))
131            .then_with(|| self.fraction.cmp(&other.fraction))
132    }
133}
134
135impl Ord for ExactDecimal {
136    fn cmp(&self, other: &Self) -> Ordering {
137        match (self.negative, other.negative) {
138            (false, true) => Ordering::Greater,
139            (true, false) => Ordering::Less,
140            (false, false) => self.magnitude_cmp(other),
141            (true, true) => other.magnitude_cmp(self),
142        }
143    }
144}
145
146impl PartialOrd for ExactDecimal {
147    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
148        Some(self.cmp(other))
149    }
150}
151
152/// A decimal integer string: optional sign, digits only.
153pub(crate) fn parse_integer(text: &str) -> Option<i128> {
154    let digits = text.strip_prefix(['-', '+']).unwrap_or(text);
155    if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
156        return None;
157    }
158    text.parse::<i128>().ok()
159}
160
161fn rfc3339_micros(text: &str) -> Option<i64> {
162    let bytes = text.as_bytes();
163    if bytes.len() < 20 {
164        return None;
165    }
166    let year = digits_at(bytes, 0, 4)?;
167    let month = digits_at(bytes, 5, 2)?;
168    let day = digits_at(bytes, 8, 2)?;
169    let hour = digits_at(bytes, 11, 2)?;
170    let minute = digits_at(bytes, 14, 2)?;
171    let second = digits_at(bytes, 17, 2)?;
172    if bytes[4] != b'-'
173        || bytes[7] != b'-'
174        || !matches!(bytes[10], b'T' | b't')
175        || bytes[13] != b':'
176        || bytes[16] != b':'
177    {
178        return None;
179    }
180    if !(1..=12).contains(&month)
181        || day == 0
182        || day > days_in_month(year, month)
183        || hour > 23
184        || minute > 59
185        || second > 59
186    {
187        return None;
188    }
189    let mut position = 19;
190    let mut fraction_micros = 0i64;
191    if bytes.get(position) == Some(&b'.') {
192        position += 1;
193        let start = position;
194        while bytes.get(position).is_some_and(u8::is_ascii_digit) {
195            position += 1;
196        }
197        let fraction = &text[start..position];
198        if fraction.is_empty() || fraction.len() > 9 {
199            return None;
200        }
201        let (kept, dropped) = fraction.split_at(fraction.len().min(6));
202        if dropped.bytes().any(|byte| byte != b'0') {
203            return None;
204        }
205        let scale = 10i64.pow(u32::try_from(6 - kept.len()).ok()?);
206        fraction_micros = kept.parse::<i64>().ok()? * scale;
207    }
208    let offset_seconds = match bytes.get(position)? {
209        b'Z' | b'z' if position + 1 == bytes.len() => 0,
210        sign @ (b'+' | b'-') if position + 6 == bytes.len() => {
211            let offset_hour = digits_at(bytes, position + 1, 2)?;
212            let offset_minute = digits_at(bytes, position + 4, 2)?;
213            if bytes[position + 3] != b':' || offset_hour > 23 || offset_minute > 59 {
214                return None;
215            }
216            let magnitude = offset_hour * 3600 + offset_minute * 60;
217            if *sign == b'-' { -magnitude } else { magnitude }
218        }
219        _ => return None,
220    };
221    let days = days_from_civil(year, month, day);
222    let seconds = days
223        .checked_mul(SECONDS_PER_DAY)?
224        .checked_add(hour * 3600 + minute * 60 + second)?
225        .checked_sub(offset_seconds)?;
226    seconds
227        .checked_mul(MICROS_PER_SECOND)?
228        .checked_add(fraction_micros)
229}
230
231fn digits_at(bytes: &[u8], start: usize, len: usize) -> Option<i64> {
232    let slice = bytes.get(start..start + len)?;
233    slice.iter().try_fold(0i64, |value, byte| {
234        byte.is_ascii_digit()
235            .then(|| value * 10 + i64::from(byte - b'0'))
236    })
237}
238
239const fn is_leap_year(year: i64) -> bool {
240    (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
241}
242
243const fn days_in_month(year: i64, month: i64) -> i64 {
244    match month {
245        1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
246        4 | 6 | 9 | 11 => 30,
247        _ if is_leap_year(year) => 29,
248        _ => 28,
249    }
250}
251
252// Days since 1970-01-01 for a proleptic Gregorian date (H. Hinnant's algorithm).
253const fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
254    let year = if month <= 2 { year - 1 } else { year };
255    let era = if year >= 0 { year } else { year - 399 } / 400;
256    let year_of_era = year - era * 400;
257    let shifted_month = if month > 2 { month - 3 } else { month + 9 };
258    let day_of_year = (153 * shifted_month + 2) / 5 + day - 1;
259    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
260    era * 146_097 + day_of_era - 719_468
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266
267    #[test]
268    fn given_rfc3339_instants_when_parsed_then_should_normalize_to_utc_micros() {
269        let utc = TimestampFormat::Rfc3339
270            .micros_from_text("2026-09-21T18:04:12.331Z")
271            .expect("parses");
272        let offset = TimestampFormat::Rfc3339
273            .micros_from_text("2026-09-21T20:04:12.331000+02:00")
274            .expect("parses");
275        assert_eq!(utc, offset, "the same instant in two offsets is equal");
276        assert_eq!(
277            TimestampFormat::Rfc3339.micros_from_text("1970-01-01T00:00:00Z"),
278            Some(0)
279        );
280        assert_eq!(
281            TimestampFormat::Rfc3339.micros_from_text("1969-12-31T23:59:59.999999Z"),
282            Some(-1)
283        );
284    }
285
286    #[test]
287    fn given_ambiguous_or_lossy_rfc3339_when_parsed_then_should_be_rejected() {
288        for text in [
289            "2026-09-21T18:04:12.331000",
290            "2026-09-21 18:04:12Z",
291            "2026-02-29T00:00:00Z",
292            "2026-09-21T24:00:00Z",
293            "2026-09-21T18:04:60Z",
294            "2026-09-21T18:04:12.0000001Z",
295            "2026-09-21T18:04:12.Z",
296            "2026-09-21T18:04:12+2:00",
297        ] {
298            assert_eq!(
299                TimestampFormat::Rfc3339.micros_from_text(text),
300                None,
301                "`{text}` must be rejected"
302            );
303        }
304        assert_eq!(
305            TimestampFormat::Rfc3339.micros_from_text("2024-02-29T00:00:00.000000000Z"),
306            Some(1_709_164_800_000_000)
307        );
308    }
309
310    #[test]
311    fn given_epoch_units_when_coerced_then_should_scale_exactly() {
312        assert_eq!(
313            TimestampFormat::EpochSeconds.micros_from_integer(1_758_470_652),
314            Some(1_758_470_652_000_000)
315        );
316        assert_eq!(
317            TimestampFormat::EpochMillis.micros_from_text("1758470652331"),
318            Some(1_758_470_652_331_000)
319        );
320        assert_eq!(
321            TimestampFormat::EpochMicros.micros_from_integer(-5),
322            Some(-5)
323        );
324        assert_eq!(
325            TimestampFormat::EpochSeconds.micros_from_integer(i128::from(i64::MAX)),
326            None
327        );
328        assert_eq!(TimestampFormat::EpochMillis.micros_from_text("12.5"), None);
329    }
330
331    #[test]
332    fn given_decimals_when_compared_then_should_order_exactly() {
333        let parse = |text: &str| ExactDecimal::parse(text).expect("parses");
334        assert_eq!(parse("1.50"), parse("1.5"));
335        assert_eq!(parse("-0"), parse("0.000"));
336        assert!(parse("9007199254740993") > parse("9007199254740992"));
337        assert!(parse("-2") < parse("-1.999"));
338        assert!(parse("0.1") < parse("0.10001"));
339        assert!(parse("10") > parse("9.999999"));
340        assert_eq!(ExactDecimal::from_integer(-42), parse("-42.0"));
341        assert_eq!(ExactDecimal::from_f64(0.5), Some(parse("0.5")));
342    }
343
344    #[test]
345    fn given_malformed_decimals_when_parsed_then_should_be_rejected() {
346        for text in ["", "-", ".", "1.", "1e5", " 1", "1,5", "0x10", "--1"] {
347            assert_eq!(ExactDecimal::parse(text), None, "`{text}` must be rejected");
348        }
349        assert!(ExactDecimal::parse(".5").is_some());
350    }
351}