timeglyph 0.7.0

Forensic timestamp decipherment — decode, encode, and identify the many ways systems inscribe time, with scored, cited, ambiguity-first interpretation.
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
//! The forensic format registry — the ENGINE half of the knowledge/engine split.
//!
//! The authoritative catalog of the 45 formats (ids, labels, epochs, tick units,
//! tz/leap semantics, and packed-layout tags) lives in
//! [`forensicnomicon::temporal_formats`] (a zero-dep, clean-room, primary-source
//! knowledge table). This module is the decoder: it owns the calendar math for
//! the 16 packed bit-field layouts — FAT/DOS, exFAT, DTTM, BitDate/BitDec, BCD/GSM
//! semi-octet, Motorola, Symantec, DVR, NS40/NS40LE, LogTime, Nokia LE, SQL Server
//! — and builds [`FORMATS`] by wrapping each catalog entry in an engine [`Format`]
//! with the matching [`crate::PackedCodec`]. The SYSTEMTIME packed and
//! ULID/UUIDv1/RFC-2822/EXIF string forms live in `interpret.rs`; the leap-aware
//! GPS/NTP/TAI scales in `leap.rs`. Each packed codec is cross-validated against
//! the MIT `time-decode` oracle (tests/oracle.rs, tests/catalog.rs), and
//! `tests/docs_sync.rs` fails the build if a format drifts out of
//! `docs/validation.md`.

use crate::{ChronoError, Format, PackedCodec, PosixNs};
use forensicnomicon::temporal_formats::{Encoding, PackedLayout, SQLSERVER_EPOCH_NS, TIME_FORMATS};
use std::sync::LazyLock;

/// Unpack a 32-bit FAT/DOS packed date+time into an instant. The high 16 bits
/// are the date word (`(year-1980) << 9 | month << 5 | day`), the low 16 are the
/// time word (`hour << 11 | minute << 5 | second/2`, i.e. 2-second resolution).
/// FAT stores LOCAL time with no offset; the value is read as a naive civil
/// datetime (the [`Format`] carries `LocalNaive` so callers are not misled).
/// Invalid packed fields (month 0, day 0, …) surface as an error, never a panic.
fn decode_fat_dos(value: i64) -> Result<PosixNs, ChronoError> {
    let packed = u32::try_from(value).map_err(|_| ChronoError::OutOfRange {
        what: "FAT/DOS packed value (not a u32)",
        value: i128::from(value),
    })?;
    let date = (packed >> 16) as u16;
    let time = (packed & 0xFFFF) as u16;
    let year = 1980 + ((date >> 9) & 0x7F) as i16;
    let month = ((date >> 5) & 0x0F) as i8;
    let day = (date & 0x1F) as i8;
    let hour = ((time >> 11) & 0x1F) as i8;
    let minute = ((time >> 5) & 0x3F) as i8;
    let second = ((time & 0x1F) * 2) as i8;
    let dt = jiff::civil::DateTime::new(year, month, day, hour, minute, second, 0)
        .map_err(|e| ChronoError::Render(e.to_string()))?;
    let ts = dt
        .to_zoned(jiff::tz::TimeZone::UTC)
        // cov:unreachable: to_zoned(UTC) of an already-valid civil datetime cannot fail.
        .map_err(|e| ChronoError::Render(e.to_string()))?
        .timestamp();
    Ok(PosixNs(ts.as_nanosecond()))
}

/// Build an instant from packed civil fields read as naive UTC (the [`Format`]
/// carries `LocalNaive` so callers know it is wall-clock, not real UTC). Invalid
/// fields surface as an error, never a panic. Shared by the packed decoders.
fn packed_civil(
    year: i16,
    month: i8,
    day: i8,
    hour: i8,
    minute: i8,
    second: i8,
) -> Result<PosixNs, ChronoError> {
    let dt = jiff::civil::DateTime::new(year, month, day, hour, minute, second, 0)
        .map_err(|e| ChronoError::Render(e.to_string()))?;
    let ts = dt
        .to_zoned(jiff::tz::TimeZone::UTC)
        // cov:unreachable: to_zoned(UTC) of an already-valid civil datetime cannot fail.
        .map_err(|e| ChronoError::Render(e.to_string()))?
        .timestamp();
    Ok(PosixNs(ts.as_nanosecond()))
}

/// The inverse of [`packed_civil`]: the UTC civil fields (year, month, day,
/// hour, minute, second) of an instant. Packed formats store naive wall-clock,
/// so the fields are read in UTC. Shared by the packed encoders.
fn civil_fields(instant: PosixNs) -> Result<(i16, i8, i8, i8, i8, i8), ChronoError> {
    let ts = jiff::Timestamp::from_nanosecond(instant.0)
        .map_err(|e| ChronoError::Render(e.to_string()))?;
    let dt = jiff::tz::Offset::UTC.to_datetime(ts);
    Ok((
        dt.year(),
        dt.month(),
        dt.day(),
        dt.hour(),
        dt.minute(),
        dt.second(),
    ))
}

/// Inverse of [`decode_fat_dos`]: pack an instant into the FAT/DOS date+time
/// word pair (`date << 16 | time`). LOCAL naive, 2-second granularity; the year
/// must fit the 7-bit field (1980–2107).
fn encode_fat_dos(instant: PosixNs) -> Result<i64, ChronoError> {
    let (year, month, day, hour, minute, second) = civil_fields(instant)?;
    if !(1980..=2107).contains(&year) {
        return Err(ChronoError::OutOfRange {
            what: "FAT/DOS year (1980-2107)",
            value: i128::from(year),
        });
    }
    let date = (u32::from((year - 1980) as u16) << 9)
        | (u32::from(month as u8) << 5)
        | u32::from(day as u8);
    let time = (u32::from(hour as u8) << 11)
        | (u32::from(minute as u8) << 5)
        | u32::from((second / 2) as u8);
    Ok(i64::from((date << 16) | time))
}

/// exFAT 32-bit packed timestamp (MSB-first): year(7,+1980) month(4) day(5)
/// hour(5) minute(6) 2-second(5). LOCAL time. [Microsoft exFAT spec]
fn decode_exfat(value: i64) -> Result<PosixNs, ChronoError> {
    let p = u32::try_from(value).map_err(|_| ChronoError::OutOfRange {
        what: "exFAT packed value (not a u32)",
        value: i128::from(value),
    })?;
    packed_civil(
        1980 + ((p >> 25) & 0x7F) as i16,
        ((p >> 21) & 0x0F) as i8,
        ((p >> 16) & 0x1F) as i8,
        ((p >> 11) & 0x1F) as i8,
        ((p >> 5) & 0x3F) as i8,
        ((p & 0x1F) * 2) as i8,
    )
}

/// Inverse of [`decode_exfat`]: pack an instant into the exFAT 32-bit word
/// (MSB-first year(7,+1980) month(4) day(5) hour(5) minute(6) 2-second(5)).
/// LOCAL naive, 2-second granularity; the year must fit the 7-bit field
/// (1980–2107).
fn encode_exfat(instant: PosixNs) -> Result<i64, ChronoError> {
    let (year, month, day, hour, minute, second) = civil_fields(instant)?;
    if !(1980..=2107).contains(&year) {
        return Err(ChronoError::OutOfRange {
            what: "exFAT year (1980-2107)",
            value: i128::from(year),
        });
    }
    let p = (u32::from((year - 1980) as u16) << 25)
        | (u32::from(month as u8) << 21)
        | (u32::from(day as u8) << 16)
        | (u32::from(hour as u8) << 11)
        | (u32::from(minute as u8) << 5)
        | u32::from((second / 2) as u8);
    Ok(i64::from(p))
}

/// Microsoft DTTM 32-bit packed date (MSB-first): dayOfWeek(3, ignored)
/// year(9,+1900) month(4) day(5) hour(5) minute(6); no seconds. LOCAL time.
fn decode_dttm(value: i64) -> Result<PosixNs, ChronoError> {
    let p = u32::try_from(value).map_err(|_| ChronoError::OutOfRange {
        what: "DTTM packed value (not a u32)",
        value: i128::from(value),
    })?;
    packed_civil(
        1900 + ((p >> 20) & 0x1FF) as i16,
        ((p >> 16) & 0x0F) as i8,
        ((p >> 11) & 0x1F) as i8,
        ((p >> 6) & 0x1F) as i8,
        (p & 0x3F) as i8,
        0,
    )
}

/// Inverse of [`decode_dttm`]: pack an instant into the DTTM 32-bit word
/// (MSB-first year(9,+1900) month(4) day(5) hour(5) minute(6); no seconds).
/// LOCAL naive. dayOfWeek(3) is display-only and is written as 0. The year must
/// fit the 9-bit field (1900–2411).
fn encode_dttm(instant: PosixNs) -> Result<i64, ChronoError> {
    let (year, month, day, hour, minute, _second) = civil_fields(instant)?;
    if !(1900..=2411).contains(&year) {
        return Err(ChronoError::OutOfRange {
            what: "DTTM year (1900-2411)",
            value: i128::from(year),
        });
    }
    let p = (u32::from((year - 1900) as u16) << 20)
        | (u32::from(month as u8) << 16)
        | (u32::from(day as u8) << 11)
        | (u32::from(hour as u8) << 6)
        | u32::from(minute as u8);
    Ok(i64::from(p))
}

/// Samsung/LG BitDate: the 4 bytes are byte-reversed, then MSB-first year(12)
/// month(4) day(5) hour(5) minute(6); no seconds. LOCAL time.
fn decode_bitdate(value: i64) -> Result<PosixNs, ChronoError> {
    let p = u32::try_from(value)
        .map_err(|_| ChronoError::OutOfRange {
            what: "BitDate packed value (not a u32)",
            value: i128::from(value),
        })?
        .swap_bytes();
    packed_civil(
        ((p >> 20) & 0xFFF) as i16,
        ((p >> 16) & 0x0F) as i8,
        ((p >> 11) & 0x1F) as i8,
        ((p >> 6) & 0x1F) as i8,
        (p & 0x3F) as i8,
        0,
    )
}

/// Inverse of [`decode_bitdate`]: pack an instant MSB-first (year(12) month(4)
/// day(5) hour(5) minute(6); no seconds), then byte-reverse — the same
/// `swap_bytes` the decoder applies, so encode∘decode is identity. LOCAL naive.
/// The year must fit the 12-bit field (0–4095).
fn encode_bitdate(instant: PosixNs) -> Result<i64, ChronoError> {
    let (year, month, day, hour, minute, _second) = civil_fields(instant)?;
    if !(0..=4095).contains(&year) {
        return Err(ChronoError::OutOfRange {
            what: "BitDate year (0-4095)",
            value: i128::from(year),
        });
    }
    let p = (u32::from(year as u16) << 20)
        | (u32::from(month as u8) << 16)
        | (u32::from(day as u8) << 11)
        | (u32::from(hour as u8) << 6)
        | u32::from(minute as u8);
    Ok(i64::from(p.swap_bytes()))
}

/// Bitwise Decimal: a decimal value bit-packed year(>>20) month(&15 at >>16)
/// day(&31 at >>11) hour(&31 at >>6) minute(&63); no seconds. LOCAL time.
fn decode_bitdec(value: i64) -> Result<PosixNs, ChronoError> {
    if value < 0 {
        return Err(ChronoError::OutOfRange {
            what: "Bitwise Decimal value (negative)",
            value: i128::from(value),
        });
    }
    packed_civil(
        i16::try_from(value >> 20).map_err(|_| ChronoError::OutOfRange {
            what: "Bitwise Decimal year",
            value: i128::from(value),
        })?,
        ((value >> 16) & 15) as i8,
        ((value >> 11) & 31) as i8,
        ((value >> 6) & 31) as i8,
        (value & 63) as i8,
        0,
    )
}

/// Inverse of [`decode_bitdec`]: bit-pack the civil fields into a decimal value
/// (year(<<20) month(<<16,&15) day(<<11,&31) hour(<<6,&31) minute(&63); no
/// seconds). LOCAL naive. The year must be non-negative and fit the decoder's
/// `i16` year field (0–32767).
fn encode_bitdec(instant: PosixNs) -> Result<i64, ChronoError> {
    let (year, month, day, hour, minute, _second) = civil_fields(instant)?;
    if year < 0 {
        return Err(ChronoError::OutOfRange {
            what: "Bitwise Decimal year (non-negative)",
            value: i128::from(year),
        });
    }
    Ok((i64::from(year) << 20)
        | (i64::from(month) << 16)
        | (i64::from(day) << 11)
        | (i64::from(hour) << 6)
        | i64::from(minute))
}

/// Binary-Coded-Decimal: 12 decimal digits as pairs YY(+2000) MM DD HH MM SS,
/// LOCAL time. The value is read as its zero-padded 12-digit decimal string.
fn decode_bcd(value: i64) -> Result<PosixNs, ChronoError> {
    if !(0..1_000_000_000_000).contains(&value) {
        return Err(ChronoError::OutOfRange {
            what: "BCD value (not 12 decimal digits)",
            value: i128::from(value),
        });
    }
    let s = format!("{value:012}");
    let pair = |i: usize| -> i8 { s[i..i + 2].parse().unwrap_or(-1) };
    packed_civil(
        2000 + i16::from(pair(0)),
        pair(2),
        pair(4),
        pair(6),
        pair(8),
        pair(10),
    )
}

/// Inverse of [`decode_bcd`]: render the civil fields as the 12-digit decimal
/// value YY(year-2000) MM DD HH MM SS. LOCAL naive. The year must fit the
/// 2-digit YY field (2000–2099).
fn encode_bcd(instant: PosixNs) -> Result<i64, ChronoError> {
    let (year, month, day, hour, minute, second) = civil_fields(instant)?;
    if !(2000..=2099).contains(&year) {
        return Err(ChronoError::OutOfRange {
            what: "BCD year (2000-2099)",
            value: i128::from(year),
        });
    }
    let s = format!(
        "{:02}{:02}{:02}{:02}{:02}{:02}",
        year - 2000,
        month,
        day,
        hour,
        minute,
        second
    );
    s.parse().map_err(|_| ChronoError::OutOfRange {
        // cov:unreachable: six 2-digit fields always form a valid 12-digit i64.
        what: "BCD packed value",
        value: i128::from(year),
    })
}

/// Motorola 6-byte timestamp: one byte per field — year(+1970) month day hour
/// minute second. UTC.
fn decode_moto(value: i64) -> Result<PosixNs, ChronoError> {
    let v = u64::try_from(value)
        .ok()
        .filter(|v| *v <= 0xFFFF_FFFF_FFFF)
        .ok_or(ChronoError::OutOfRange {
            what: "Motorola (not a 6-byte value)",
            value: i128::from(value),
        })?;
    let byte = |sh: u32| ((v >> sh) & 0xFF) as i8;
    packed_civil(
        1970 + i16::from(((v >> 40) & 0xFF) as u8),
        byte(32),
        byte(24),
        byte(16),
        byte(8),
        byte(0),
    )
}

/// Symantec AV 6-byte timestamp: like Motorola, but the month byte is +1. UTC.
fn decode_symantec(value: i64) -> Result<PosixNs, ChronoError> {
    let v = u64::try_from(value)
        .ok()
        .filter(|v| *v <= 0xFFFF_FFFF_FFFF)
        .ok_or(ChronoError::OutOfRange {
            what: "Symantec (not a 6-byte value)",
            value: i128::from(value),
        })?;
    let byte = |sh: u32| ((v >> sh) & 0xFF) as i8;
    packed_civil(
        1970 + i16::from(((v >> 40) & 0xFF) as u8),
        byte(32).wrapping_add(1),
        byte(24),
        byte(16),
        byte(8),
        byte(0),
    )
}

/// DVR (WFS/DHFS) 32-bit packed timestamp (MSB-first): year(6,+2000) month(4)
/// day(5) hour(5) minute(6) second(6). LOCAL time.
fn decode_dvr(value: i64) -> Result<PosixNs, ChronoError> {
    let p = u32::try_from(value).map_err(|_| ChronoError::OutOfRange {
        what: "DVR packed value (not a u32)",
        value: i128::from(value),
    })?;
    packed_civil(
        2000 + ((p >> 26) & 0x3F) as i16,
        ((p >> 22) & 0x0F) as i8,
        ((p >> 17) & 0x1F) as i8,
        ((p >> 12) & 0x1F) as i8,
        ((p >> 6) & 0x3F) as i8,
        (p & 0x3F) as i8,
    )
}

/// Nokia S40 7-byte timestamp: year(BE u16) then month/day/hour/minute/second,
/// each a raw byte value. UTC.
fn decode_ns40(value: i64) -> Result<PosixNs, ChronoError> {
    let v = u64::try_from(value)
        .ok()
        .filter(|v| *v <= 0xFF_FFFF_FFFF_FFFF)
        .ok_or(ChronoError::OutOfRange {
            what: "Nokia S40 (not a 7-byte value)",
            value: i128::from(value),
        })?;
    let byte = |sh: u32| ((v >> sh) & 0xFF) as i8;
    let yr = i16::try_from((v >> 40) & 0xFFFF).map_err(|_| ChronoError::OutOfRange {
        what: "Nokia S40 year",
        value: i128::from(value),
    })?;
    packed_civil(yr, byte(32), byte(24), byte(16), byte(8), byte(0))
}

/// Nokia S40 LE: like ns40 but the year u16 is little-endian. UTC.
fn decode_ns40le(value: i64) -> Result<PosixNs, ChronoError> {
    let v = u64::try_from(value)
        .ok()
        .filter(|v| *v <= 0xFF_FFFF_FFFF_FFFF)
        .ok_or(ChronoError::OutOfRange {
            what: "Nokia S40 LE (not a 7-byte value)",
            value: i128::from(value),
        })?;
    let byte = |sh: u32| ((v >> sh) & 0xFF) as i8;
    let yr = i16::try_from((((v >> 40) & 0xFFFF) as u16).swap_bytes()).map_err(|_| {
        ChronoError::OutOfRange {
            what: "Nokia S40 LE year",
            value: i128::from(value),
        }
    })?;
    packed_civil(yr, byte(32), byte(24), byte(16), byte(8), byte(0))
}

/// Inverse of [`decode_moto`]: 6 bytes, MSB-first,
/// `[year-1970][month][day][hour][minute][second]`. LOCAL naive; year 1970–2225.
fn encode_moto(instant: PosixNs) -> Result<i64, ChronoError> {
    let (year, month, day, hour, minute, second) = civil_fields(instant)?;
    let yb = u8::try_from(year - 1970).map_err(|_| ChronoError::OutOfRange {
        what: "Motorola year (1970-2225)",
        value: i128::from(year),
    })?;
    let v = (u64::from(yb) << 40)
        | (u64::from(month as u8) << 32)
        | (u64::from(day as u8) << 24)
        | (u64::from(hour as u8) << 16)
        | (u64::from(minute as u8) << 8)
        | u64::from(second as u8);
    Ok(v as i64)
}

/// Inverse of [`decode_symantec`]: like Motorola, but the month byte stores
/// month-1 (0-based). LOCAL naive; year 1970–2225.
fn encode_symantec(instant: PosixNs) -> Result<i64, ChronoError> {
    let (year, month, day, hour, minute, second) = civil_fields(instant)?;
    let yb = u8::try_from(year - 1970).map_err(|_| ChronoError::OutOfRange {
        what: "Symantec year (1970-2225)",
        value: i128::from(year),
    })?;
    let v = (u64::from(yb) << 40)
        | (u64::from((month - 1) as u8) << 32)
        | (u64::from(day as u8) << 24)
        | (u64::from(hour as u8) << 16)
        | (u64::from(minute as u8) << 8)
        | u64::from(second as u8);
    Ok(v as i64)
}

/// Inverse of [`decode_dvr`]: u32 (MSB-first) year(6,+2000) month(4) day(5)
/// hour(5) minute(6) second(6). LOCAL naive; year 2000–2063.
fn encode_dvr(instant: PosixNs) -> Result<i64, ChronoError> {
    let (year, month, day, hour, minute, second) = civil_fields(instant)?;
    if !(2000..=2063).contains(&year) {
        return Err(ChronoError::OutOfRange {
            what: "DVR year (2000-2063)",
            value: i128::from(year),
        });
    }
    let p = (u32::from((year - 2000) as u8) << 26)
        | (u32::from(month as u8) << 22)
        | (u32::from(day as u8) << 17)
        | (u32::from(hour as u8) << 12)
        | (u32::from(minute as u8) << 6)
        | u32::from(second as u8);
    Ok(i64::from(p))
}

/// Inverse of [`decode_ns40`]: 7 bytes, MSB-first — a big-endian year u16 then
/// `[month][day][hour][minute][second]`. LOCAL naive.
fn encode_ns40(instant: PosixNs) -> Result<i64, ChronoError> {
    let (year, month, day, hour, minute, second) = civil_fields(instant)?;
    let yr = u16::try_from(year).map_err(|_| ChronoError::OutOfRange {
        what: "Nokia S40 year (0-65535)",
        value: i128::from(year),
    })?;
    let v = (u64::from(yr) << 40)
        | (u64::from(month as u8) << 32)
        | (u64::from(day as u8) << 24)
        | (u64::from(hour as u8) << 16)
        | (u64::from(minute as u8) << 8)
        | u64::from(second as u8);
    Ok(v as i64)
}

/// Inverse of [`decode_ns40le`]: like Nokia S40, but the year u16 is stored
/// little-endian. LOCAL naive.
fn encode_ns40le(instant: PosixNs) -> Result<i64, ChronoError> {
    let (year, month, day, hour, minute, second) = civil_fields(instant)?;
    let yr = u16::try_from(year).map_err(|_| ChronoError::OutOfRange {
        what: "Nokia S40 LE year (0-65535)",
        value: i128::from(year),
    })?;
    let v = (u64::from(yr.swap_bytes()) << 40)
        | (u64::from(month as u8) << 32)
        | (u64::from(day as u8) << 24)
        | (u64::from(hour as u8) << 16)
        | (u64::from(minute as u8) << 8)
        | u64::from(second as u8);
    Ok(v as i64)
}

/// JET LogTime 8-byte timestamp, reversed field order: sec min hour day month
/// year(+1900), then 2 filler bytes. UTC.
fn decode_logtime(value: i64) -> Result<PosixNs, ChronoError> {
    let v = u64::try_from(value).map_err(|_| ChronoError::OutOfRange {
        what: "JET LogTime (negative)",
        value: i128::from(value),
    })?;
    let byte = |sh: u32| ((v >> sh) & 0xFF) as i8;
    let yr = 1900 + ((v >> 16) & 0xFF) as i16;
    packed_civil(yr, byte(24), byte(32), byte(40), byte(48), byte(56))
}

/// Inverse of [`decode_logtime`]: pack an instant into the JET LogTime u64. The
/// year is stored as a single (year − 1900) byte, so 1900–2155 is the range.
fn encode_logtime(instant: PosixNs) -> Result<i64, ChronoError> {
    let (year, month, day, hour, minute, second) = civil_fields(instant)?;
    if !(1900..=2155).contains(&year) {
        return Err(ChronoError::OutOfRange {
            what: "JET LogTime year (1900-2155)",
            value: i128::from(year),
        });
    }
    let yb = u64::from((year - 1900) as u16);
    let v = (yb << 16)
        | (u64::from(month as u8) << 24)
        | (u64::from(day as u8) << 32)
        | (u64::from(hour as u8) << 40)
        | (u64::from(minute as u8) << 48)
        | (u64::from(second as u8) << 56);
    Ok(v as i64)
}

/// Decode one nibble-swapped semi-octet byte/pair to its decimal value, or -1
/// (an invalid field that `packed_civil` will reject) when a nibble exceeds 9.
fn semi_pair(low: u8, high: u8) -> i8 {
    i8::try_from(low * 10 + high).unwrap_or(-1)
}

/// Semi-Octet decimal: 12 digits, each pair nibble-swapped → YY(+2000) MM DD HH
/// MM SS. LOCAL time.
fn decode_semioctet(value: i64) -> Result<PosixNs, ChronoError> {
    if !(0..1_000_000_000_000).contains(&value) {
        return Err(ChronoError::OutOfRange {
            what: "Semi-Octet (not 12 decimal digits)",
            value: i128::from(value),
        });
    }
    let s = format!("{value:012}");
    let b = s.as_bytes();
    let pair = |i: usize| semi_pair(b[i + 1] - b'0', b[i] - b'0');
    packed_civil(
        2000 + i16::from(pair(0)),
        pair(2),
        pair(4),
        pair(6),
        pair(8),
        pair(10),
    )
}

/// Nibble-swap a 2-digit decimal field (0..=99) into its semi-octet encoding:
/// `decode` reads it as `ones*10 + tens`, so swapping the digits inverts it.
fn semi_swap(field: i8) -> u64 {
    let f = field as u64;
    (f % 10) * 10 + (f / 10)
}

/// Inverse of [`decode_semioctet`]: a 12-digit decimal, each 2-digit field
/// nibble-swapped, YY(+2000) MM DD HH MM SS. Range is 2000–2099.
fn encode_semioctet(instant: PosixNs) -> Result<i64, ChronoError> {
    let (year, month, day, hour, minute, second) = civil_fields(instant)?;
    if !(2000..=2099).contains(&year) {
        return Err(ChronoError::OutOfRange {
            what: "Semi-Octet year (2000-2099)",
            value: i128::from(year),
        });
    }
    let yy = (year - 2000) as i8;
    let v = semi_swap(yy) * 10_000_000_000
        + semi_swap(month) * 100_000_000
        + semi_swap(day) * 1_000_000
        + semi_swap(hour) * 10_000
        + semi_swap(minute) * 100
        + semi_swap(second);
    Ok(v as i64)
}

/// GSM 7-byte semi-octet timestamp: per byte nibble-swap → decimal, YY(+2000)
/// MM DD HH MM SS, then a timezone byte (ignored). UTC.
fn decode_gsm(value: i64) -> Result<PosixNs, ChronoError> {
    let v = u64::try_from(value)
        .ok()
        .filter(|v| *v <= 0xFF_FFFF_FFFF_FFFF)
        .ok_or(ChronoError::OutOfRange {
            what: "GSM (not a 7-byte value)",
            value: i128::from(value),
        })?;
    let semi = |sh: u32| {
        let byte = ((v >> sh) & 0xFF) as u8;
        semi_pair(byte & 0x0F, byte >> 4)
    };
    packed_civil(
        2000 + i16::from(semi(48)),
        semi(40),
        semi(32),
        semi(24),
        semi(16),
        semi(8),
    )
}

/// Nibble-swap a 2-digit decimal field (0..=99) into a GSM semi-octet byte:
/// `decode` reads it as `(byte & 0x0F) * 10 + (byte >> 4)`, so the tens digit
/// goes in the low nibble and the ones digit in the high nibble.
fn gsm_byte(field: i8) -> u64 {
    let f = field as u64;
    ((f % 10) << 4) | (f / 10)
}

/// Inverse of [`decode_gsm`]: 7 bytes, each field nibble-swapped, YY(+2000) MM
/// DD HH MM SS then a UTC timezone byte (0x00). Range is 2000–2099.
fn encode_gsm(instant: PosixNs) -> Result<i64, ChronoError> {
    let (year, month, day, hour, minute, second) = civil_fields(instant)?;
    if !(2000..=2099).contains(&year) {
        return Err(ChronoError::OutOfRange {
            what: "GSM year (2000-2099)",
            value: i128::from(year),
        });
    }
    let yy = (year - 2000) as i8;
    let v = (gsm_byte(yy) << 48)
        | (gsm_byte(month) << 40)
        | (gsm_byte(day) << 32)
        | (gsm_byte(hour) << 24)
        | (gsm_byte(minute) << 16)
        | (gsm_byte(second) << 8);
    // Low byte is the timezone; UTC ⇒ 0x00.
    Ok(v as i64)
}

/// Nokia time LE: 4 bytes reversed, then a two's-complement count of seconds
/// remaining before 2050 (`to_int − 0xFFFF_FFFF + secs(1970→2050)`). UTC.
fn decode_nokiale(value: i64) -> Result<PosixNs, ChronoError> {
    let p = i64::from(
        u32::try_from(value)
            .map_err(|_| ChronoError::OutOfRange {
                what: "Nokia LE (not a u32)",
                value: i128::from(value),
            })?
            .swap_bytes(),
    );
    let unix = p - 0xFFFF_FFFF + 2_524_608_000; // secs(1970→2050)
    Ok(PosixNs(i128::from(unix) * 1_000_000_000))
}

/// Inverse of [`decode_nokiale`]: `p = unix + 0xFFFF_FFFF − secs(1970→2050)`
/// must fit a u32 (a byte-reversed two's-complement count of seconds remaining
/// before 2050), then byte-reverse it. Whole-second granularity.
fn encode_nokiale(instant: PosixNs) -> Result<i64, ChronoError> {
    let unix = instant.0.div_euclid(1_000_000_000);
    let p = unix + 0xFFFF_FFFF - 2_524_608_000;
    let p = u32::try_from(p).map_err(|_| ChronoError::OutOfRange {
        what: "Nokia LE seconds-before-2050 (out of u32 range)",
        value: unix,
    })?;
    Ok(i64::from(p.swap_bytes()))
}

/// SQL Server `datetime`: 8 bytes = int32 days since 1900-01-01 + uint32 ticks
/// of 1/300 second. UTC.
fn decode_sqlserver(value: i64) -> Result<PosixNs, ChronoError> {
    let v = value as u64;
    let days = i128::from((v >> 32) as i32);
    let ticks = v & 0xFFFF_FFFF;
    if ticks >= 25_920_000 {
        // 300 ticks/s × 86400 s — a tick count of a full day or more is invalid.
        return Err(ChronoError::OutOfRange {
            what: "SQL Server datetime ticks (>= one day)",
            value: i128::from(ticks),
        });
    }
    let ns = SQLSERVER_EPOCH_NS
        + days * 86_400 * 1_000_000_000
        + (i128::from(ticks) * 1_000_000_000) / 300;
    Ok(PosixNs(ns))
}

/// Inverse of [`decode_sqlserver`]: pack an instant into `(days << 32) | ticks`,
/// where `days` is an int32 count since 1900-01-01 and `ticks` is a 1/300-second
/// count within the day. Sub-tick resolution is quantised to the nearest tick.
fn encode_sqlserver(instant: PosixNs) -> Result<i64, ChronoError> {
    const NS_PER_DAY: i128 = 86_400 * 1_000_000_000;
    let rel = instant
        .0
        .checked_sub(SQLSERVER_EPOCH_NS)
        .ok_or(ChronoError::OutOfRange {
            what: "SQL Server ns since 1900 (overflow)",
            value: instant.0,
        })?; // ns since 1900-01-01
    let days = rel.div_euclid(NS_PER_DAY);
    let rem_ns = rel.rem_euclid(NS_PER_DAY);
    // ticks = round(rem_ns × 300 / 1e9); round-half-up.
    let mut ticks = (rem_ns * 300 + 500_000_000) / 1_000_000_000;
    let mut days = days;
    if ticks >= 25_920_000 {
        // Rounded up past the last tick of the day → roll into the next day.
        ticks -= 25_920_000;
        days += 1;
    }
    let days = i32::try_from(days).map_err(|_| ChronoError::OutOfRange {
        what: "SQL Server days-since-1900 (out of i32 range)",
        value: days,
    })?;
    Ok((i64::from(days) << 32) | ticks as i64)
}

// ---------------------------------------------------------------------------
// Packed-codec dispatch + the engine's format registry.
//
// The 45-format catalog (ids, labels, epochs, units, tz/leap semantics, packed
// LAYOUT TAGS) is authoritative in `forensicnomicon::temporal_formats`. This
// module is the ENGINE: it owns the calendar math for the packed layouts and
// wraps each catalog entry in a `Format` that carries the matching codec.
// ---------------------------------------------------------------------------

/// The engine codec (unpacker + optional packer) for a knowledge-table
/// [`PackedLayout`] tag — the seam between the zero-dep catalog (which names the
/// layout) and the engine (which owns the calendar math). Exhaustive over the
/// tag, so a new layout in the catalog is a compile error here until wired.
fn packed_codec(layout: PackedLayout) -> PackedCodec {
    match layout {
        PackedLayout::FatDos => PackedCodec {
            decode: decode_fat_dos,
            encode: Some(encode_fat_dos),
        },
        PackedLayout::ExFat => PackedCodec {
            decode: decode_exfat,
            encode: Some(encode_exfat),
        },
        PackedLayout::Dttm => PackedCodec {
            decode: decode_dttm,
            encode: Some(encode_dttm),
        },
        PackedLayout::BitDate => PackedCodec {
            decode: decode_bitdate,
            encode: Some(encode_bitdate),
        },
        PackedLayout::BitDec => PackedCodec {
            decode: decode_bitdec,
            encode: Some(encode_bitdec),
        },
        PackedLayout::Bcd => PackedCodec {
            decode: decode_bcd,
            encode: Some(encode_bcd),
        },
        PackedLayout::Moto => PackedCodec {
            decode: decode_moto,
            encode: Some(encode_moto),
        },
        PackedLayout::Symantec => PackedCodec {
            decode: decode_symantec,
            encode: Some(encode_symantec),
        },
        PackedLayout::Dvr => PackedCodec {
            decode: decode_dvr,
            encode: Some(encode_dvr),
        },
        PackedLayout::Ns40 => PackedCodec {
            decode: decode_ns40,
            encode: Some(encode_ns40),
        },
        PackedLayout::Ns40Le => PackedCodec {
            decode: decode_ns40le,
            encode: Some(encode_ns40le),
        },
        PackedLayout::LogTime => PackedCodec {
            decode: decode_logtime,
            encode: Some(encode_logtime),
        },
        PackedLayout::SemiOctet => PackedCodec {
            decode: decode_semioctet,
            encode: Some(encode_semioctet),
        },
        PackedLayout::Gsm => PackedCodec {
            decode: decode_gsm,
            encode: Some(encode_gsm),
        },
        PackedLayout::NokiaLe => PackedCodec {
            decode: decode_nokiale,
            encode: Some(encode_nokiale),
        },
        PackedLayout::SqlServer => PackedCodec {
            decode: decode_sqlserver,
            encode: Some(encode_sqlserver),
        },
    }
}

/// The engine's format registry: every authoritative
/// [`forensicnomicon::temporal_formats::TIME_FORMATS`] entry wrapped in an engine
/// [`Format`] that carries the packed codec for a packed layout (and `None` for
/// the linear/embedded/float families). The knowledge is forensicnomicon's; the
/// decode/encode behaviour is the engine's.
pub static FORMATS: LazyLock<Vec<Format>> = LazyLock::new(|| {
    TIME_FORMATS
        .iter()
        .map(|meta| Format {
            meta,
            packed: match meta.encoding {
                Encoding::Packed(layout) => Some(packed_codec(layout)),
                Encoding::LinearInt { .. }
                | Encoding::LinearFloat { .. }
                | Encoding::Embedded { .. } => None,
            },
        })
        .collect()
});