timefilter 0.2.0

Human-readable time string parsing and filtering with comparison operators (e.g., ">=7d", "<2h", "2024-05-01")
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! Core types, constants, and parsing logic.
//!
//! All error strings live in `.rodata` — no heap `String` allocation
//! in error paths.

use std::error::Error;
use std::fmt;
use std::str::FromStr;

use chrono::{DateTime, Duration, Local, NaiveDateTime, Utc};

// ── TimeOp ───────────────────────────────────────────────────────────────────

/// Time comparison operator.
///
/// Mirrors [`sizefilter::SizeOp`](https://docs.rs/sizefilter) but is an
/// independent type — the two may evolve differently.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum TimeOp {
    /// Greater than (`>`)
    Gt,
    /// Greater than or equal to (`>=`)
    Ge,
    /// Less than (`<`)
    Lt,
    /// Less than or equal to (`<=`)
    Le,
    /// Equal to (`=`)
    Eq,
}

impl TimeOp {
    /// All variants, in declaration order.
    pub const ALL: [TimeOp; 5] = [TimeOp::Gt, TimeOp::Ge, TimeOp::Lt, TimeOp::Le, TimeOp::Eq];

    /// Apply this operator to two `DateTime<Utc>` values.
    #[inline]
    #[must_use]
    pub fn applies(self, value: DateTime<Utc>, threshold: DateTime<Utc>) -> bool {
        match self {
            TimeOp::Gt => value > threshold,
            TimeOp::Ge => value >= threshold,
            TimeOp::Lt => value < threshold,
            TimeOp::Le => value <= threshold,
            TimeOp::Eq => value == threshold,
        }
    }
}

impl fmt::Display for TimeOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            TimeOp::Gt => ">",
            TimeOp::Ge => ">=",
            TimeOp::Lt => "<",
            TimeOp::Le => "<=",
            TimeOp::Eq => "=",
        })
    }
}

// ── TimeFilter ───────────────────────────────────────────────────────────────

/// A time filter with operator (e.g., `>=7d`, `<2026-05-01`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct TimeFilter {
    op: TimeOp,
    time: DateTime<Utc>,
}

impl TimeFilter {
    /// Create a new filter from an operator and threshold time.
    #[inline]
    #[must_use]
    pub const fn new(op: TimeOp, time: DateTime<Utc>) -> Self {
        TimeFilter { op, time }
    }

    /// Get the comparison operator.
    #[inline]
    #[must_use]
    pub const fn op(self) -> TimeOp {
        self.op
    }

    /// Get the threshold time.
    #[inline]
    #[must_use]
    pub fn time(self) -> DateTime<Utc> {
        self.time
    }

    /// Filter: `value > threshold`.
    #[inline]
    #[must_use]
    pub const fn gt(time: DateTime<Utc>) -> Self {
        TimeFilter {
            op: TimeOp::Gt,
            time,
        }
    }

    /// Filter: `value >= threshold`.
    #[inline]
    #[must_use]
    pub const fn ge(time: DateTime<Utc>) -> Self {
        TimeFilter {
            op: TimeOp::Ge,
            time,
        }
    }

    /// Filter: `value < threshold`.
    #[inline]
    #[must_use]
    pub const fn lt(time: DateTime<Utc>) -> Self {
        TimeFilter {
            op: TimeOp::Lt,
            time,
        }
    }

    /// Filter: `value <= threshold`.
    #[inline]
    #[must_use]
    pub const fn le(time: DateTime<Utc>) -> Self {
        TimeFilter {
            op: TimeOp::Le,
            time,
        }
    }

    /// Filter: `value == threshold`.
    #[inline]
    #[must_use]
    pub const fn eq(time: DateTime<Utc>) -> Self {
        TimeFilter {
            op: TimeOp::Eq,
            time,
        }
    }

    /// Check whether `value` passes this filter.
    #[inline]
    #[must_use]
    pub fn matches(self, value: DateTime<Utc>) -> bool {
        self.op.applies(value, self.time)
    }
}

impl fmt::Display for TimeFilter {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}{}", self.op, format_datetime(&self.time))
    }
}

impl FromStr for TimeFilter {
    type Err = TimeError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        parse_time_filter(s)
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for TimeFilter {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        // Serialize as "op UTC_time" to preserve timezone
        serializer.collect_str(&format!(
            "{}{}",
            self.op,
            self.time.format("%Y-%m-%d %H:%M:%S")
        ))
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for TimeFilter {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let s = String::deserialize(deserializer)?;
        s.parse().map_err(serde::de::Error::custom)
    }
}

// ── TimeError ────────────────────────────────────────────────────────────────

/// Errors that can occur during time parsing and formatting.
///
/// All variants carry zero heap-allocated data — error strings are
/// `&'static str` literals in `.rodata`.
///
/// This enum is `#[non_exhaustive]` — new variants may be added in
/// minor releases without breaking changes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TimeError {
    /// Filter string lacks `>=`, `>`, `<=`, `<`, or `=` prefix.
    MissingOperator,
    /// Empty input string.
    EmptyInput,
    /// Unknown or unsupported time suffix.
    UnknownSuffix,
    /// Numeric value can't be parsed.
    InvalidNumber,
    /// Date/time string doesn't match expected format.
    InvalidDate,
}

impl fmt::Display for TimeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            TimeError::MissingOperator => {
                "time filter must start with an operator (>=, >, <=, <, =)"
            }
            TimeError::EmptyInput => "empty input",
            TimeError::UnknownSuffix => "unknown time suffix",
            TimeError::InvalidNumber => "failed to parse number",
            TimeError::InvalidDate => "failed to parse date/time",
        })
    }
}

impl Error for TimeError {}

/// `Result` type alias for `timefilter` operations.
pub type TimeResult<T> = Result<T, TimeError>;

// ── parsing ──────────────────────────────────────────────────────────────────

/// Parse a time filter string like `">=7d"`, `"<2h"`, `"=2026-05-01"`.
///
/// Operator is required — returns error if missing.
///
/// # Errors
///
/// Returns [`TimeError::MissingOperator`] if no operator is found,
/// or [`TimeError`] variants from time parsing.
pub fn parse_time_filter(s: &str) -> TimeResult<TimeFilter> {
    let s = s.trim();
    let prefixes: &[(&str, TimeOp)] = &[
        (">=", TimeOp::Ge),
        ("<=", TimeOp::Le),
        (">", TimeOp::Gt),
        ("<", TimeOp::Lt),
        ("=", TimeOp::Eq),
    ];
    let (op, rest) = prefixes
        .iter()
        .find_map(|&(prefix, op)| s.strip_prefix(prefix).map(|r| (op, r)))
        .ok_or(TimeError::MissingOperator)?;
    let time = parse_time(rest)?;
    Ok(TimeFilter { op, time })
}

/// Parse human-readable time string to `DateTime<Utc>`.
///
/// Supports relative formats:
/// - `"7d"`, `"7 days"` — days ago
/// - `"2h"`, `"2hr"` — hours ago
/// - `"30m"`, `"30min"` — minutes ago
/// - `"30s"` — seconds ago
///
/// And absolute formats:
/// - `"2024-05-01"` — date-only (midnight UTC)
/// - `"2024-05-01 10:00"` — date and hour:minute
/// - `"2024-05-01 10:00:00"` — date and hour:minute:second
///
/// # Errors
///
/// Returns [`TimeError::EmptyInput`], [`TimeError::UnknownSuffix`],
/// [`TimeError::InvalidNumber`], or [`TimeError::InvalidDate`].
pub fn parse_time(time_str: &str) -> TimeResult<DateTime<Utc>> {
    let s = time_str.trim();
    if s.is_empty() {
        return Err(TimeError::EmptyInput);
    }

    // Try relative time formats (suffix-based)
    if let Some(time) = try_parse_relative(s) {
        return Ok(time);
    }

    // Try absolute time formats
    try_parse_absolute(s)
}

fn try_parse_relative(s: &str) -> Option<DateTime<Utc>> {
    let duration = parse_duration_inner(s)?;
    Some(Utc::now() - duration)
}

/// Parse human-readable duration string to `Duration`.
///
/// Supports relative formats:
/// - `"7d"`, `"7 days"` — days
/// - `"2h"`, `"2hr"` — hours
/// - `"30m"`, `"30min"` — minutes
/// - `"30s"` — seconds
///
/// Also supports ISO 8601 duration format:
/// - `"P7D"` — 7 days
/// - `"PT2H"` — 2 hours
/// - `"P1DT12H"` — 1 day and 12 hours
///
/// ```
/// use timefilter::parse_duration;
/// use chrono::Duration;
///
/// // Human-readable formats
/// assert_eq!(parse_duration("7d").unwrap(), Duration::days(7));
/// assert_eq!(parse_duration("2h").unwrap(), Duration::hours(2));
/// assert_eq!(parse_duration("30m").unwrap(), Duration::minutes(30));
/// assert_eq!(parse_duration("30s").unwrap(), Duration::seconds(30));
///
/// // Verbose suffixes
/// assert_eq!(parse_duration("1 day").unwrap(), Duration::days(1));
/// assert_eq!(parse_duration("2 hours").unwrap(), Duration::hours(2));
///
/// // ISO 8601 duration format
/// assert_eq!(parse_duration("P7D").unwrap(), Duration::days(7));
/// assert_eq!(parse_duration("PT2H").unwrap(), Duration::hours(2));
/// assert_eq!(parse_duration("P1DT12H").unwrap(), Duration::days(1) + Duration::hours(12));
/// ```
///
/// # Errors
///
/// Returns [`TimeError::EmptyInput`], [`TimeError::UnknownSuffix`],
/// or [`TimeError::InvalidNumber`].
pub fn parse_duration(s: &str) -> TimeResult<Duration> {
    let s = s.trim();
    if s.is_empty() {
        return Err(TimeError::EmptyInput);
    }

    // Try ISO 8601 duration format first
    if s.starts_with('P') || s.starts_with('p') {
        return parse_iso8601_duration(s);
    }

    // Try human-readable format
    parse_duration_inner(s).ok_or(TimeError::UnknownSuffix)
}

fn parse_duration_inner(s: &str) -> Option<Duration> {
    // We need to split digits from suffix. Find where alphabetic part starts.
    let alpha_pos = s.find(|c: char| c.is_ascii_alphabetic())?;
    let (num_str, suffix) = s.split_at(alpha_pos);
    let num: i64 = num_str.trim().parse().ok()?;

    let suf = suffix.trim();
    if suf.eq_ignore_ascii_case("d")
        || suf.eq_ignore_ascii_case("day")
        || suf.eq_ignore_ascii_case("days")
    {
        Some(Duration::days(num))
    } else if suf.eq_ignore_ascii_case("h")
        || suf.eq_ignore_ascii_case("hr")
        || suf.eq_ignore_ascii_case("hour")
        || suf.eq_ignore_ascii_case("hours")
    {
        Some(Duration::hours(num))
    } else if suf.eq_ignore_ascii_case("m")
        || suf.eq_ignore_ascii_case("min")
        || suf.eq_ignore_ascii_case("minute")
        || suf.eq_ignore_ascii_case("minutes")
    {
        Some(Duration::minutes(num))
    } else if suf.eq_ignore_ascii_case("s")
        || suf.eq_ignore_ascii_case("sec")
        || suf.eq_ignore_ascii_case("second")
        || suf.eq_ignore_ascii_case("seconds")
    {
        Some(Duration::seconds(num))
    } else {
        None
    }
}

fn parse_iso8601_duration(s: &str) -> TimeResult<Duration> {
    // Trim leading 'P' (case-insensitive) without allocating
    let s = if s.as_bytes().first() == Some(&b'P') || s.as_bytes().first() == Some(&b'p') {
        &s[1..]
    } else {
        return Err(TimeError::UnknownSuffix);
    };

    if s.is_empty() {
        return Err(TimeError::InvalidNumber);
    }

    let mut total_seconds = 0i64;
    let mut num_start: Option<usize> = None;
    let mut in_time = false;
    let bytes = s.as_bytes();

    for (i, &b) in bytes.iter().enumerate() {
        match b {
            b'T' | b't' => {
                in_time = true;
                if num_start.is_some() {
                    return Err(TimeError::InvalidNumber);
                }
            }
            b'0'..=b'9' => {
                if num_start.is_none() {
                    num_start = Some(i);
                }
            }
            b'D' | b'd' => {
                let Some(start) = num_start.take() else {
                    return Err(TimeError::InvalidNumber);
                };
                let days: i64 = s[start..i].parse().map_err(|_| TimeError::InvalidNumber)?;
                total_seconds += days * 86400;
            }
            b'H' | b'h' => {
                let Some(start) = num_start.take() else {
                    return Err(TimeError::InvalidNumber);
                };
                if !in_time {
                    return Err(TimeError::InvalidNumber);
                }
                let hours: i64 = s[start..i].parse().map_err(|_| TimeError::InvalidNumber)?;
                total_seconds += hours * 3600;
            }
            b'M' | b'm' => {
                let Some(start) = num_start.take() else {
                    return Err(TimeError::InvalidNumber);
                };
                if !in_time {
                    return Err(TimeError::InvalidNumber);
                }
                let minutes: i64 = s[start..i].parse().map_err(|_| TimeError::InvalidNumber)?;
                total_seconds += minutes * 60;
            }
            b'S' | b's' => {
                let Some(start) = num_start.take() else {
                    return Err(TimeError::InvalidNumber);
                };
                if !in_time {
                    return Err(TimeError::InvalidNumber);
                }
                let seconds: i64 = s[start..i].parse().map_err(|_| TimeError::InvalidNumber)?;
                total_seconds += seconds;
            }
            _ => {
                return Err(TimeError::UnknownSuffix);
            }
        }
    }

    // If there's remaining unparsed number, it's an error
    if num_start.is_some() {
        return Err(TimeError::InvalidNumber);
    }

    // Must have parsed at least some duration
    if total_seconds == 0 {
        return Err(TimeError::InvalidNumber);
    }

    Ok(Duration::seconds(total_seconds))
}

fn try_parse_absolute(s: &str) -> TimeResult<DateTime<Utc>> {
    // "2024-05-01 10:00:00"
    if let Ok(naive) = NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M:%S") {
        return Ok(DateTime::from_naive_utc_and_offset(naive, Utc));
    }
    // "2024-05-01 10:00"
    if let Ok(naive) = NaiveDateTime::parse_from_str(s, "%Y-%m-%d %H:%M") {
        return Ok(DateTime::from_naive_utc_and_offset(naive, Utc));
    }
    // "2024-05-01" — parse as NaiveDate, then convert
    if let Ok(naive_date) = chrono::NaiveDate::parse_from_str(s, "%Y-%m-%d") {
        let Some(naive) = naive_date.and_hms_opt(0, 0, 0) else {
            return Err(TimeError::InvalidDate);
        };
        return Ok(DateTime::from_naive_utc_and_offset(naive, Utc));
    }
    Err(TimeError::InvalidDate)
}

// ── formatting ───────────────────────────────────────────────────────────────

/// Format a `DateTime<Utc>` for display in **local timezone**.
///
/// ```
/// use timefilter::format_datetime;
/// use chrono::{DateTime, NaiveDateTime, Utc};
///
/// let naive = NaiveDateTime::parse_from_str("2024-05-01 10:30:45", "%Y-%m-%d %H:%M:%S").unwrap();
/// let dt: DateTime<Utc> = DateTime::from_naive_utc_and_offset(naive, Utc);
/// let out = format_datetime(&dt);
/// assert!(out.contains("2024"));
/// ```
#[must_use]
pub fn format_datetime(dt: &DateTime<Utc>) -> String {
    dt.with_timezone(&Local)
        .format("%Y-%m-%d %H:%M:%S")
        .to_string()
}