herolib_otoml 0.3.13

OTOML - Canonical TOML serialization format with compact binary representation.
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
//! # otime - Canonical UTC Time Type
//!
//! A deterministic, minimal time type designed for:
//! - Stable serialization
//! - Easy human readability
//! - Compact binary storage (u32)
//! - Zero ambiguity across systems
//!
//! ## Format
//!
//! Text: `YYYY-MM-DD HH:MM:SS` (19 characters, fixed width)
//! Binary: `u32` (seconds since Unix epoch)
//!
//! ## Example
//!
//! ```rust
//! use herolib_otoml::OTime;
//!
//! // Create from epoch seconds
//! let time = OTime::from_epoch(1735689600);
//!
//! // Display as canonical string
//! assert_eq!(time.to_string(), "2025-01-01 00:00:00");
//!
//! // Parse from string
//! let parsed: OTime = "2025-01-01 00:00:00".parse().unwrap();
//! assert_eq!(parsed.epoch(), 1735689600);
//! ```

use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use std::str::FromStr;

use super::error::{OtomlError, Result};

/// Canonical UTC timestamp with second precision.
///
/// Internally stores seconds since Unix epoch as u32.
/// Text representation: `YYYY-MM-DD HH:MM:SS`
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OTime(u32);

impl OTime {
    /// Create an OTime from Unix epoch seconds.
    ///
    /// # Example
    /// ```
    /// use herolib_otoml::OTime;
    /// let time = OTime::from_epoch(0);
    /// assert_eq!(time.to_string(), "1970-01-01 00:00:00");
    /// ```
    pub fn from_epoch(seconds: u32) -> Self {
        OTime(seconds)
    }

    /// Get the Unix epoch seconds.
    pub fn epoch(&self) -> u32 {
        self.0
    }

    /// Create OTime from date and time components.
    ///
    /// Returns error if the date/time is invalid or out of range.
    pub fn from_components(
        year: u32,
        month: u32,
        day: u32,
        hour: u32,
        minute: u32,
        second: u32,
    ) -> Result<Self> {
        // Validate ranges
        if !(1970..=2106).contains(&year) {
            return Err(OtomlError::InvalidTime(format!(
                "year {} out of range (1970-2106)",
                year
            )));
        }
        if !(1..=12).contains(&month) {
            return Err(OtomlError::InvalidTime(format!(
                "month {} out of range (1-12)",
                month
            )));
        }
        if !(1..=31).contains(&day) {
            return Err(OtomlError::InvalidTime(format!(
                "day {} out of range (1-31)",
                day
            )));
        }
        if hour > 23 {
            return Err(OtomlError::InvalidTime(format!(
                "hour {} out of range (0-23)",
                hour
            )));
        }
        if minute > 59 {
            return Err(OtomlError::InvalidTime(format!(
                "minute {} out of range (0-59)",
                minute
            )));
        }
        if second > 59 {
            return Err(OtomlError::InvalidTime(format!(
                "second {} out of range (0-59)",
                second
            )));
        }

        // Validate day for month
        let days_in_month = days_in_month(year, month);
        if day > days_in_month {
            return Err(OtomlError::InvalidTime(format!(
                "day {} invalid for month {} (max {})",
                day, month, days_in_month
            )));
        }

        // Calculate epoch seconds
        let epoch = date_to_epoch(year, month, day, hour, minute, second);

        // Check for overflow (year 2106)
        if epoch > u32::MAX as u64 {
            return Err(OtomlError::InvalidTime(format!(
                "date {}-{:02}-{:02} exceeds u32 range",
                year, month, day
            )));
        }

        Ok(OTime(epoch as u32))
    }

    /// Get the date and time components.
    pub fn components(&self) -> (u32, u32, u32, u32, u32, u32) {
        epoch_to_date(self.0)
    }

    /// Get the current time.
    pub fn now() -> Self {
        use std::time::{SystemTime, UNIX_EPOCH};
        let secs = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        OTime((secs & 0xFFFFFFFF) as u32)
    }
}

impl Default for OTime {
    fn default() -> Self {
        OTime(0)
    }
}

impl fmt::Display for OTime {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (year, month, day, hour, minute, second) = self.components();
        write!(
            f,
            "{:04}-{:02}-{:02} {:02}:{:02}:{:02}",
            year, month, day, hour, minute, second
        )
    }
}

impl FromStr for OTime {
    type Err = OtomlError;

    fn from_str(s: &str) -> Result<Self> {
        // Expected format: YYYY-MM-DD HH:MM:SS (19 chars)
        let s = s.trim();
        if s.len() != 19 {
            return Err(OtomlError::InvalidTime(format!(
                "invalid length {}, expected 19 (YYYY-MM-DD HH:MM:SS)",
                s.len()
            )));
        }

        // Check separators
        let bytes = s.as_bytes();
        if bytes[4] != b'-'
            || bytes[7] != b'-'
            || bytes[10] != b' '
            || bytes[13] != b':'
            || bytes[16] != b':'
        {
            return Err(OtomlError::InvalidTime(format!(
                "invalid format, expected YYYY-MM-DD HH:MM:SS, got '{}'",
                s
            )));
        }

        // Parse components
        let year: u32 = s[0..4]
            .parse()
            .map_err(|_| OtomlError::InvalidTime("invalid year".to_string()))?;
        let month: u32 = s[5..7]
            .parse()
            .map_err(|_| OtomlError::InvalidTime("invalid month".to_string()))?;
        let day: u32 = s[8..10]
            .parse()
            .map_err(|_| OtomlError::InvalidTime("invalid day".to_string()))?;
        let hour: u32 = s[11..13]
            .parse()
            .map_err(|_| OtomlError::InvalidTime("invalid hour".to_string()))?;
        let minute: u32 = s[14..16]
            .parse()
            .map_err(|_| OtomlError::InvalidTime("invalid minute".to_string()))?;
        let second: u32 = s[17..19]
            .parse()
            .map_err(|_| OtomlError::InvalidTime("invalid second".to_string()))?;

        OTime::from_components(year, month, day, hour, minute, second)
    }
}

impl Serialize for OTime {
    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

impl<'de> Deserialize<'de> for OTime {
    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        OTime::from_str(&s).map_err(serde::de::Error::custom)
    }
}

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

/// Get the number of days in a month.
fn days_in_month(year: u32, month: u32) -> u32 {
    match month {
        1 => 31,
        2 => {
            if is_leap_year(year) {
                29
            } else {
                28
            }
        }
        3 => 31,
        4 => 30,
        5 => 31,
        6 => 30,
        7 => 31,
        8 => 31,
        9 => 30,
        10 => 31,
        11 => 30,
        12 => 31,
        _ => 0,
    }
}

/// Convert date components to Unix epoch seconds.
fn date_to_epoch(year: u32, month: u32, day: u32, hour: u32, minute: u32, second: u32) -> u64 {
    // Days since epoch
    let mut days: u64 = 0;

    // Add days for complete years
    for y in 1970..year {
        days += if is_leap_year(y) { 366 } else { 365 };
    }

    // Add days for complete months in current year
    for m in 1..month {
        days += days_in_month(year, m) as u64;
    }

    // Add days in current month (day is 1-indexed)
    days += (day - 1) as u64;

    // Convert to seconds
    days * 86400 + (hour as u64) * 3600 + (minute as u64) * 60 + (second as u64)
}

/// Convert Unix epoch seconds to date components.
fn epoch_to_date(epoch: u32) -> (u32, u32, u32, u32, u32, u32) {
    let mut remaining = epoch as u64;

    // Extract time components
    let second = (remaining % 60) as u32;
    remaining /= 60;
    let minute = (remaining % 60) as u32;
    remaining /= 60;
    let hour = (remaining % 24) as u32;
    let mut days = remaining / 24;

    // Find year
    let mut year = 1970u32;
    loop {
        let days_in_year = if is_leap_year(year) { 366 } else { 365 };
        if days < days_in_year {
            break;
        }
        days -= days_in_year;
        year += 1;
    }

    // Find month
    let mut month = 1u32;
    loop {
        let days_in_m = days_in_month(year, month) as u64;
        if days < days_in_m {
            break;
        }
        days -= days_in_m;
        month += 1;
    }

    // Day is 1-indexed
    let day = (days + 1) as u32;

    (year, month, day, hour, minute, second)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_epoch_zero() {
        let time = OTime::from_epoch(0);
        assert_eq!(time.to_string(), "1970-01-01 00:00:00");
        assert_eq!(time.epoch(), 0);
    }

    #[test]
    fn test_parse_and_format() {
        let time: OTime = "2025-01-03 14:22:59".parse().unwrap();
        assert_eq!(time.to_string(), "2025-01-03 14:22:59");
    }

    #[test]
    fn test_roundtrip() {
        let original = "2038-01-19 03:14:07";
        let time: OTime = original.parse().unwrap();
        assert_eq!(time.to_string(), original);
    }

    #[test]
    fn test_from_components() {
        let time = OTime::from_components(2025, 6, 15, 12, 30, 45).unwrap();
        let (year, month, day, hour, minute, second) = time.components();
        assert_eq!(year, 2025);
        assert_eq!(month, 6);
        assert_eq!(day, 15);
        assert_eq!(hour, 12);
        assert_eq!(minute, 30);
        assert_eq!(second, 45);
    }

    #[test]
    fn test_leap_year() {
        // Feb 29 in leap year should work
        let time = OTime::from_components(2024, 2, 29, 0, 0, 0).unwrap();
        assert_eq!(time.to_string(), "2024-02-29 00:00:00");

        // Feb 29 in non-leap year should fail
        let result = OTime::from_components(2025, 2, 29, 0, 0, 0);
        assert!(result.is_err());
    }

    #[test]
    fn test_invalid_format() {
        // Wrong length
        assert!("2025-01-03".parse::<OTime>().is_err());

        // Wrong separators
        assert!("2025/01/03 14:22:59".parse::<OTime>().is_err());
        assert!("2025-01-03T14:22:59".parse::<OTime>().is_err());

        // Invalid values
        assert!("2025-13-03 14:22:59".parse::<OTime>().is_err()); // month 13
        assert!("2025-01-32 14:22:59".parse::<OTime>().is_err()); // day 32
        assert!("2025-01-03 25:22:59".parse::<OTime>().is_err()); // hour 25
    }

    #[test]
    fn test_comparison() {
        let t1: OTime = "2025-01-01 00:00:00".parse().unwrap();
        let t2: OTime = "2025-01-02 00:00:00".parse().unwrap();
        assert!(t1 < t2);
        assert!(t2 > t1);
    }

    #[test]
    fn test_serde_roundtrip() {
        use serde::{Deserialize, Serialize};

        #[derive(Serialize, Deserialize, PartialEq, Debug)]
        struct Doc {
            created_at: OTime,
        }

        let doc = Doc {
            created_at: "2025-01-03 14:22:59".parse().unwrap(),
        };

        let otoml = crate::dump_otoml(&doc).unwrap();
        assert!(otoml.contains("created_at = \"2025-01-03 14:22:59\""));

        let parsed: Doc = crate::load_otoml(&otoml).unwrap();
        assert_eq!(doc, parsed);
    }

    #[test]
    fn test_y2038() {
        // Just before Y2K38
        let time: OTime = "2038-01-19 03:14:07".parse().unwrap();
        assert_eq!(time.epoch(), 2147483647); // i32::MAX

        // After Y2K38 (u32 can handle this)
        let time: OTime = "2038-01-19 03:14:08".parse().unwrap();
        assert_eq!(time.epoch(), 2147483648);
    }

    #[test]
    fn test_max_date() {
        // Year 2106 is the approximate limit for u32 epoch
        let time = OTime::from_components(2106, 2, 7, 6, 28, 15).unwrap();
        assert!(time.epoch() <= u32::MAX);
    }

    #[test]
    fn test_binary_roundtrip() {
        use serde::{Deserialize, Serialize};

        #[derive(Serialize, Deserialize, PartialEq, Debug)]
        struct Doc {
            created_at: OTime,
            updated_at: Option<OTime>,
        }

        let doc = Doc {
            created_at: "2025-01-03 14:22:59".parse().unwrap(),
            updated_at: Some("2025-06-15 10:00:00".parse().unwrap()),
        };

        let bytes = crate::dump_obin(&doc).unwrap();
        let parsed: Doc = crate::load_obin(&bytes).unwrap();

        assert_eq!(doc, parsed);
    }

    #[test]
    fn test_default() {
        let time = OTime::default();
        assert_eq!(time.epoch(), 0);
        assert_eq!(time.to_string(), "1970-01-01 00:00:00");
    }

    #[test]
    fn test_hash() {
        use std::collections::HashSet;

        let t1: OTime = "2025-01-01 00:00:00".parse().unwrap();
        let t2: OTime = "2025-01-01 00:00:00".parse().unwrap();
        let t3: OTime = "2025-01-02 00:00:00".parse().unwrap();

        let mut set = HashSet::new();
        set.insert(t1);
        set.insert(t2); // duplicate
        set.insert(t3);

        assert_eq!(set.len(), 2);
    }

    #[test]
    fn test_clone_and_copy() {
        let t1: OTime = "2025-01-01 00:00:00".parse().unwrap();
        let t2 = t1; // Copy
        let t3 = t1.clone();

        assert_eq!(t1, t2);
        assert_eq!(t1, t3);
    }

    #[test]
    fn test_invalid_component_ranges() {
        // Year before 1970
        assert!(OTime::from_components(1969, 12, 31, 23, 59, 59).is_err());

        // Year after 2106
        assert!(OTime::from_components(2107, 1, 1, 0, 0, 0).is_err());

        // Month 0 and 13
        assert!(OTime::from_components(2025, 0, 1, 0, 0, 0).is_err());
        assert!(OTime::from_components(2025, 13, 1, 0, 0, 0).is_err());

        // Day 0 and 32
        assert!(OTime::from_components(2025, 1, 0, 0, 0, 0).is_err());
        assert!(OTime::from_components(2025, 1, 32, 0, 0, 0).is_err());

        // Hour 24, minute 60, second 60
        assert!(OTime::from_components(2025, 1, 1, 24, 0, 0).is_err());
        assert!(OTime::from_components(2025, 1, 1, 0, 60, 0).is_err());
        assert!(OTime::from_components(2025, 1, 1, 0, 0, 60).is_err());
    }

    #[test]
    fn test_edge_dates() {
        // First second of 1970
        let t = OTime::from_components(1970, 1, 1, 0, 0, 0).unwrap();
        assert_eq!(t.epoch(), 0);

        // Last second of each month
        let months_with_31 = [1, 3, 5, 7, 8, 10, 12];
        for m in months_with_31 {
            assert!(OTime::from_components(2025, m, 31, 23, 59, 59).is_ok());
        }

        let months_with_30 = [4, 6, 9, 11];
        for m in months_with_30 {
            assert!(OTime::from_components(2025, m, 30, 23, 59, 59).is_ok());
            assert!(OTime::from_components(2025, m, 31, 0, 0, 0).is_err());
        }
    }

    #[test]
    fn test_century_leap_years() {
        // 2000 was a leap year (divisible by 400)
        assert!(OTime::from_components(2000, 2, 29, 0, 0, 0).is_ok());

        // 2100 is not a leap year (divisible by 100 but not 400)
        assert!(OTime::from_components(2100, 2, 29, 0, 0, 0).is_err());
        assert!(OTime::from_components(2100, 2, 28, 0, 0, 0).is_ok());
    }
}