girt 0.6.1

An incremental, idiomatic Rust implementation of Git
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
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
//! Pinned file pairs with bounded offset tables and explicit streaming pack verification.

#![warn(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::unreachable,
    clippy::indexing_slicing,
    reason = "parses untrusted repository or network input (#103)"
)]
use std::fs::File;
use std::io::{self, BufRead, BufReader, Read};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};

mod window;
pub(crate) use window::HeaderScope;

static NEXT_WINDOW_ID: AtomicU64 = AtomicU64::new(1);

use super::index::{Entry, Index, verify_hash, word};
use super::reader::{EntryHeader, Source, check_cancelled, decode};
use crate::object::Hasher;
use crate::{Object, ObjectFormat, ObjectId, ObjectKind, ObjectReadError as Error, ReadLimits};

/// A pinned artifact read with positioned reads, so lookups share no cursor or lock.
#[derive(Debug)]
struct Artifact {
    file: File,
    path: PathBuf,
    len: usize,
    stamp: Stamp,
    window_id: u64,
    #[cfg(test)]
    bytes_read: std::sync::atomic::AtomicUsize,
}

impl Artifact {
    fn open(path: &Path) -> Result<Self, Error> {
        let mut options = std::fs::OpenOptions::new();
        options.read(true);
        #[cfg(windows)]
        {
            use std::os::windows::fs::OpenOptionsExt;

            // Published artifacts are immutable; retain Git's rename/delete interoperability.
            use windows_sys::Win32::Storage::FileSystem::{FILE_SHARE_DELETE, FILE_SHARE_READ};
            options.share_mode(FILE_SHARE_READ | FILE_SHARE_DELETE);
        }
        let file = options
            .open(path)
            .map_err(|source| path_error(path, source))?;
        let stamp = Stamp::read(&file).map_err(|source| path_error(path, source))?;
        let len = stamp.len;
        let len = usize::try_from(len).map_err(|_| Error::Limit("artifact address space"))?;
        Ok(Self {
            file,
            path: path.to_owned(),
            len,
            stamp,
            window_id: NEXT_WINDOW_ID.fetch_add(1, Ordering::Relaxed),
            #[cfg(test)]
            bytes_read: std::sync::atomic::AtomicUsize::new(0),
        })
    }

    fn read_at(&self, offset: usize, output: &mut [u8]) -> Result<(), Error> {
        self.read_file(offset, output)
            .map_err(|source| path_error(&self.path, source))
    }

    /// Reads exactly `output.len()` bytes at `offset` with one positioned read where possible.
    fn read_file(&self, offset: usize, output: &mut [u8]) -> io::Result<()> {
        #[cfg(test)]
        {
            self.bytes_read
                .fetch_add(output.len(), std::sync::atomic::Ordering::Relaxed);
            counters::OS_READS.with(|reads| reads.set(reads.get() + 1));
        }
        read_exact_at(&self.file, offset as u64, output)
    }

    fn bytes(&self, start: usize, end: usize) -> Result<Vec<u8>, Error> {
        let mut bytes = vec![0; end - start];
        self.read_at(start, &mut bytes)?;
        Ok(bytes)
    }

    fn check_unchanged(&self) -> Result<(), Error> {
        let current = Stamp::read(&self.file).map_err(|source| path_error(&self.path, source))?;
        if current != self.stamp {
            return Err(Error::PackChanged {
                path: self.path.clone(),
            });
        }
        Ok(())
    }

    fn check_not_truncated(&self) -> Result<(), Error> {
        let current = self
            .file
            .metadata()
            .map_err(|source| path_error(&self.path, source))?
            .len();
        if current < self.len as u64 {
            return Err(path_error(&self.path, io::ErrorKind::UnexpectedEof.into()));
        }
        Ok(())
    }
}

/// Identity and content-generation metadata of the open handle, never the current pathname.
#[derive(Debug, Eq, PartialEq)]
struct Stamp {
    len: u64,
    modified: std::time::SystemTime,
    identity: (u64, u64),
}

impl Stamp {
    fn read(file: &File) -> io::Result<Self> {
        let metadata = file.metadata()?;
        #[cfg(unix)]
        let identity = {
            use std::os::unix::fs::MetadataExt;
            (metadata.dev(), metadata.ino())
        };
        #[cfg(windows)]
        let identity = {
            use std::os::windows::io::AsRawHandle;

            use windows_sys::Win32::Storage::FileSystem::{
                BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle,
            };
            let mut info = std::mem::MaybeUninit::<BY_HANDLE_FILE_INFORMATION>::uninit();
            // SAFETY: file owns a live handle and info points to writable, correctly sized storage.
            if unsafe { GetFileInformationByHandle(file.as_raw_handle(), info.as_mut_ptr()) } == 0 {
                return Err(io::Error::last_os_error());
            }
            // SAFETY: a successful call initializes every field of BY_HANDLE_FILE_INFORMATION.
            let info = unsafe { info.assume_init() };
            (
                u64::from(info.dwVolumeSerialNumber),
                (u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow),
            )
        };
        #[cfg(not(any(unix, windows)))]
        let identity = (0, 0);
        Ok(Self {
            len: metadata.len(),
            modified: metadata.modified()?,
            identity,
        })
    }
}

#[cfg(unix)]
fn read_exact_at(file: &File, offset: u64, output: &mut [u8]) -> io::Result<()> {
    std::os::unix::fs::FileExt::read_exact_at(file, output, offset)
}

#[cfg(windows)]
fn read_exact_at(file: &File, mut offset: u64, mut output: &mut [u8]) -> io::Result<()> {
    // Positioned reads on Windows move the shared cursor, which no other read here relies on.
    while !output.is_empty() {
        match std::os::windows::fs::FileExt::seek_read(file, output, offset) {
            Ok(0) => return Err(io::ErrorKind::UnexpectedEof.into()),
            Ok(count) => {
                output = output.get_mut(count..).ok_or(io::ErrorKind::InvalidData)?;
                offset += count as u64;
            }
            Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
            Err(error) => return Err(error),
        }
    }
    Ok(())
}

/// Per-thread observations of pack I/O, so tests can bound how often a walk touches storage.
#[cfg(test)]
pub(crate) mod counters {
    use std::cell::{Cell, RefCell};
    use std::collections::HashMap;

    thread_local! {
        /// Reads issued to the operating system for any pinned artifact.
        pub(crate) static OS_READS: Cell<usize> = const { Cell::new(0) };
        /// Inflations started per pack entry offset, including partial delta-header inflations.
        pub(crate) static INFLATIONS: RefCell<HashMap<usize, usize>> = RefCell::new(HashMap::new());
    }

    pub(crate) fn inflated(offset: usize) {
        INFLATIONS.with(|map| *map.borrow_mut().entry(offset).or_default() += 1);
    }

    pub(crate) fn reset() {
        OS_READS.with(|reads| reads.set(0));
        INFLATIONS.with(|map| map.borrow_mut().clear());
    }
}

fn path_error(path: &Path, source: io::Error) -> Error {
    Error::Path {
        path: path.to_owned(),
        source,
    }
}

/// Validated index bytes and bounded entry tables remain in memory; the original file stays pinned.
#[derive(Debug)]
pub(crate) struct FilePack {
    index: Artifact,
    index_bytes: Vec<u8>,
    pack: Artifact,
    format: ObjectFormat,
    table: Index,
    /// Set once the index's own checksum has been verified, before its identities label reused
    /// bytes.
    index_verified: std::sync::OnceLock<()>,
    base_cache: super::reader::BaseCache,
}

impl FilePack {
    pub(crate) fn check_unchanged(&self) -> Result<(), Error> {
        self.pack.check_unchanged()?;
        self.index.check_unchanged()
    }

    pub(crate) fn open(
        format: ObjectFormat,
        path: &Path,
        budget: &mut crate::PackLimits,
        cancelled: &AtomicBool,
    ) -> Result<Self, Error> {
        Self::open_after_index(format, path, budget, cancelled, || {})
    }

    // The checkpoint permits deterministic publication interleavings without sleeps or global
    // hooks. Production has no callback work between the two artifact opens.
    fn open_after_index(
        format: ObjectFormat,
        path: &Path,
        budget: &mut crate::PackLimits,
        cancelled: &AtomicBool,
        after_index: impl FnOnce(),
    ) -> Result<Self, Error> {
        check_cancelled(cancelled)?;
        let index_file = Artifact::open(path)?;
        after_index();
        let pack = Artifact::open(&path.with_extension("pack"))?;
        let bytes = index_file
            .len
            .checked_add(pack.len)
            .ok_or(Error::Limit("pack snapshot bytes"))?;
        budget.max_bytes = budget
            .max_bytes
            .checked_sub(bytes)
            .ok_or(Error::Limit("pack snapshot bytes"))?;
        // Charge the input before reading. Derived tables have at most one entry per 24 input
        // bytes, so a conservative fourfold bound also covers parsing and conversion overlap.
        budget.max_index_bytes = budget
            .max_index_bytes
            .checked_sub(index_file.len)
            .ok_or(Error::Limit("pack index bytes"))?;
        if pack.len < 12 + format.digest_len() {
            return Err(Error::Corrupt("pack header"));
        }
        let header = pack.bytes(0, 12)?;
        if !header.starts_with(b"PACK") {
            return Err(Error::Corrupt("pack header"));
        }
        let version = word(&header, 4)?;
        if !matches!(version, 2 | 3) {
            return Err(Error::PackVersion(version));
        }
        let end = pack.len - format.digest_len();
        let index_bytes = index_file.bytes(0, index_file.len)?;
        check_cancelled(cancelled)?;
        let index = Index::parse(format, &index_bytes, end)?;
        check_cancelled(cancelled)?;
        if word(&header, 8)? as usize != index.len() {
            return Err(Error::Corrupt("pack object count"));
        }
        let trailer = pack.bytes(end, pack.len)?;
        if index.pack_hash.as_bytes() != trailer {
            return Err(Error::Corrupt("index/pack checksum disagreement"));
        }
        check_cancelled(cancelled)?;
        Ok(Self {
            index: index_file,
            index_bytes,
            pack,
            format,
            table: index,
            index_verified: std::sync::OnceLock::new(),
            base_cache: super::reader::BaseCache::new(),
        })
    }

    /// Binds receive-time identity evidence to this pinned representation, not a pathname or
    /// claimed checksum. The index retained by this reader must agree byte for byte as well.
    #[expect(
        clippy::indexing_slicing,
        reason = "every buffer slice ends at a count bounded by that buffer's length"
    )]
    pub(crate) fn matches_received(
        &self,
        index: &[u8],
        mut received: impl Read,
        len: usize,
        cancel: &AtomicBool,
    ) -> Result<bool, Error> {
        if self.index_bytes != index || self.pack.len != len {
            return Ok(false);
        }
        self.index.check_not_truncated()?;
        self.pack.check_not_truncated()?;
        let mut expected = [0; 64 * 1024];
        let mut actual = [0; 64 * 1024];
        let mut offset = 0;
        let end = len - self.format.digest_len();
        let mut hash = Hasher::new(self.format);
        while offset < len {
            check_cancelled(cancel)?;
            let count = expected.len().min(len - offset);
            received
                .read_exact(&mut expected[..count])
                .map_err(|source| path_error(&self.pack.path, source))?;
            self.pack.read_at(offset, &mut actual[..count])?;
            if expected[..count] != actual[..count] {
                return Ok(false);
            }
            if offset < end {
                hash.update(&actual[..count.min(end - offset)]);
            }
            offset += count;
        }
        if Some(hash.finalize().as_bytes()) != pack_hash(self.format, index) {
            return Ok(false);
        }
        check_cancelled(cancel)?;
        Ok(true)
    }

    /// Checks the index checksum, the entire pinned pack checksum and every v2 entry CRC without
    /// decoding objects.
    #[expect(
        clippy::indexing_slicing,
        reason = "every buffer slice ends at a count bounded by that buffer's length"
    )]
    pub(crate) fn verify(&self, cancelled: &AtomicBool) -> Result<(), Error> {
        check_cancelled(cancelled)?;
        self.verify_index()?;
        self.pack.check_not_truncated()?;
        let pack = &self.pack;
        let format = self.format;
        let end = pack.len - format.digest_len();
        let mut hash = Hasher::new(format);
        hash.update(&pack.bytes(0, 12)?);
        let mut buffer = [0; 64 * 1024];
        for &position in &self.table.offsets {
            let entry = self.entry(position)?;
            let mut offset = entry.offset;
            let mut crc = crc32fast::Hasher::new();
            while offset < entry.end {
                check_cancelled(cancelled)?;
                let count = buffer.len().min(entry.end - offset);
                pack.read_at(offset, &mut buffer[..count])?;
                hash.update(&buffer[..count]);
                crc.update(&buffer[..count]);
                offset += count;
            }
            if entry.crc.is_some_and(|expected| crc.finalize() != expected) {
                return Err(Error::Corrupt("entry CRC"));
            }
        }
        let trailer = pack.bytes(end, pack.len)?;
        if hash.finalize().as_bytes() != trailer {
            return Err(Error::Corrupt("pack checksum"));
        }
        if pack_hash(format, &self.index_bytes) != Some(&trailer[..]) {
            return Err(Error::Corrupt("index/pack checksum disagreement"));
        }
        check_cancelled(cancelled)
    }

    /// Checks the pinned index's own trailing checksum, once per reader.
    ///
    /// Opening validates only the index structure. Anything that trusts the index's identities
    /// without hashing the objects they name, such as copying entries into a new pack, checks this
    /// first so a damaged name cannot label other bytes.
    pub(crate) fn verify_index(&self) -> Result<(), Error> {
        if self.index_verified.get().is_some() {
            return Ok(());
        }
        self.index.check_not_truncated()?;
        verify_hash(self.format, &self.index_bytes, "index checksum")?;
        let _ = self.index_verified.set(());
        Ok(())
    }

    pub(crate) fn find(&self, id: ObjectId) -> Result<Option<usize>, Error> {
        if id.format() != self.format {
            return Ok(None);
        }
        // Retained identities cannot turn a truncated pinned index into a successful lookup.
        self.index.check_not_truncated()?;
        Ok(self.table.find(&self.index_bytes, id))
    }

    /// Pack offset of the entry at index `position`.
    #[expect(
        clippy::indexing_slicing,
        reason = "callers pass positions below len() from this pack's own index"
    )]
    pub(crate) fn offset(&self, position: usize) -> usize {
        self.table.ranges[position].0
    }

    fn identity(&self, position: usize) -> Result<ObjectId, Error> {
        Ok(self.table.identity(&self.index_bytes, position))
    }

    /// Iterates identities from the validated pinned index without decoding their payloads.
    pub(crate) fn identities(&self) -> impl Iterator<Item = Result<ObjectId, Error>> + '_ {
        (0..self.table.len()).map(|position| self.identity(position))
    }

    /// Reads entry/delta headers only. Payload identity and CRC remain the reader's job.
    pub(crate) fn locate(
        &self,
        position: usize,
        limits: ReadLimits,
        cancel: &AtomicBool,
    ) -> Result<(ObjectKind, u64), Error> {
        self.locate_memoized(position, limits, cancel, &mut BaseKinds::new())
    }

    /// Locates like [`Self::locate`], sharing resolved delta chains across calls through `known`.
    ///
    /// Objects in one delta family share bases, so a batch reads each chain header once. `known`
    /// must only be used with this pack.
    pub(crate) fn locate_memoized(
        &self,
        mut position: usize,
        limits: ReadLimits,
        cancel: &AtomicBool,
        known: &mut BaseKinds,
    ) -> Result<(ObjectKind, u64), Error> {
        let mut seen = Vec::new();
        let mut visited = std::collections::HashSet::new();
        let mut result_size = None;
        let resolved = loop {
            check_cancelled(cancel)?;
            // The requested entry is always read: its own header or delta prefix gives its size.
            if !seen.is_empty()
                && let Some(&(kind, depth)) = known.get(&position)
            {
                // A known chain is acyclic and within its own depth; check the combined depth.
                if seen.len() + depth > limits.max_delta_depth {
                    return Err(Error::Limit("delta depth"));
                }
                break (kind, depth + 1);
            }
            if !visited.insert(position) {
                return Err(Error::Corrupt("delta cycle"));
            }
            seen.push(position);
            let entry = self.entry(position)?;
            let header = super::reader::entry_header(self, &entry)?;
            if let Some(base) = header.base {
                if seen.len() > limits.max_delta_depth {
                    return Err(Error::Limit("delta depth"));
                }
                if result_size.is_none() {
                    result_size = Some(self.delta_result_size(&entry, &header)? as u64);
                }
                position = base;
            } else {
                let kind = match header.kind {
                    1 => ObjectKind::Commit,
                    2 => ObjectKind::Tree,
                    3 => ObjectKind::Blob,
                    4 => ObjectKind::Tag,
                    _ => return Err(Error::Corrupt("pack entry kind")),
                };
                if result_size.is_none() {
                    result_size = Some(header.length as u64);
                }
                break (kind, 0);
            }
        };
        let (kind, base_depth) = resolved;
        for (depth, position) in seen.iter().rev().enumerate() {
            known.insert(*position, (kind, base_depth + depth));
        }
        // The first iteration always reads the requested entry and records its size.
        let size = result_size.ok_or(Error::Corrupt("pack entry size"))?;
        if size > limits.max_object_bytes as u64 {
            return Err(Error::Limit("object bytes"));
        }
        Ok((kind, size))
    }

    pub(crate) fn read(
        &self,
        position: usize,
        limits: ReadLimits,
        cancelled: &AtomicBool,
    ) -> Result<Object, Error> {
        decode(self, position, limits, cancelled)
    }

    /// Inflates only a delta entry's two leading size varints and returns the result size.
    ///
    /// The varints are the first output bytes, so the zlib bytes read with the header nearly
    /// always hold them; otherwise the entry is streamed from the file. No instructions or base
    /// bytes are inflated, and the entry CRC is left to full reads.
    fn delta_result_size(&self, entry: &Entry, header: &EntryHeader) -> Result<usize, Error> {
        thread_local! {
            // Reused across entries: creating an inflater allocates and clears its window.
            static INFLATER: std::cell::RefCell<flate2::Decompress> =
                std::cell::RefCell::new(flate2::Decompress::new(true));
        }
        #[cfg(test)]
        counters::inflated(entry.offset);
        // Two size varints, each at most ten bytes on a 64-bit host.
        let mut prefix = [0; 20];
        let produced = INFLATER.with(|inflater| {
            let mut inflater = inflater.borrow_mut();
            inflater.reset(true);
            let status = inflater
                .decompress(&header.ahead, &mut prefix, flate2::FlushDecompress::None)
                .map_err(|_| Error::Corrupt("delta size prefix"))?;
            let produced = inflater.total_out() as usize;
            let complete = produced == prefix.len() || status == flate2::Status::StreamEnd;
            Ok::<_, Error>(
                (complete || header.ahead.len() == entry.end - header.data_start)
                    .then_some(produced),
            )
        })?;
        let produced = match produced {
            Some(produced) => produced,
            None => {
                let range = Range::entry(&self.pack, entry, header, None);
                let mut decoder = flate2::read::ZlibDecoder::new_with_buf(range, vec![0; 256]);
                let mut produced = 0;
                while produced < prefix.len() {
                    let Some(unfilled) = prefix.get_mut(produced..) else {
                        break;
                    };
                    match decoder.read(unfilled) {
                        Ok(0) => break,
                        Ok(count) => produced += count,
                        Err(error) if error.kind() == io::ErrorKind::Interrupted => {}
                        Err(_) => return Err(Error::Corrupt("delta size prefix")),
                    }
                }
                produced
            }
        };
        let mut input = prefix
            .get(..produced)
            .ok_or(Error::Corrupt("delta size prefix"))?;
        super::delta::size(&mut input, 0, 0, true)?;
        super::delta::size(&mut input, 0, 0, true)
    }

    /// Decodes with every check of [`Self::read`] except the requested object's identity hash.
    pub(crate) fn read_unverified(
        &self,
        position: usize,
        limits: ReadLimits,
        cancelled: &AtomicBool,
    ) -> Result<crate::UnverifiedObject, Error> {
        let mut remaining = limits.max_decode_bytes;
        let object = super::reader::decode_checked(
            self,
            position,
            limits,
            cancelled,
            &mut remaining,
            super::reader::Identity::Skip,
        )?;
        Ok(crate::UnverifiedObject {
            kind: object.kind,
            data: object.data,
        })
    }
}

/// Resolved kinds and delta depths of entries in one pack, keyed by entry index.
pub(crate) type BaseKinds = std::collections::HashMap<usize, (ObjectKind, usize)>;

/// Keeps source corruption distinct from output failures during raw reuse.
#[derive(Debug, thiserror::Error)]
pub(crate) enum CopyError {
    #[error(transparent)]
    Read(#[from] Error),
    #[error("write reused entry")]
    Write(#[source] io::Error),
}

impl FilePack {
    /// Reads only framing and delta size prefixes, never a reconstructed blob payload.
    pub(crate) fn object_header(
        &self,
        position: usize,
        limits: ReadLimits,
    ) -> Result<(crate::ObjectKind, usize), Error> {
        let mut current = position;
        let mut length = None;
        let mut seen = std::collections::HashSet::new();
        loop {
            if !seen.insert(current) {
                return Err(Error::Corrupt("delta cycle"));
            }
            let entry = self.entry(current)?;
            let header = super::reader::entry_header(self, &entry)?;
            if let Some(base) = header.base {
                if seen.len() > limits.max_delta_depth {
                    return Err(Error::Limit("delta depth"));
                }
                if header.length > limits.max_delta_bytes {
                    return Err(Error::Limit("delta bytes"));
                }
                if length.is_none() {
                    length = Some(self.delta_result_size(&entry, &header)?);
                }
                current = base;
            } else {
                let kind = match header.kind {
                    1 => crate::ObjectKind::Commit,
                    2 => crate::ObjectKind::Tree,
                    3 => crate::ObjectKind::Blob,
                    4 => crate::ObjectKind::Tag,
                    other => return Err(Error::ObjectType(other)),
                };
                let length = length.unwrap_or(header.length);
                if length > limits.max_object_bytes {
                    return Err(Error::Limit("object bytes"));
                }
                return Ok((kind, length));
            }
        }
    }

    /// Copies an entry's bytes while checking the original framing and stream CRC.
    pub(crate) fn copy_raw(
        &self,
        entry: &Entry,
        header: &EntryHeader,
        output: &mut impl io::Write,
    ) -> Result<(), CopyError> {
        let delta = header.base.is_some();
        let start = if delta {
            header.data_start
        } else {
            entry.offset
        };
        let crc = entry.crc.map(|_| {
            let mut crc = crc32fast::Hasher::new();
            if delta {
                crc.update(&header.encoded);
            }
            crc
        });
        let mut ahead = Vec::new();
        if !delta {
            ahead.extend_from_slice(&header.encoded);
        }
        ahead.extend_from_slice(&header.ahead);
        let input = Range {
            artifact: &self.pack,
            ahead: &ahead,
            position: start + ahead.len(),
            end: entry.end,
            crc,
        };
        let mut input = BufReader::with_capacity(64 * 1024, input);
        loop {
            let bytes = input
                .fill_buf()
                .map_err(|source| path_error(&self.pack.path, source))?;
            if bytes.is_empty() {
                break;
            }
            output.write_all(bytes).map_err(CopyError::Write)?;
            let count = bytes.len();
            input.consume(count);
        }
        input.get_ref().verify_crc(entry.crc)?;
        Ok(())
    }
}

impl Source for FilePack {
    fn format(&self) -> ObjectFormat {
        self.format
    }

    fn entry(&self, position: usize) -> Result<Entry, Error> {
        Ok(self.table.entry(&self.index_bytes, position))
    }

    fn find(&self, id: ObjectId) -> Result<Option<usize>, Error> {
        self.find(id)
    }

    fn base_cache(&self) -> Option<&super::reader::BaseCache> {
        Some(&self.base_cache)
    }

    fn at_offset(&self, offset: usize) -> Result<usize, Error> {
        self.table.at_offset(offset)
    }

    /// Reads the header with up to 4 KiB of the entry, so a typical entry needs one read.
    fn prefix(&self, entry: &Entry) -> Result<Vec<u8>, Error> {
        window::bytes(
            &self.pack,
            entry.offset,
            entry.end.min(entry.offset.saturating_add(4096)),
        )
    }

    #[expect(
        clippy::indexing_slicing,
        reason = "every buffer slice ends at a count bounded by that buffer's length"
    )]
    fn inflate(
        &self,
        entry: &Entry,
        header: &EntryHeader,
        cancelled: &AtomicBool,
    ) -> Result<Vec<u8>, Error> {
        #[cfg(test)]
        counters::inflated(entry.offset);
        let start = header.data_start;
        let end = entry.end;
        let expected = header.length;
        let mut crc = entry.crc.map(|_| {
            let mut crc = crc32fast::Hasher::new();
            crc.update(&header.encoded);
            crc.update(&header.ahead);
            crc
        });
        // Input comes from the bytes read with the header, then from exact-sized positioned
        // reads of the rest of the entry; neither is zero-filled beyond what is read.
        const CHUNK: usize = 256 * 1024;
        let mut chunk = Vec::new();
        let mut from_ahead = true;
        let mut consumed_in_chunk = 0;
        let mut position = start + header.ahead.len();
        let mut decoder = flate2::Decompress::new(true);
        // The declared size is unproven until the stream produces it: reserve a bounded start
        // and grow with the output, so a tiny malformed entry cannot request a huge buffer.
        let mut data = Vec::with_capacity(expected.min(super::delta::INITIAL_RESERVATION));
        let mut overflow = [0; 1];
        loop {
            check_cancelled(cancelled)?;
            let source = if from_ahead {
                &header.ahead[..]
            } else {
                &chunk[..]
            };
            if consumed_in_chunk == source.len() && position < end {
                let count = CHUNK.min(end - position);
                chunk.clear();
                chunk.resize(count, 0);
                self.pack.read_at(position, &mut chunk)?;
                if let Some(crc) = &mut crc {
                    crc.update(&chunk);
                }
                position += count;
                from_ahead = false;
                consumed_in_chunk = 0;
            }
            let input = if from_ahead {
                &header.ahead[consumed_in_chunk..]
            } else {
                &chunk[consumed_in_chunk..]
            };
            let before_in = decoder.total_in();
            let before_out = decoder.total_out();
            if data.len() == data.capacity() && data.len() < expected {
                data.reserve_exact((expected - data.len()).min(data.len().max(4096)));
            }
            let status = if data.len() < expected {
                decoder.decompress_vec(input, &mut data, flate2::FlushDecompress::None)
            } else {
                decoder.decompress(input, &mut overflow, flate2::FlushDecompress::None)
            }
            .map_err(|_| Error::Corrupt("invalid packed zlib stream"))?;
            let consumed = (decoder.total_in() - before_in) as usize;
            let count = (decoder.total_out() - before_out) as usize;
            consumed_in_chunk += consumed;
            if decoder.total_out() > expected as u64 {
                return Err(Error::Corrupt("inflated entry exceeds declared size"));
            }
            if status == flate2::Status::StreamEnd {
                if data.len() != expected || decoder.total_in() != (end - start) as u64 {
                    return Err(Error::Corrupt("packed entry length or trailing data"));
                }
                break;
            }
            if consumed == 0 && count == 0 {
                return Err(Error::Corrupt("truncated packed zlib stream"));
            }
        }
        if let (Some(expected), Some(crc)) = (entry.crc, crc)
            && crc.finalize() != expected
        {
            return Err(Error::Corrupt("entry CRC"));
        }
        Ok(data)
    }
}

/// The pack checksum an index records just before its own trailing checksum.
fn pack_hash(format: ObjectFormat, index: &[u8]) -> Option<&[u8]> {
    let width = format.digest_len();
    let start = index.len().checked_sub(2 * width)?;
    index.get(start..start + width)
}

/// A bounded cursor whose reads never disturb another lookup's logical position.
///
/// Bytes already read with the entry header are served from `ahead` before the file is read.
struct Range<'a> {
    artifact: &'a Artifact,
    ahead: &'a [u8],
    position: usize,
    end: usize,
    crc: Option<crc32fast::Hasher>,
}

impl<'a> Range<'a> {
    /// Streams an entry's zlib data from `data_start`, starting with the header's read-ahead.
    fn entry(
        artifact: &'a Artifact,
        entry: &Entry,
        header: &'a EntryHeader,
        crc: Option<crc32fast::Hasher>,
    ) -> Self {
        Self {
            artifact,
            ahead: &header.ahead,
            position: header.data_start + header.ahead.len(),
            end: entry.end,
            crc,
        }
    }
}

impl Range<'_> {
    fn verify_crc(&self, expected: Option<u32>) -> Result<(), Error> {
        if let Some(expected) = expected {
            // Entries with a recorded CRC always stream with a hasher; fail closed otherwise.
            let crc = self.crc.as_ref().ok_or(Error::Corrupt("entry CRC"))?;
            let actual = crc.clone().finalize();
            if actual != expected {
                return Err(Error::Corrupt("entry CRC"));
            }
        }
        Ok(())
    }
}

impl Read for Range<'_> {
    #[expect(
        clippy::indexing_slicing,
        reason = "every buffer slice ends at a count bounded by that buffer's length"
    )]
    fn read(&mut self, output: &mut [u8]) -> io::Result<usize> {
        if !self.ahead.is_empty() {
            let count = output.len().min(self.ahead.len());
            output[..count].copy_from_slice(&self.ahead[..count]);
            self.ahead = &self.ahead[count..];
            if let Some(crc) = &mut self.crc {
                crc.update(&output[..count]);
            }
            return Ok(count);
        }
        let count = output.len().min(self.end - self.position);
        if count == 0 {
            return Ok(0);
        }
        self.artifact
            .read_file(self.position, &mut output[..count])?;
        if let Some(crc) = &mut self.crc {
            crc.update(&output[..count]);
        }
        self.position += count;
        Ok(count)
    }
}

#[cfg(test)]
mod publication_tests {
    use std::fs;

    use rstest::rstest;

    use super::*;
    use crate::{ObjectKind, PackLimits, PackObject, PackWriteLimits};

    fn pair(root: &Path, name: &str, format: ObjectFormat, data: &[u8]) -> PathBuf {
        let object = PackObject {
            id: ObjectId::for_blob(format, data),
            kind: ObjectKind::Blob,
            data,
        };
        let (mut pack, mut index) = (Vec::new(), Vec::new());
        crate::write_pack(
            format,
            &[object],
            &mut pack,
            &mut index,
            PackWriteLimits::default(),
        )
        .unwrap();
        let path = root.join(name).with_extension("idx");
        fs::write(&path, index).unwrap();
        fs::write(path.with_extension("pack"), pack).unwrap();
        path
    }

    // Original malformed framing, with independent artifact checksums and CRCs rebuilt so the
    // encoded-entry parser, rather than the outer checksum validator, rejects it.
    fn malformed_pair(root: &Path, framing: &[u8]) -> PathBuf {
        let format = ObjectFormat::Sha1;
        let id = ObjectId::for_blob(format, b"fixture");
        let mut bytes = b"PACK\0\0\0\x02\0\0\0\x01".to_vec();
        bytes.extend_from_slice(framing);
        let checksum = format.checksum(&bytes);
        bytes.extend_from_slice(checksum.as_bytes());
        let entry = crate::pack::write::Entry {
            id,
            offset: 12,
            crc: crc32fast::hash(framing),
        };
        let index = crate::pack::write::encode_index(&[entry], checksum).unwrap();
        let path = root.join("malformed.idx");
        fs::write(&path, index).unwrap();
        fs::write(path.with_extension("pack"), bytes).unwrap();
        path
    }

    #[rstest]
    #[case::sha1(ObjectFormat::Sha1)]
    #[case::sha256(ObjectFormat::Sha256)]
    fn open_does_not_read_pack_body(#[case] format: ObjectFormat) {
        let root = tempfile::tempdir().unwrap();
        let mut state = 123456789u64;
        let data: Vec<u8> = (0..2 * 1024 * 1024)
            .map(|_| {
                state ^= state << 13;
                state ^= state >> 7;
                state ^= state << 17;
                state as u8
            })
            .collect();
        let path = pair(root.path(), "large", format, &data);
        let reader = FilePack::open(
            format,
            &path,
            &mut PackLimits::default(),
            &AtomicBool::new(false),
        )
        .unwrap();
        assert!(reader.pack.len > 1024 * 1024);
        let opened_bytes = reader
            .pack
            .bytes_read
            .load(std::sync::atomic::Ordering::Relaxed);
        assert_eq!(opened_bytes, 12 + format.digest_len());
        reader.verify(&AtomicBool::new(false)).unwrap();
        assert_eq!(
            reader
                .pack
                .bytes_read
                .load(std::sync::atomic::Ordering::Relaxed),
            opened_bytes + reader.pack.len
        );
    }

    #[rstest]
    #[case::reserved(&[0x50, 0])]
    #[case::truncated_size(&[0xb0])]
    #[case::zero_distance(&[0x60, 0])]
    #[case::before_pack(&[0x60, 127])]
    #[case::truncated_reference(&[0x70, 1])]
    #[case::missing_reference(&[0x70, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])]
    fn stored_entry_rejects_malformed_framing(#[case] framing: &[u8]) {
        let root = tempfile::tempdir().unwrap();
        let path = malformed_pair(root.path(), framing);
        let pack = FilePack::open(
            ObjectFormat::Sha1,
            &path,
            &mut PackLimits::default(),
            &AtomicBool::new(false),
        )
        .unwrap();
        let _scope = super::super::HeaderScope::new();
        assert!(super::super::reader::entry_header(&pack, &pack.entry(0).unwrap()).is_err());
    }

    #[rstest]
    #[case::sha1(ObjectFormat::Sha1)]
    #[case::sha256(ObjectFormat::Sha256)]
    fn removal_between_opens_is_path_error(#[case] format: ObjectFormat) {
        let root = tempfile::tempdir().unwrap();
        let path = pair(root.path(), "a", format, b"first");
        let result = FilePack::open_after_index(
            format,
            &path,
            &mut PackLimits::default(),
            &AtomicBool::new(false),
            || {
                fs::remove_file(path.with_extension("pack")).unwrap();
            },
        );
        assert!(
            matches!(result, Err(Error::Path { source, .. }) if source.kind() == io::ErrorKind::NotFound)
        );
    }

    #[rstest]
    #[case::sha1(ObjectFormat::Sha1)]
    #[case::sha256(ObjectFormat::Sha256)]
    fn different_valid_pair_between_opens_is_rejected(#[case] format: ObjectFormat) {
        let root = tempfile::tempdir().unwrap();
        let path = pair(root.path(), "a", format, b"first");
        let replacement = pair(root.path(), "b", format, b"other");
        let result = FilePack::open_after_index(
            format,
            &path,
            &mut PackLimits::default(),
            &AtomicBool::new(false),
            || {
                fs::remove_file(path.with_extension("pack")).unwrap();
                fs::rename(
                    replacement.with_extension("pack"),
                    path.with_extension("pack"),
                )
                .unwrap();
            },
        );
        assert!(matches!(result, Err(Error::Corrupt(_))));
    }

    #[rstest]
    #[case::sha1(ObjectFormat::Sha1)]
    #[case::sha256(ObjectFormat::Sha256)]
    fn index_path_replacement_keeps_pinned_index(#[case] format: ObjectFormat) {
        let root = tempfile::tempdir().unwrap();
        let path = pair(root.path(), "a", format, b"first");
        let replacement = pair(root.path(), "b", format, b"other");
        let reader = FilePack::open_after_index(
            format,
            &path,
            &mut PackLimits::default(),
            &AtomicBool::new(false),
            || {
                fs::rename(&path, path.with_extension("old")).unwrap();
                fs::rename(replacement, &path).unwrap();
            },
        )
        .unwrap();
        let id = ObjectId::for_blob(format, b"first");
        let value = reader
            .read(
                reader.find(id).unwrap().unwrap(),
                ReadLimits::default(),
                &AtomicBool::new(false),
            )
            .unwrap();
        assert_eq!(value.data(), b"first");
        assert!(matches!(
            FilePack::open(
                format,
                &path,
                &mut PackLimits::default(),
                &AtomicBool::new(false)
            ),
            Err(Error::Corrupt(_))
        ));
    }
    #[test]
    fn header_windows_are_bounded_across_many_packs_and_drop_with_scope() {
        let root = tempfile::tempdir().unwrap();
        let paths: Vec<_> = (0..32)
            .map(|i| {
                pair(
                    root.path(),
                    &format!("p{i}"),
                    ObjectFormat::Sha1,
                    &[i as u8; 128],
                )
            })
            .collect();
        let packs: Vec<_> = paths
            .iter()
            .map(|path| {
                FilePack::open(
                    ObjectFormat::Sha1,
                    path,
                    &mut PackLimits::trusted(),
                    &AtomicBool::new(false),
                )
                .unwrap()
            })
            .collect();
        let scope = super::super::HeaderScope::new();
        for pack in &packs {
            pack.prefix(&pack.entry(0).unwrap()).unwrap();
            assert!(super::window::allocated() <= 256 * 1024);
        }
        drop(scope);
        assert_eq!(super::window::allocated(), 0);
    }

    #[rstest]
    #[case::cross_window(256 * 1024 - 2, 256 * 1024 + 4)]
    #[case::final_bytes(512 * 1024 - 3, 512 * 1024)]
    #[case::empty_eof(512 * 1024, 512 * 1024)]
    fn header_window_boundaries(#[case] start: usize, #[case] end: usize) {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("bytes.pack");
        let bytes: Vec<_> = (0..512 * 1024).map(|i| (i % 251) as u8).collect();
        fs::write(&path, &bytes).unwrap();
        let artifact = super::Artifact::open(&path).unwrap();
        let _scope = super::super::HeaderScope::new();
        super::window::bytes(&artifact, 0, 4096).unwrap();
        let _ordered = super::super::HeaderScope::ordered();
        super::window::bytes(&artifact, 0, 8192).unwrap();
        assert_eq!(
            super::window::bytes(&artifact, start, end).unwrap(),
            bytes[start..end]
        );
        assert!(super::window::bytes(&artifact, 512 * 1024, 512 * 1024 + 1).is_err());
        assert!(super::window::bytes(&artifact, usize::MAX, 0).is_err());
    }

    #[cfg(windows)]
    #[test]
    fn pinned_pack_denies_writers_but_allows_rename_and_delete() {
        use std::os::windows::fs::OpenOptionsExt;

        use windows_sys::Win32::Storage::FileSystem::{
            FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
        };
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("shared.pack");
        fs::write(&path, b"pinned bytes").unwrap();
        let artifact = super::Artifact::open(&path).unwrap();
        let writer = fs::OpenOptions::new()
            .write(true)
            .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
            .open(&path);
        assert!(writer.is_err());
        let renamed = root.path().join("renamed.pack");
        fs::rename(&path, &renamed).unwrap();
        fs::remove_file(&renamed).unwrap();
        artifact.check_unchanged().unwrap();
        assert_eq!(artifact.bytes(0, 12).unwrap(), b"pinned bytes");
    }

    #[cfg(windows)]
    #[test]
    fn pinned_pack_allows_attribute_only_freshening_and_detects_it() {
        use std::os::windows::fs::OpenOptionsExt;

        use windows_sys::Win32::Storage::FileSystem::{
            FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_WRITE_ATTRIBUTES,
        };
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("freshened.pack");
        fs::write(&path, b"pinned bytes").unwrap();
        let artifact = super::Artifact::open(&path).unwrap();
        let attributes = fs::OpenOptions::new()
            .access_mode(FILE_WRITE_ATTRIBUTES)
            .share_mode(FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE)
            .open(&path)
            .unwrap();
        attributes
            .set_modified(std::time::UNIX_EPOCH + std::time::Duration::from_secs(42))
            .unwrap();
        assert_eq!(artifact.bytes(0, 12).unwrap(), b"pinned bytes");
        assert!(
            matches!(artifact.check_unchanged(), Err(Error::PackChanged { path: changed }) if changed == path)
        );
    }

    #[cfg(unix)]
    #[test]
    fn warmed_window_rename_replacement_keeps_pinned_original() {
        let root = tempfile::tempdir().unwrap();
        let path = root.path().join("old.pack");
        let replacement = root.path().join("new.pack");
        fs::write(&path, b"original").unwrap();
        fs::write(&replacement, b"replaced").unwrap();
        let artifact = super::Artifact::open(&path).unwrap();
        let _scope = super::super::HeaderScope::new();
        assert_eq!(super::window::bytes(&artifact, 0, 8).unwrap(), b"original");
        fs::rename(replacement, &path).unwrap();
        artifact.check_unchanged().unwrap();
        assert_eq!(super::window::bytes(&artifact, 0, 8).unwrap(), b"original");
    }
}