file-parse-cache 0.1.0

Mtime-gated file parse cache for apps that poll files and reparse on change
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
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
use std::fmt;
use std::hash::Hash;
use std::io;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, SystemTime};

use moka::sync::Cache;

// ---------------------------------------------------------------------------
// Fingerprint trait + impls
// ---------------------------------------------------------------------------

/// Cheaply identifies whether a file's content has changed since the last parse.
pub trait Fingerprint: Send + Sync + 'static {
    /// Opaque stamp that can be compared for equality and hashed.
    type Stamp: Eq + Hash + Clone + Send + Sync + fmt::Debug + 'static;

    /// Compute the current stamp for `path`. Returns `Err` if the file is
    /// unreadable (missing, permissions, etc.) — the cache treats this as a miss
    /// that produces the caller's error.
    fn stamp(&self, path: &Path) -> io::Result<Self::Stamp>;
}

// ---------------------------------------------------------------------------
// MtimeStamp — serialization-ready replacement for SystemTime
// ---------------------------------------------------------------------------

/// Seconds + nanoseconds since UNIX epoch. Negative `secs` for pre-epoch times.
///
/// Uses floor semantics: `nanos` is always non-negative and `secs` is the
/// largest integer ≤ the true value. For example, 0.5 seconds before epoch
/// is `{ secs: -1, nanos: 500_000_000 }`, representing −1 + 0.5 = −0.5.
#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
#[cfg_attr(any(test, feature = "persist"), derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct MtimeStamp {
    pub secs: i64,
    pub nanos: u32,
}

impl From<SystemTime> for MtimeStamp {
    fn from(t: SystemTime) -> Self {
        match t.duration_since(SystemTime::UNIX_EPOCH) {
            Ok(d) => MtimeStamp {
                secs: d.as_secs() as i64,
                nanos: d.subsec_nanos(),
            },
            Err(e) => {
                let d = e.duration();
                let sub = d.subsec_nanos();
                if sub == 0 {
                    MtimeStamp {
                        secs: -(d.as_secs() as i64),
                        nanos: 0,
                    }
                } else {
                    MtimeStamp {
                        secs: -(d.as_secs() as i64) - 1,
                        nanos: 1_000_000_000 - sub,
                    }
                }
            }
        }
    }
}

impl MtimeStamp {
    /// Convert back to `SystemTime`. Lossless roundtrip with `From<SystemTime>`.
    pub fn to_system_time(self) -> SystemTime {
        if self.secs >= 0 {
            SystemTime::UNIX_EPOCH + Duration::new(self.secs as u64, self.nanos)
        } else if self.nanos == 0 {
            SystemTime::UNIX_EPOCH - Duration::new((-self.secs) as u64, 0)
        } else {
            SystemTime::UNIX_EPOCH
                - Duration::new((-self.secs - 1) as u64, 1_000_000_000 - self.nanos)
        }
    }
}

/// Compares `mtime` from filesystem metadata. Cheap (one syscall), but can
/// miss edits that land within the same second on coarse-grained filesystems,
/// and reports false changes after `git clone` or `cargo` resets mtimes.
#[derive(Debug, Clone, Copy, Default)]
pub struct MtimeFingerprint;

impl Fingerprint for MtimeFingerprint {
    type Stamp = MtimeStamp;

    fn stamp(&self, path: &Path) -> io::Result<Self::Stamp> {
        let mtime = std::fs::metadata(path)?.modified()?;
        Ok(MtimeStamp::from(mtime))
    }
}

/// BLAKE3 hash of the full file content. Robust against mtime resets, but
/// reads the entire file on every check.
#[derive(Debug, Clone, Copy, Default)]
pub struct ContentHashFingerprint;

/// 32-byte BLAKE3 digest, wrapped for trait impls.
#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
#[cfg_attr(any(test, feature = "persist"), derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct Blake3Stamp(pub [u8; 32]);

impl Fingerprint for ContentHashFingerprint {
    type Stamp = Blake3Stamp;

    fn stamp(&self, path: &Path) -> io::Result<Self::Stamp> {
        let bytes = std::fs::read(path)?;
        Ok(Blake3Stamp(*blake3::hash(&bytes).as_bytes()))
    }
}

// ---------------------------------------------------------------------------
// Cache entry (stored inside moka)
// ---------------------------------------------------------------------------

#[derive(Clone, Debug)]
struct Entry<T, S> {
    stamp: S,
    value: T,
}

// ---------------------------------------------------------------------------
// Core cache
// ---------------------------------------------------------------------------

/// Mtime-gated (or content-hash-gated) file parse cache.
///
/// On `get`, the fingerprint of the file is checked. If it matches the cached
/// stamp, the cached `T` is returned without re-parsing. On mismatch or cache
/// miss the `parser` closure runs and the result is stored.
///
/// Backed by `moka::sync::Cache` with bounded-size LRU eviction.
pub struct FileParseCache<T, F: Fingerprint = MtimeFingerprint> {
    inner: Cache<PathBuf, Entry<T, F::Stamp>>,
    fingerprint: Arc<F>,
    dirty: AtomicBool,
}

impl<T, F> fmt::Debug for FileParseCache<T, F>
where
    T: Clone + Send + Sync + 'static + fmt::Debug,
    F: Fingerprint + fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.inner.run_pending_tasks();
        f.debug_struct("FileParseCache")
            .field("entry_count", &self.inner.entry_count())
            .field("fingerprint", &self.fingerprint)
            .finish()
    }
}

impl<T: Clone + Send + Sync + 'static> FileParseCache<T, MtimeFingerprint> {
    /// Create a cache with mtime-based invalidation and room for `max_entries` files.
    pub fn new(max_entries: u64) -> Self {
        Self::with_fingerprint(max_entries, MtimeFingerprint)
    }
}

impl<T, F> FileParseCache<T, F>
where
    T: Clone + Send + Sync + 'static,
    F: Fingerprint,
{
    /// Create a cache with a custom fingerprint strategy.
    pub fn with_fingerprint(max_entries: u64, fingerprint: F) -> Self {
        Self {
            inner: Cache::new(max_entries),
            fingerprint: Arc::new(fingerprint),
            dirty: AtomicBool::new(false),
        }
    }

    /// Return the cached value for `path`, or parse it via `parser` on miss /
    /// fingerprint change.
    ///
    /// If multiple threads call `get` for the same path concurrently and all
    /// miss, each thread runs `parser` independently. The last writer wins in
    /// moka; all callers receive a correct (freshly-parsed) value. This trades
    /// a rare redundant parse for a simpler API — coalescing via
    /// `try_get_with` would require wrapping the caller's error in `Arc`.
    ///
    /// On unreadable files (missing, permissions), the fingerprint stat fails
    /// and returns `Err(E::from(io::Error))` without invoking `parser`.
    pub fn get<E>(
        &self,
        path: &Path,
        parser: impl FnOnce(&Path) -> Result<T, E>,
    ) -> Result<T, E>
    where
        E: From<io::Error> + Send + Sync + 'static,
    {
        let key = path.to_path_buf();
        let current_stamp = self.fingerprint.stamp(path).map_err(E::from)?;

        if let Some(entry) = self.inner.get(&key) {
            if entry.stamp == current_stamp {
                return Ok(entry.value.clone());
            }
        }

        let value = parser(path)?;
        self.inner.insert(
            key,
            Entry {
                stamp: current_stamp,
                value: value.clone(),
            },
        );
        self.dirty.store(true, Ordering::Release);
        Ok(value)
    }

    /// Remove entries where `predicate` returns `true`.
    ///
    /// Not atomic: takes a snapshot via iteration, then invalidates matching
    /// keys one by one. An entry inserted by a concurrent `get` between the
    /// snapshot and the invalidation pass will be missed — it will be caught
    /// on the next `purge_if` call. Invalidated entries become immediately
    /// invisible to `get`, but `len()` reflects the removal only after its
    /// own pending-task flush.
    ///
    /// Allocates O(cache size) for the key snapshot — every key is cloned
    /// into a temporary `Vec` before invalidation begins. Fine for caches
    /// under ~10K entries. For larger caches, prefer moka's built-in
    /// TTL/TTI-based eviction over manual purging.
    pub fn purge_if(&self, predicate: impl Fn(&Path) -> bool) {
        let keys_to_remove: Vec<PathBuf> = self
            .inner
            .iter()
            .filter(|(k, _)| predicate(k))
            .map(|(k, _)| k.as_ref().clone())
            .collect();
        if !keys_to_remove.is_empty() {
            for key in &keys_to_remove {
                self.inner.invalidate(key);
            }
            self.dirty.store(true, Ordering::Release);
        }
    }

    /// Remove all entries.
    pub fn clear(&self) {
        self.inner.invalidate_all();
        self.dirty.store(true, Ordering::Release);
    }

    /// Number of entries currently in the cache.
    ///
    /// Flushes pending bookkeeping before reading the count so the value is
    /// immediately consistent with preceding `get`, `purge_if`, and `clear`
    /// calls. Cost is O(pending operations), not O(1) — typically microseconds
    /// for caches with low write rates, but callers in tight loops should be
    /// aware.
    pub fn len(&self) -> u64 {
        self.inner.run_pending_tasks();
        self.inner.entry_count()
    }

    /// Whether the cache is empty.
    ///
    /// Same consistency and cost as [`len`](Self::len).
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

// ---------------------------------------------------------------------------
// Persistence (feature = "persist")
// ---------------------------------------------------------------------------

/// Serialization codec for disk persistence. Not object-safe due to generic
/// methods — pass as `&Fmt` where `Fmt: Format`, not `&dyn Format`.
#[cfg(feature = "persist")]
pub trait Format: Send + Sync {
    fn serialize<T: serde::Serialize>(
        &self,
        value: &T,
    ) -> Result<Vec<u8>, Box<dyn std::error::Error + Send + Sync>>;

    fn deserialize<T: serde::de::DeserializeOwned>(
        &self,
        bytes: &[u8],
    ) -> Result<T, Box<dyn std::error::Error + Send + Sync>>;
}

#[cfg(feature = "persist-bincode")]
#[derive(Debug, Clone, Copy, Default)]
pub struct BincodeFormat;

#[cfg(feature = "persist-bincode")]
impl Format for BincodeFormat {
    fn serialize<T: serde::Serialize>(
        &self,
        value: &T,
    ) -> Result<Vec<u8>, Box<dyn std::error::Error + Send + Sync>> {
        bincode::serialize(value).map_err(|e| e as Box<dyn std::error::Error + Send + Sync>)
    }

    fn deserialize<T: serde::de::DeserializeOwned>(
        &self,
        bytes: &[u8],
    ) -> Result<T, Box<dyn std::error::Error + Send + Sync>> {
        bincode::deserialize(bytes).map_err(|e| e as Box<dyn std::error::Error + Send + Sync>)
    }
}

#[cfg(feature = "persist-postcard")]
#[derive(Debug, Clone, Copy, Default)]
pub struct PostcardFormat;

#[cfg(feature = "persist-postcard")]
impl Format for PostcardFormat {
    fn serialize<T: serde::Serialize>(
        &self,
        value: &T,
    ) -> Result<Vec<u8>, Box<dyn std::error::Error + Send + Sync>> {
        postcard::to_allocvec(value)
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)
    }

    fn deserialize<T: serde::de::DeserializeOwned>(
        &self,
        bytes: &[u8],
    ) -> Result<T, Box<dyn std::error::Error + Send + Sync>> {
        postcard::from_bytes(bytes)
            .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)
    }
}

#[cfg(feature = "persist")]
const DISK_CACHE_VERSION: u32 = 1;

#[cfg(feature = "persist")]
#[derive(serde::Serialize, serde::Deserialize)]
struct DiskCache<T, S> {
    version: u32,
    entries: Vec<DiskEntry<T, S>>,
}

#[cfg(feature = "persist")]
#[derive(serde::Serialize, serde::Deserialize)]
struct DiskEntry<T, S> {
    path: String,
    stamp: S,
    value: T,
}

#[cfg(feature = "persist")]
#[derive(Debug)]
#[non_exhaustive]
pub enum SaveError {
    Io(io::Error),
    Serialize(Box<dyn std::error::Error + Send + Sync>),
}

#[cfg(feature = "persist")]
impl fmt::Display for SaveError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io(e) => write!(f, "IO error: {e}"),
            Self::Serialize(e) => write!(f, "serialization error: {e}"),
        }
    }
}

#[cfg(feature = "persist")]
impl std::error::Error for SaveError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io(e) => Some(e),
            Self::Serialize(e) => Some(e.as_ref()),
        }
    }
}

#[cfg(feature = "persist")]
#[derive(Debug)]
#[non_exhaustive]
pub enum LoadError {
    Io(io::Error),
    Deserialize(Box<dyn std::error::Error + Send + Sync>),
    VersionMismatch { disk: u32, expected: u32 },
}

#[cfg(feature = "persist")]
impl fmt::Display for LoadError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Io(e) => write!(f, "IO error: {e}"),
            Self::Deserialize(e) => write!(f, "deserialization error: {e}"),
            Self::VersionMismatch { disk, expected } => {
                write!(f, "version mismatch: disk={disk}, expected={expected}")
            }
        }
    }
}

#[cfg(feature = "persist")]
impl std::error::Error for LoadError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::Io(e) => Some(e),
            Self::Deserialize(e) => Some(e.as_ref()),
            Self::VersionMismatch { .. } => None,
        }
    }
}

#[cfg(feature = "persist")]
#[derive(Debug, Clone, Copy)]
pub struct LoadStats {
    pub loaded: u64,
    pub stale: u64,
}

#[cfg(feature = "persist")]
impl<T, F> FileParseCache<T, F>
where
    T: Clone + Send + Sync + 'static,
    F: Fingerprint,
{
    /// Persist the current cache to `path` using `format`.
    ///
    /// Returns `Ok(())` immediately if no entries have changed since the last
    /// save. On failure, the dirty flag is restored so the next `save()` retries.
    ///
    /// **Deferred-insert semantics:** A concurrent `get()` that parses and
    /// inserts during `save()` may or may not be included in this snapshot.
    /// If missed, the insert sets the dirty flag, ensuring the next `save()`
    /// captures it. No insert is ever lost as long as the caller saves again
    /// when entries have changed.
    pub fn save<Fmt: Format>(&self, path: &Path, format: &Fmt) -> Result<(), SaveError>
    where
        T: serde::Serialize,
        F::Stamp: serde::Serialize,
    {
        if !self.dirty.swap(false, Ordering::AcqRel) {
            return Ok(());
        }

        let entries: Vec<DiskEntry<T, F::Stamp>> = self
            .inner
            .iter()
            .map(|(k, entry)| DiskEntry {
                path: k.to_string_lossy().into_owned(),
                stamp: entry.stamp.clone(),
                value: entry.value.clone(),
            })
            .collect();

        let disk = DiskCache {
            version: DISK_CACHE_VERSION,
            entries,
        };

        let bytes = match format.serialize(&disk) {
            Ok(b) => b,
            Err(e) => {
                self.dirty.store(true, Ordering::Release);
                return Err(SaveError::Serialize(e));
            }
        };

        if let Some(parent) = path.parent() {
            if let Err(e) = std::fs::create_dir_all(parent) {
                self.dirty.store(true, Ordering::Release);
                return Err(SaveError::Io(e));
            }
        }

        if let Err(e) = std::fs::write(path, &bytes) {
            self.dirty.store(true, Ordering::Release);
            return Err(SaveError::Io(e));
        }

        Ok(())
    }

    /// Load cached entries from `path`, dropping entries whose fingerprint no
    /// longer matches the file on disk.
    ///
    /// Stale validation is eager: every loaded entry is re-stamped via the
    /// `Fingerprint` impl. Entries for files that were deleted or modified
    /// since the cache was saved are silently skipped. Returns counts of
    /// loaded vs stale entries.
    ///
    /// Does not set the dirty flag — loaded data already matches disk.
    pub fn load<Fmt: Format>(&self, path: &Path, format: &Fmt) -> Result<LoadStats, LoadError>
    where
        T: serde::de::DeserializeOwned,
        F::Stamp: serde::de::DeserializeOwned,
    {
        let bytes = std::fs::read(path).map_err(LoadError::Io)?;
        let disk: DiskCache<T, F::Stamp> =
            format.deserialize(&bytes).map_err(LoadError::Deserialize)?;

        if disk.version != DISK_CACHE_VERSION {
            return Err(LoadError::VersionMismatch {
                disk: disk.version,
                expected: DISK_CACHE_VERSION,
            });
        }

        let mut loaded = 0u64;
        let mut stale = 0u64;

        for entry in disk.entries {
            let file_path = PathBuf::from(&entry.path);
            let current_stamp = match self.fingerprint.stamp(&file_path) {
                Ok(s) => s,
                Err(_) => {
                    stale += 1;
                    continue;
                }
            };
            if current_stamp != entry.stamp {
                stale += 1;
                continue;
            }
            self.inner.insert(
                file_path,
                Entry {
                    stamp: entry.stamp,
                    value: entry.value,
                },
            );
            loaded += 1;
        }

        Ok(LoadStats { loaded, stale })
    }
}

// ===========================================================================
// Tests
// ===========================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::io::Write as IoWrite;
    use tempfile::TempDir;

    fn write_file(dir: &TempDir, name: &str, content: &str) -> PathBuf {
        let p = dir.path().join(name);
        let mut f = fs::File::create(&p).unwrap();
        f.write_all(content.as_bytes()).unwrap();
        p
    }

    fn make_cache() -> FileParseCache<Vec<String>> {
        FileParseCache::new(64)
    }

    fn line_parser(path: &Path) -> Result<Vec<String>, io::Error> {
        let text = fs::read_to_string(path)?;
        Ok(text.lines().map(String::from).collect())
    }

    // ----- MtimeStamp roundtrip -----

    #[test]
    fn mtime_stamp_post_epoch_roundtrip() {
        let now = SystemTime::now();
        let stamp = MtimeStamp::from(now);
        assert!(stamp.secs > 0);
        assert_eq!(stamp.to_system_time(), now);
    }

    #[test]
    fn mtime_stamp_pre_epoch_roundtrip() {
        let t = SystemTime::UNIX_EPOCH - Duration::new(1, 500_000_000);
        let stamp = MtimeStamp::from(t);
        assert_eq!(stamp.secs, -2);
        assert_eq!(stamp.nanos, 500_000_000);
        assert_eq!(stamp.to_system_time(), t);

        let t = SystemTime::UNIX_EPOCH - Duration::new(0, 500_000_000);
        let stamp = MtimeStamp::from(t);
        assert_eq!(stamp.secs, -1);
        assert_eq!(stamp.nanos, 500_000_000);
        assert_eq!(stamp.to_system_time(), t);

        let t = SystemTime::UNIX_EPOCH - Duration::from_secs(3);
        let stamp = MtimeStamp::from(t);
        assert_eq!(stamp.secs, -3);
        assert_eq!(stamp.nanos, 0);
        assert_eq!(stamp.to_system_time(), t);

        let stamp = MtimeStamp::from(SystemTime::UNIX_EPOCH);
        assert_eq!(stamp.secs, 0);
        assert_eq!(stamp.nanos, 0);
        assert_eq!(stamp.to_system_time(), SystemTime::UNIX_EPOCH);
    }

    #[test]
    fn mtime_stamp_serde_roundtrip() {
        let cases = [
            MtimeStamp { secs: 1_700_000_000, nanos: 123_456_789 },
            MtimeStamp { secs: -2, nanos: 500_000_000 },
            MtimeStamp { secs: -1, nanos: 500_000_000 },
            MtimeStamp { secs: 0, nanos: 0 },
        ];
        for stamp in &cases {
            let json = serde_json::to_string(stamp).unwrap();
            let back: MtimeStamp = serde_json::from_str(&json).unwrap();
            assert_eq!(*stamp, back, "failed roundtrip for {stamp:?}");
        }
    }

    #[test]
    fn blake3_stamp_serde_roundtrip() {
        let bytes = *blake3::hash(b"hello").as_bytes();
        let stamp = Blake3Stamp(bytes);
        let json = serde_json::to_string(&stamp).unwrap();
        let back: Blake3Stamp = serde_json::from_str(&json).unwrap();
        assert_eq!(stamp, back);
    }

    // ----- basic cache behavior -----

    #[test]
    fn returns_parsed_value_and_caches_it() {
        let tmp = TempDir::new().unwrap();
        let p = write_file(&tmp, "a.txt", "hello\nworld");
        let cache = make_cache();

        let first = cache.get(&p, line_parser).unwrap();
        assert_eq!(first, vec!["hello", "world"]);

        let second = cache.get(&p, line_parser).unwrap();
        assert_eq!(second, first);
    }

    #[test]
    fn len_is_consistent_immediately_after_insert() {
        let tmp = TempDir::new().unwrap();
        let a = write_file(&tmp, "a.txt", "a");
        let b = write_file(&tmp, "b.txt", "b");
        let cache = make_cache();

        assert_eq!(cache.len(), 0);
        cache.get(&a, line_parser).unwrap();
        assert_eq!(cache.len(), 1);
        cache.get(&b, line_parser).unwrap();
        assert_eq!(cache.len(), 2);
    }

    #[test]
    fn missing_file_returns_error() {
        let cache = make_cache();
        let result = cache.get(Path::new("/no/such/file.txt"), line_parser);
        assert!(result.is_err());
    }

    // ----- invalidation -----

    #[test]
    fn reparses_when_mtime_changes() {
        let tmp = TempDir::new().unwrap();
        let p = write_file(&tmp, "a.txt", "v1");
        let cache = make_cache();

        let first = cache.get(&p, line_parser).unwrap();
        assert_eq!(first, vec!["v1"]);

        std::thread::sleep(std::time::Duration::from_millis(1100));
        fs::write(&p, "v2\nv3").unwrap();

        let second = cache.get(&p, line_parser).unwrap();
        assert_eq!(second, vec!["v2", "v3"]);
    }

    // ----- content-hash fingerprint -----

    #[test]
    fn content_hash_detects_same_mtime_different_content() {
        let tmp = TempDir::new().unwrap();
        let p = write_file(&tmp, "a.txt", "original");
        let cache: FileParseCache<Vec<String>, ContentHashFingerprint> =
            FileParseCache::with_fingerprint(64, ContentHashFingerprint);

        let first = cache.get(&p, line_parser).unwrap();
        assert_eq!(first, vec!["original"]);

        fs::write(&p, "changed").unwrap();

        let second = cache.get(&p, line_parser).unwrap();
        assert_eq!(second, vec!["changed"]);
    }

    #[test]
    fn content_hash_skips_reparse_on_identical_content() {
        let tmp = TempDir::new().unwrap();
        let p = write_file(&tmp, "a.txt", "stable");

        use std::sync::atomic::{AtomicU32, Ordering};
        let parse_count = Arc::new(AtomicU32::new(0));

        let cache: FileParseCache<Vec<String>, ContentHashFingerprint> =
            FileParseCache::with_fingerprint(64, ContentHashFingerprint);

        let counter = parse_count.clone();
        let counting_parser = move |path: &Path| -> Result<Vec<String>, io::Error> {
            counter.fetch_add(1, Ordering::Relaxed);
            line_parser(path)
        };

        cache.get(&p, &counting_parser).unwrap();
        assert_eq!(parse_count.load(Ordering::Relaxed), 1);

        std::thread::sleep(std::time::Duration::from_millis(1100));
        fs::write(&p, "stable").unwrap();

        cache.get(&p, &counting_parser).unwrap();
        assert_eq!(parse_count.load(Ordering::Relaxed), 1);
    }

    // ----- purge_if -----

    #[test]
    fn purge_if_removes_matching_entries() {
        let tmp = TempDir::new().unwrap();
        let a = write_file(&tmp, "keep.txt", "a");
        let b = write_file(&tmp, "drop.txt", "b");
        let cache = make_cache();

        cache.get(&a, line_parser).unwrap();
        cache.get(&b, line_parser).unwrap();

        cache.purge_if(|p| p.file_name().map_or(false, |n| n == "drop.txt"));

        // len() flushes pending tasks internally — no explicit drain needed.
        assert_eq!(cache.len(), 1);
    }

    // ----- clear -----

    #[test]
    fn clear_removes_all_entries() {
        let tmp = TempDir::new().unwrap();
        let a = write_file(&tmp, "a.txt", "a");
        let b = write_file(&tmp, "b.txt", "b");
        let cache = make_cache();

        cache.get(&a, line_parser).unwrap();
        cache.get(&b, line_parser).unwrap();

        cache.clear();
        // len() flushes pending tasks internally — no explicit drain needed.
        assert_eq!(cache.len(), 0);
    }

    // ----- user-controlled error type -----

    #[derive(Debug)]
    #[allow(dead_code)]
    enum MyError {
        Io(io::Error),
        Parse(String),
    }

    impl From<io::Error> for MyError {
        fn from(e: io::Error) -> Self {
            MyError::Io(e)
        }
    }

    #[test]
    fn parser_error_propagates_without_caching() {
        let tmp = TempDir::new().unwrap();
        let p = write_file(&tmp, "bad.txt", "not-a-number");
        let cache: FileParseCache<i32> = FileParseCache::new(64);

        let result = cache.get(&p, |path| {
            let text = fs::read_to_string(path).map_err(MyError::Io)?;
            text.trim()
                .parse::<i32>()
                .map_err(|e| MyError::Parse(e.to_string()))
        });

        assert!(matches!(result, Err(MyError::Parse(_))));
        // len() flushes pending tasks internally — no explicit drain needed.
        assert_eq!(cache.len(), 0);
    }
}

// ---------------------------------------------------------------------------
// Persistence tests (bincode)
// ---------------------------------------------------------------------------

#[cfg(all(test, feature = "persist-bincode"))]
mod persist_tests {
    use super::*;
    use std::fs;
    use std::io::Write as IoWrite;
    use tempfile::TempDir;

    fn write_file(dir: &TempDir, name: &str, content: &str) -> PathBuf {
        let p = dir.path().join(name);
        let mut f = fs::File::create(&p).unwrap();
        f.write_all(content.as_bytes()).unwrap();
        p
    }

    fn make_cache() -> FileParseCache<Vec<String>> {
        FileParseCache::new(64)
    }

    fn line_parser(path: &Path) -> Result<Vec<String>, io::Error> {
        let text = fs::read_to_string(path)?;
        Ok(text.lines().map(String::from).collect())
    }

    struct FailingFormat;
    impl Format for FailingFormat {
        fn serialize<T: serde::Serialize>(
            &self,
            _: &T,
        ) -> Result<Vec<u8>, Box<dyn std::error::Error + Send + Sync>> {
            Err("intentional failure".into())
        }
        fn deserialize<T: serde::de::DeserializeOwned>(
            &self,
            _: &[u8],
        ) -> Result<T, Box<dyn std::error::Error + Send + Sync>> {
            Err("intentional failure".into())
        }
    }

    #[test]
    fn save_and_load_roundtrip() {
        let tmp = TempDir::new().unwrap();
        let cache_path = tmp.path().join("cache.bin");
        let p = write_file(&tmp, "a.txt", "hello\nworld");

        let cache = make_cache();
        cache.get(&p, line_parser).unwrap();
        cache.save(&cache_path, &BincodeFormat).unwrap();
        assert!(cache_path.exists());

        let cache2 = make_cache();
        let stats = cache2.load(&cache_path, &BincodeFormat).unwrap();
        assert_eq!(stats.loaded, 1);
        assert_eq!(stats.stale, 0);

        let entries = cache2.get(&p, line_parser).unwrap();
        assert_eq!(entries, vec!["hello", "world"]);
    }

    #[test]
    fn load_drops_stale_entries() {
        let tmp = TempDir::new().unwrap();
        let cache_path = tmp.path().join("cache.bin");
        let p = write_file(&tmp, "a.txt", "v1");

        let cache = make_cache();
        cache.get(&p, line_parser).unwrap();
        cache.save(&cache_path, &BincodeFormat).unwrap();

        // Modify the file so mtime changes — entry becomes stale.
        std::thread::sleep(std::time::Duration::from_millis(1100));
        fs::write(&p, "v2").unwrap();

        let cache2 = make_cache();
        let stats = cache2.load(&cache_path, &BincodeFormat).unwrap();
        assert_eq!(stats.loaded, 0);
        assert_eq!(stats.stale, 1);
        assert_eq!(cache2.len(), 0);
    }

    #[test]
    fn load_drops_missing_files() {
        let tmp = TempDir::new().unwrap();
        let cache_path = tmp.path().join("cache.bin");
        let p = write_file(&tmp, "a.txt", "v1");

        let cache = make_cache();
        cache.get(&p, line_parser).unwrap();
        cache.save(&cache_path, &BincodeFormat).unwrap();

        fs::remove_file(&p).unwrap();

        let cache2 = make_cache();
        let stats = cache2.load(&cache_path, &BincodeFormat).unwrap();
        assert_eq!(stats.loaded, 0);
        assert_eq!(stats.stale, 1);
    }

    #[test]
    fn save_noop_when_not_dirty() {
        let tmp = TempDir::new().unwrap();
        let cache_path = tmp.path().join("cache.bin");
        let cache = make_cache();

        cache.save(&cache_path, &BincodeFormat).unwrap();
        assert!(!cache_path.exists());
    }

    #[test]
    fn save_after_load_is_noop() {
        let tmp = TempDir::new().unwrap();
        let cache_path = tmp.path().join("cache.bin");
        let p = write_file(&tmp, "a.txt", "hello");

        let cache = make_cache();
        cache.get(&p, line_parser).unwrap();
        cache.save(&cache_path, &BincodeFormat).unwrap();

        // Load into fresh cache — dirty should remain false.
        let cache2 = make_cache();
        cache2.load(&cache_path, &BincodeFormat).unwrap();

        // Remove the file and try to save — should be noop (not dirty).
        fs::remove_file(&cache_path).unwrap();
        cache2.save(&cache_path, &BincodeFormat).unwrap();
        assert!(!cache_path.exists());
    }

    #[test]
    fn save_restores_dirty_on_failure() {
        let tmp = TempDir::new().unwrap();
        let cache_path = tmp.path().join("cache.bin");
        let p = write_file(&tmp, "a.txt", "hello");
        let cache = make_cache();

        cache.get(&p, line_parser).unwrap();

        let result = cache.save(&cache_path, &FailingFormat);
        assert!(result.is_err());

        // Dirty was restored — real save should now succeed.
        cache.save(&cache_path, &BincodeFormat).unwrap();
        assert!(cache_path.exists());
    }

    #[test]
    fn version_mismatch_returns_error() {
        let tmp = TempDir::new().unwrap();
        let cache_path = tmp.path().join("cache.bin");

        // Write a cache with a bogus version.
        let disk: DiskCache<Vec<String>, MtimeStamp> = DiskCache {
            version: 99,
            entries: vec![],
        };
        let bytes = bincode::serialize(&disk).unwrap();
        fs::write(&cache_path, &bytes).unwrap();

        let cache = make_cache();
        let result = cache.load(&cache_path, &BincodeFormat);
        assert!(matches!(
            result,
            Err(LoadError::VersionMismatch { disk: 99, expected: 1 })
        ));
    }

    #[test]
    fn multiple_entries_roundtrip() {
        let tmp = TempDir::new().unwrap();
        let cache_path = tmp.path().join("cache.bin");
        let a = write_file(&tmp, "a.txt", "alpha");
        let b = write_file(&tmp, "b.txt", "beta\ngamma");

        let cache = make_cache();
        cache.get(&a, line_parser).unwrap();
        cache.get(&b, line_parser).unwrap();
        cache.save(&cache_path, &BincodeFormat).unwrap();

        let cache2 = make_cache();
        let stats = cache2.load(&cache_path, &BincodeFormat).unwrap();
        assert_eq!(stats.loaded, 2);

        assert_eq!(cache2.get(&a, line_parser).unwrap(), vec!["alpha"]);
        assert_eq!(cache2.get(&b, line_parser).unwrap(), vec!["beta", "gamma"]);
    }
}

// ---------------------------------------------------------------------------
// Persistence tests (postcard)
// ---------------------------------------------------------------------------

#[cfg(all(test, feature = "persist-postcard"))]
mod postcard_tests {
    use super::*;
    use std::fs;
    use std::io::Write as IoWrite;
    use tempfile::TempDir;

    fn write_file(dir: &TempDir, name: &str, content: &str) -> PathBuf {
        let p = dir.path().join(name);
        let mut f = fs::File::create(&p).unwrap();
        f.write_all(content.as_bytes()).unwrap();
        p
    }

    fn line_parser(path: &Path) -> Result<Vec<String>, io::Error> {
        let text = fs::read_to_string(path)?;
        Ok(text.lines().map(String::from).collect())
    }

    #[test]
    fn postcard_save_and_load_roundtrip() {
        let tmp = TempDir::new().unwrap();
        let cache_path = tmp.path().join("cache.pc");
        let p = write_file(&tmp, "a.txt", "hello\nworld");

        let cache: FileParseCache<Vec<String>> = FileParseCache::new(64);
        cache.get(&p, line_parser).unwrap();
        cache.save(&cache_path, &PostcardFormat).unwrap();

        let cache2: FileParseCache<Vec<String>> = FileParseCache::new(64);
        let stats = cache2.load(&cache_path, &PostcardFormat).unwrap();
        assert_eq!(stats.loaded, 1);
        assert_eq!(stats.stale, 0);

        let entries = cache2.get(&p, line_parser).unwrap();
        assert_eq!(entries, vec!["hello", "world"]);
    }
}