date_filter_search 0.1.0

A Rust library for parsing and filtering dates using relative and absolute time intervals. Useful for log filtering, search tools, and automation.
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
use chrono::{Datelike, Local, Timelike};
use regex::Regex;
use std::error::Error;
use std::fmt;

const YEAR_START: u16 = 1970;
const YEAR_END: u16 = 2100;

const UNIT_SECONDS: &str = "s";
const UNIT_MINUTES: &str = "m";
const UNIT_HOURS: &str = "h";
const UNIT_DAYS: &str = "D";
const UNIT_MONTHS: &str = "M";
const UNIT_YEARS: &str = "Y";

const UNIT_DELIMITER: &str = "to";

#[derive(Debug)]
pub struct DateTime {
    year: u16,
    month: u8,
    day: u8,
    hour: u8,
    minute: u8,
    second: u8,
}

#[derive(Debug)]
pub enum DateError {
    EmptyInput,
    InvalidDateFormat,
    InvalidRegex,
    OutOfRange(String),
    ParsingError(String),
    IncorrectUnit(String),
}

impl fmt::Display for DateError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let msg = match self {
            DateError::EmptyInput => "The input provided is empty.",
            DateError::InvalidDateFormat => "The date format is invalid.",
            DateError::InvalidRegex => "The regex pattern format is incorrect.",
            DateError::OutOfRange(detail) => return write!(f, "Value out of range: {}", detail),
            DateError::ParsingError(detail) => return write!(f, "Error parsing value: {}", detail),
            DateError::IncorrectUnit(unit) => {
                return write!(f, "Unrecognized unit of measurement: {}", unit)
            }
        };
        write!(f, "{}", msg)
    }
}

impl Error for DateError {}

/* ============================== Date Utility Functions ============================== */

// Gets the current date
fn get_current_date() -> DateTime {
    let now = Local::now();
    let dt = DateTime {
        year: now.year() as u16,
        month: now.month() as u8,
        day: now.day() as u8,
        hour: now.hour() as u8,
        minute: now.minute() as u8,
        second: now.second() as u8,
    };
    dt
}

// Returns the start date (min)
fn get_start_date() -> DateTime {
    DateTime {
        year: YEAR_START,
        month: 1,
        day: 1,
        hour: 0,
        minute: 0,
        second: 0,
    }
}

// Returns the end date (MAX)
fn get_end_date() -> DateTime {
    DateTime {
        year: YEAR_END,
        month: 12,
        day: 31,
        hour: 23,
        minute: 59,
        second: 59,
    }
}

// Check if a year is a leap year
fn leap_year(year: u16) -> bool {
    ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)
}

// Calculate the days of the month (considering leap years)
fn days_of_the_month(month: u8, year: u16) -> u8 {
    match month {
        4 | 6 | 9 | 11 => 30,
        2 => {
            if leap_year(year) {
                29
            } else {
                28
            }
        }
        _ => 31,
    }
}

// Converts a number of seconds (from YEAR_START) to a Date_Time structure
fn seconds_to_date(mut seconds: u64) -> DateTime {
    let mut dt = get_start_date();

    loop {
        let secs_in_year: u64 = if leap_year(dt.year) {
            366 * 86400
        } else {
            365 * 86400
        };

        if seconds < secs_in_year {
            break;
        }

        seconds -= secs_in_year;
        dt.year += 1;
    }
    loop {
        let secs_in_month: u64 = (days_of_the_month(dt.month, dt.year) as u64) * 86400;

        if seconds < secs_in_month {
            break;
        }
        seconds -= secs_in_month;
        dt.month += 1;
    }
    dt.day = ((seconds / 86400) + 1) as u8;
    seconds %= 86400;
    dt.hour = (seconds / 3600) as u8;
    seconds %= 3600;
    dt.minute = (seconds / 60) as u8;
    dt.second = (seconds % 60) as u8;
    dt
}

// Converts a Date_Time structure to seconds (from YEAR_START)
fn date_to_seconds(dt: DateTime) -> u64 {
    let mut seconds: u64 = 0;

    for y in YEAR_START..dt.year {
        seconds += if leap_year(y) {
            366 * 86400
        } else {
            365 * 86400
        };
    }

    for m in 1..dt.month {
        seconds += (days_of_the_month(m, dt.year) as u64) * 86400;
    }

    seconds += ((dt.day - 1) as u64) * 86400;
    seconds += (dt.hour as u64) * 3600;
    seconds += (dt.minute as u64) * 60;
    seconds += dt.second as u64;
    seconds
}

/* ============================== Functions to get "calendar" boundaries ============================== */

// Returns the date with time at the beginning of the day (00:00:00)
fn get_start_of_day(mut dt: DateTime) -> DateTime {
    dt.hour = 0;
    dt.minute = 0;
    dt.second = 0;
    dt
}

// Returns the date with day set to the first of the month (start of the month)
fn get_start_of_month(mut dt: DateTime) -> DateTime {
    dt.day = 1;
    dt.hour = 0;
    dt.minute = 0;
    dt.second = 0;
    dt
}

// Returns the date set to the first day of the year (start of the year)
fn get_start_of_year(mut dt: DateTime) -> DateTime {
    dt.month = 1;
    dt.day = 1;
    dt.hour = 0;
    dt.minute = 0;
    dt.second = 0;
    dt
}

/* ============================== Functions to "subtract" time ============================== */

// Subtract months from a given timestamp (in seconds)
fn subtract_months(now: u64, months: u64) -> u64 {
    let mut dt = seconds_to_date(now);
    let mut total_months = dt.year as u64 * 12 + dt.month as u64 - 1;
    total_months = total_months.saturating_sub(months);
    dt.year = (total_months / 12) as u16;
    dt.month = ((total_months % 12) + 1) as u8;
    let dim = days_of_the_month(dt.month, dt.year);
    if dt.day > dim {
        dt.day = dim;
    }
    date_to_seconds(dt)
}

// Subtract years from a given timestamp (in seconds)
fn subtract_years(now: u64, years: u64) -> u64 {
    let mut dt = seconds_to_date(now);
    dt.year = dt.year.saturating_sub(years as u16);
    let dim = days_of_the_month(dt.month, dt.year);
    if dt.day > dim {
        dt.day = dim;
    }
    date_to_seconds(dt)
}

// Subtract days from a given timestamp (in seconds)
fn subtract_days(now: u64, days: u64) -> u64 {
    now.saturating_sub(days * 86400)
}

/* ============================== Search Function ============================== */

// Returns 1 if target is between lowerBound and upperBound (inclusive), 0 otherwise.
pub fn search_generic(target: u64, lower_bound: u64, upper_bound: u64) -> bool {
    target >= lower_bound && target <= upper_bound
}

/* ============================== Validation function ============================== */

// Returns a structure containing a valid date/time.
fn validate_datetime(input: &str, default: bool) -> Result<DateTime, DateError> {
    let re = Regex::new(
        r"^(\d{4})(?:[\-_:;.,/\\|\s]+(\d{1,2}))?(?:[\-_:;.,/\\|\s]+(\d{1,2}))?(?:[\-_:;.,/\\|\s]+(\d{1,2}))?(?:[\-_:;.,/\\|\s]+(\d{1,2}))?(?:[\-_:;.,/\\|\s]+(\d{1,2}))?$",
    )
    .map_err(|_| DateError::InvalidRegex)?;

    let caps = re.captures(input).ok_or(DateError::InvalidDateFormat)?;

    let mut dt = if default {
        get_start_date()
    } else {
        get_end_date()
    };

    if let Some(y) = caps.get(1) {
        dt.year = y
            .as_str()
            .parse()
            .map_err(|e| DateError::ParsingError(format!("Year: {}", e)))?;
        if dt.year < YEAR_START || dt.year > YEAR_END {
            return Err(DateError::OutOfRange(format!(
                "The year must be between {} and {}.",
                YEAR_START, YEAR_END
            )));
        }
    }

    if let Some(m) = caps.get(2) {
        dt.month = m
            .as_str()
            .parse()
            .map_err(|e| DateError::ParsingError(format!("Month: {}", e)))?;
        if dt.month < 1 || dt.month > 12 {
            return Err(DateError::OutOfRange(
                "The month must be between 1 and 12.".to_string(),
            ));
        }
    }

    if let Some(d) = caps.get(3) {
        dt.day = d
            .as_str()
            .parse()
            .map_err(|e| DateError::ParsingError(format!("Day: {}", e)))?;
        let max_day = days_of_the_month(dt.month, dt.year);
        if dt.day < 1 || dt.day > max_day {
            return Err(DateError::OutOfRange(format!(
                "The day must be between 1 and {} for the month {}.",
                max_day, dt.month
            )));
        }
    }

    if let Some(h) = caps.get(4) {
        dt.hour = h
            .as_str()
            .parse()
            .map_err(|e| DateError::ParsingError(format!("Hour: {}", e)))?;
        if dt.hour > 23 {
            return Err(DateError::OutOfRange(
                "The hour must be between 0 and 23.".to_string(),
            ));
        }
    }

    if let Some(mi) = caps.get(5) {
        dt.minute = mi
            .as_str()
            .parse()
            .map_err(|e| DateError::ParsingError(format!("Minute: {}", e)))?;
        if dt.minute > 59 {
            return Err(DateError::OutOfRange(
                "The minutes must be between 0 and 59.".to_string(),
            ));
        }
    }

    if let Some(s) = caps.get(6) {
        dt.second = s
            .as_str()
            .parse()
            .map_err(|e| DateError::ParsingError(format!("Seconds: {}", e)))?;
        if dt.second > 59 {
            return Err(DateError::OutOfRange(
                "The seconds must be between 0 and 59.".to_string(),
            ));
        }
    }

    Ok(dt)
}

/* ============================== Parsing user input ============================== */

// Input is interpreted as a range or a single date.
fn parsing_search_absolute(input: &str) -> Result<(u64, u64), DateError> {
    let parts: Vec<&str> = input.splitn(2, UNIT_DELIMITER).map(|s| s.trim()).collect();
    let start_dt = validate_datetime(parts[0], true)?;
    let start = date_to_seconds(start_dt);

    let end = if parts.len() > 1 {
        let end_dt = validate_datetime(parts[1], false)?;
        date_to_seconds(end_dt)
    } else {
        let end_dt = validate_datetime(parts[0], false)?;
        date_to_seconds(end_dt)
    };

    Ok((start, end))
}

// Input must be of the type "<value><unit>"
fn parsing_search_relative(input: &str) -> Result<(u64, u64), DateError> {
    let re = Regex::new(r"^(\d+)\s*([A-Za-z])$").map_err(|_| DateError::InvalidRegex)?;
    let caps = re.captures(input).ok_or(DateError::InvalidDateFormat)?;

    let value: u64 = caps
        .get(1)
        .unwrap()
        .as_str()
        .parse()
        .map_err(|e| DateError::ParsingError(format!("Value: {}", e)))?;
    let unit = caps.get(2).unwrap().as_str();

    let now_dt = get_current_date();
    let start: u64 = match unit {
        UNIT_SECONDS => date_to_seconds(get_current_date()).saturating_sub(value),
        UNIT_MINUTES => date_to_seconds(get_current_date()).saturating_sub(value * 60),
        UNIT_HOURS => date_to_seconds(get_current_date()).saturating_sub(value * 3600),
        UNIT_DAYS => {
            let start_dt = get_start_of_day(now_dt);
            if value > 1 {
                let start_ts = subtract_days(date_to_seconds(start_dt), value - 1);
                date_to_seconds(get_start_of_day(seconds_to_date(start_ts)))
            } else {
                date_to_seconds(start_dt)
            }
        }
        UNIT_MONTHS => {
            let start_dt = get_start_of_month(now_dt);
            if value > 1 {
                let start_ts = subtract_months(date_to_seconds(start_dt), value - 1);
                date_to_seconds(get_start_of_month(seconds_to_date(start_ts)))
            } else {
                date_to_seconds(start_dt)
            }
        }
        UNIT_YEARS => {
            let start_dt = get_start_of_year(now_dt);
            if value > 1 {
                let start_ts = subtract_years(date_to_seconds(start_dt), value - 1);
                date_to_seconds(get_start_of_year(seconds_to_date(start_ts)))
            } else {
                date_to_seconds(start_dt)
            }
        }
        other => return Err(DateError::IncorrectUnit(other.to_string())),
    };

    let global_start = date_to_seconds(get_start_date());
    if start < global_start {
        return Err(DateError::OutOfRange(
            "The requested period is earlier than the minimum allowed date.".to_string(),
        ));
    }
    let end = date_to_seconds(get_current_date());
    Ok((start, end))
}

// input parsing
pub fn parsing_search(input: &str) -> Result<(u64, u64), DateError> {
    if input.trim().is_empty() {
        return Err(DateError::EmptyInput);
    }

    let pat = Regex::new(r"^(\d+)\s*([A-Za-z])$").unwrap();
    let (start, end);
    if let Some(_) = pat.captures(input) {
        (start, end) = parsing_search_relative(input)?;
    } else {
        (start, end) = parsing_search_absolute(input)?;
    }
    Ok((start, end))
}

/* ============================== Converting a string to Date_Time  ============================== */

// Converts a string to DATE_FORMAT and returns the seconds.
pub fn string_to_date_seconds(input: &str) -> Result<u64, DateError> {
    if input.trim().is_empty() {
        return Err(DateError::EmptyInput);
    }
    let dt = validate_datetime(input, true)?;
    Ok(date_to_seconds(dt))
}