girt 0.11.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
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
use std::io::{self, Write};

use flate2::Compression;
use flate2::write::ZlibEncoder;

use super::compression::{DeltaOptions, DeltaStats, PackCompression, instructions};
use crate::object::Hasher;
use crate::{ObjectId, ObjectKind};

/// One format-bearing object to export, borrowing its exact uncompressed payload.
///
/// The writer verifies `id` against `kind` and `data`. Payload syntax and referenced object
/// existence are not checked; callers choose the object set and any graph validation. The kind
/// enum admits only blobs, trees, commits, and tags, never delta or reserved pack types.
///
/// Use this borrowed input when exporting a caller-selected set of objects. The ID is an
/// expectation checked against kind and bytes; it does not ask the writer to fetch data or validate
/// graph completeness.
///
/// ```
/// use girt::{
///     ObjectFormat, ObjectId, ObjectKind, PackObject, PackWriteError, PackWriteLimits, write_pack,
/// };
/// let input = PackObject {
///     id: ObjectId::for_blob(ObjectFormat::Sha1, b"original"),
///     kind: ObjectKind::Blob,
///     data: b"changed",
/// };
/// let (mut pack, mut index) = (Vec::new(), Vec::new());
/// assert!(matches!(
///     write_pack(
///         ObjectFormat::Sha1,
///         &[input],
///         &mut pack,
///         &mut index,
///         PackWriteLimits::default()
///     ),
///     Err(PackWriteError::Identity { .. })
/// ));
/// assert!(pack.is_empty() && index.is_empty());
/// ```
#[derive(Debug, Clone, Copy)]
pub struct PackObject<'a> {
    /// Expected identity, including the canonical Git kind/length header in the hash.
    pub id: ObjectId,
    /// Logical object kind.
    pub kind: ObjectKind,
    /// Exact payload without loose-object framing.
    pub data: &'a [u8],
}

/// Resource bounds for [`write_pack`], independent of the destination's buffering.
///
/// Input occurrences (including duplicates) are charged before sorting or hashing. Memory used by
/// the writer is proportional to that count, plus fixed compression scratch space; payloads are
/// borrowed and compressed directly to the sink by the ordinary policy. Delta compression adds
/// the scratch/work bounds documented on [`DeltaOptions`]. These are not total process heap limits.
///
/// Select input and output budgets separately: a small object count does not bound payload bytes,
/// and compressed output can fail after sinks have been touched. Keep artifacts private and discard
/// both after failure.
///
/// ```
/// use girt::{
///     ObjectFormat, ObjectId, ObjectKind, PackObject, PackWriteError, PackWriteLimits, write_pack,
/// };
/// let input = PackObject {
///     id: ObjectId::for_blob(ObjectFormat::Sha1, b"large"),
///     kind: ObjectKind::Blob,
///     data: b"large",
/// };
/// let (mut pack, mut index) = (Vec::new(), Vec::new());
/// let limits = PackWriteLimits::default().with_max_object_bytes(2);
/// assert!(matches!(
///     write_pack(ObjectFormat::Sha1, &[input], &mut pack, &mut index, limits),
///     Err(PackWriteError::Limit(_))
/// ));
/// assert!(pack.is_empty() && index.is_empty());
/// ```
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct PackWriteLimits {
    /// Maximum input occurrences, also bounded by `u32::MAX` (default one million).
    pub max_objects: u32,
    /// Maximum individual uncompressed payload length (default 64 MiB).
    pub max_object_bytes: u64,
    /// Maximum sum of input payload bytes, including duplicates (default 512 MiB).
    pub max_input_bytes: u64,
    /// Maximum pack bytes including header and checksum (default 512 MiB).
    pub max_pack_bytes: u64,
    /// Maximum index bytes including both checksums (default 64 MiB).
    pub max_index_bytes: u64,
}

impl PackWriteLimits {
    /// Sets [`Self::max_objects`].
    #[must_use]
    pub fn with_max_objects(mut self, max_objects: u32) -> Self {
        self.max_objects = max_objects;
        self
    }

    /// Sets [`Self::max_object_bytes`].
    #[must_use]
    pub fn with_max_object_bytes(mut self, max_object_bytes: u64) -> Self {
        self.max_object_bytes = max_object_bytes;
        self
    }

    /// Sets [`Self::max_input_bytes`].
    #[must_use]
    pub fn with_max_input_bytes(mut self, max_input_bytes: u64) -> Self {
        self.max_input_bytes = max_input_bytes;
        self
    }

    /// Sets [`Self::max_pack_bytes`].
    #[must_use]
    pub fn with_max_pack_bytes(mut self, max_pack_bytes: u64) -> Self {
        self.max_pack_bytes = max_pack_bytes;
        self
    }

    /// Sets [`Self::max_index_bytes`].
    #[must_use]
    pub fn with_max_index_bytes(mut self, max_index_bytes: u64) -> Self {
        self.max_index_bytes = max_index_bytes;
        self
    }
}

impl Default for PackWriteLimits {
    fn default() -> Self {
        Self {
            max_objects: 1_000_000,
            max_object_bytes: 64 * 1024 * 1024,
            max_input_bytes: 512 * 1024 * 1024,
            max_pack_bytes: 512 * 1024 * 1024,
            max_index_bytes: 64 * 1024 * 1024,
        }
    }
}

impl PackWriteLimits {
    /// Returns limits for pack writing the caller trusts as Git trusts the user's own repositories.
    ///
    /// Git bounds none of these values. The defaults suit untrusted input; these are large enough
    /// that only available memory bounds the work, while keeping headroom for internal arithmetic.
    pub const fn trusted() -> Self {
        const UNBOUNDED: u64 = u64::MAX / 4;
        Self {
            max_objects: u32::MAX,
            max_object_bytes: UNBOUNDED,
            max_input_bytes: UNBOUNDED,
            max_pack_bytes: UNBOUNDED,
            max_index_bytes: UNBOUNDED,
        }
    }
}

/// Completed artifact lengths and identity; no files have been installed by the library.
///
/// Inspect this receipt to name and account for the artifacts you just produced. Success is not
/// installation or reference publication; retain both outputs until a validated publication path
/// accepts them.
///
/// ```
/// use girt::{ObjectFormat, ObjectId, ObjectKind, PackObject, PackWriteLimits, write_pack};
/// let input = PackObject {
///     id: ObjectId::for_blob(ObjectFormat::Sha1, b"manifest"),
///     kind: ObjectKind::Blob,
///     data: b"manifest",
/// };
/// let (mut bytes, mut index) = (Vec::new(), Vec::new());
/// let written = write_pack(
///     ObjectFormat::Sha1,
///     &[input],
///     &mut bytes,
///     &mut index,
///     PackWriteLimits::default(),
/// )?;
/// assert_eq!(written.objects, 1);
/// assert!(bytes.ends_with(written.checksum.as_bytes()));
/// assert!(!index.is_empty());
/// # Ok::<(), girt::PackWriteError>(())
/// ```
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct PackWritten {
    /// Repository-format checksum of the pack before its trailer, suitable for a `pack-<hash>`
    /// basename.
    pub checksum: ObjectId,
    /// Number of distinct objects emitted.
    pub objects: u32,
    /// Total pack bytes, including its checksum.
    pub pack_bytes: u64,
    /// Total index bytes, including both checksums.
    pub index_bytes: u64,
    /// Delta search and dependency accounting; zero for the ordinary path.
    pub deltas: DeltaStats,
}

/// Failure to validate inputs or finish a caller-owned artifact pair.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum PackWriteError {
    /// A supplied identity differs from the selected pack format.
    /// Select one repository format for all inputs.
    #[error(transparent)]
    ObjectFormat(#[from] crate::ObjectFormatError),
    /// An expected identity does not match the supplied kind and bytes.
    /// Correct the caller-supplied ID, kind, or bytes; do not bypass hashing.
    #[error("object identity mismatch: expected {expected}, computed {actual}")]
    Identity {
        /// Caller-supplied identity.
        expected: ObjectId,
        /// Identity computed from the supplied kind and bytes.
        actual: ObjectId,
    },
    /// Equal identities had different kinds or payloads; no collision recovery is attempted.
    /// Inspect the conflicting payloads and stop publication; this API offers no collision
    /// recovery.
    #[error("conflicting input for object {0}")]
    ConflictingDuplicate(ObjectId),
    /// A configured resource bound or representable format limit was exceeded.
    /// Choose a justified input/output budget and discard both outputs before a fresh attempt.
    #[error("pack writing limit exceeded: {0}")]
    Limit(&'static str),
    /// A destination or compression operation failed; partial artifacts must be discarded.
    /// Discard both partial artifacts, inspect the source, and use fresh empty sinks when retrying.
    #[error("pack artifact I/O failed")]
    Io(#[from] io::Error),
}

/// Writes a pack v2 and matching index v2 in the explicitly selected object format.
///
/// `format` selects object IDs, REF_DELTA bases and both artifacts' checksums, including for an
/// empty set. Every input must use that format; no format inference or translation occurs.
///
/// Exact duplicates collapse to one entry. Both artifacts use ascending object-ID order,
/// independent of input order. Each ordinary entry uses zlib level 6, without deltas. Repeated
/// calls with the same objects and compression backend/version produce identical bytes; compressed
/// bytes are not promised stable across dependency upgrades. Similar objects can occupy much more
/// space than Git's delta-selected packs. No reachability selection or payload parsing occurs.
///
/// Sinks must be empty or positioned at the start of a separate artifact: offsets are relative to
/// this call's first byte. They need only implement [`Write`], not seeking. The pack is completed
/// and flushed before the index is written and flushed. Success does not promise disk durability.
/// The caller owns buffering, storage, cleanup, and installation; never pass live repository pack
/// paths directly. No existing packs or loose objects are removed. Validated received-pack
/// installation is available separately through [`crate::fetch`].
///
/// # Errors
///
/// Input count, payload bounds, identity formats/digests, and conflicting duplicates are checked
/// before either sink is touched. Output bounds, I/O, or flush failures can leave partial artifacts
/// (or a complete pack and incomplete index). Discard both on any error. Output counters use
/// checked `u64` arithmetic; index offsets at or above 2 GiB use the v2 large-offset table. The
/// number of large offsets cannot exceed 2^31. Allocation failure follows Rust's allocator
/// behavior.
///
/// ```
/// use girt::{ObjectId, ObjectKind, PackObject, PackWriteLimits, write_pack};
/// let input = PackObject {
///     id: ObjectId::for_blob(girt::ObjectFormat::Sha1, b"hello"),
///     kind: ObjectKind::Blob,
///     data: b"hello",
/// };
/// let (mut pack, mut index) = (Vec::new(), Vec::new());
/// let written = write_pack(
///     girt::ObjectFormat::Sha1,
///     &[input, input],
///     &mut pack,
///     &mut index,
///     PackWriteLimits::default(),
/// )?;
/// assert_eq!(written.objects, 1);
/// # Ok::<(), girt::PackWriteError>(())
/// ```
pub fn write_pack(
    format: crate::ObjectFormat,
    objects: &[PackObject<'_>],
    pack: &mut impl Write,
    index: &mut impl Write,
    limits: PackWriteLimits,
) -> Result<PackWritten, PackWriteError> {
    write_pack_with_compression(
        format,
        objects,
        pack,
        index,
        limits,
        PackCompression::Ordinary,
    )
}

/// Writes a pack/index pair with explicit bounded compression selection.
///
/// See [`write_pack`] for validation, ownership, output bounds, and partial-artifact errors, and
/// [`DeltaOptions`] for candidate ordering, memory/work bounds, reproducibility, and wire encoding.
/// The ordinary policy produces exactly [`write_pack`]'s bytes. Delta search exhaustion falls back
/// to the best completed entry, including ordinary encoding; it is not an error.
///
/// # Errors
///
/// Returns the same validation, resource, and I/O errors as [`write_pack`].
///
/// ```
/// use girt::{
///     DeltaOptions, ObjectId, ObjectKind, PackCompression, PackObject, PackWriteLimits,
///     write_pack_with_compression,
/// };
/// let base: Vec<u8> = (0..=255).cycle().take(4096).collect();
/// let mut edited = base.clone();
/// edited[1000] ^= 255;
/// let inputs: Vec<_> = [&base, &edited]
///     .into_iter()
///     .map(|data| PackObject {
///         id: ObjectId::for_blob(girt::ObjectFormat::Sha1, data),
///         kind: ObjectKind::Blob,
///         data,
///     })
///     .collect();
/// let (mut pack, mut index) = (Vec::new(), Vec::new());
/// let policy = PackCompression::Delta(DeltaOptions::default().with_max_depth(2));
/// let written = write_pack_with_compression(
///     girt::ObjectFormat::Sha1,
///     &inputs,
///     &mut pack,
///     &mut index,
///     PackWriteLimits::default(),
///     policy,
/// )?;
/// assert_eq!(written.objects, 2);
/// assert_eq!(written.deltas.entries, 1);
/// # Ok::<(), girt::PackWriteError>(())
/// ```
pub fn write_pack_with_compression(
    format: crate::ObjectFormat,
    objects: &[PackObject<'_>],
    pack: &mut impl Write,
    index: &mut impl Write,
    limits: PackWriteLimits,
    compression: PackCompression,
) -> Result<PackWritten, PackWriteError> {
    write_controlled(
        format,
        objects,
        pack,
        index,
        limits,
        compression,
        &mut || Ok(()),
    )
}

pub(crate) fn write_controlled(
    format: crate::ObjectFormat,
    objects: &[PackObject<'_>],
    pack: &mut impl Write,
    index: &mut impl Write,
    limits: PackWriteLimits,
    compression: PackCompression,
    check: &mut impl FnMut() -> Result<(), PackWriteError>,
) -> Result<PackWritten, PackWriteError> {
    write_controlled_observed(
        format,
        objects,
        (pack, index),
        limits,
        compression,
        check,
        &mut |_, _| {},
    )
}

pub(crate) fn write_controlled_observed(
    format: crate::ObjectFormat,
    objects: &[PackObject<'_>],
    outputs: (&mut impl Write, &mut impl Write),
    limits: PackWriteLimits,
    compression: PackCompression,
    check: &mut impl FnMut() -> Result<(), PackWriteError>,
    observe: &mut impl FnMut(u64, u64),
) -> Result<PackWritten, PackWriteError> {
    let (pack, index) = outputs;
    let objects = validate(format, objects, limits, check)?;
    check()?;
    let count = objects.len() as u32;
    observe(0, u64::from(count));
    check()?;
    let mut pack = Output::new(format, pack, limits.max_pack_bytes, "pack bytes");
    pack.put(b"PACK")?;
    pack.put(&2u32.to_be_bytes())?;
    pack.put(&count.to_be_bytes())?;
    let mut entries = Vec::with_capacity(objects.len());
    let mut depths = Vec::with_capacity(objects.len());
    let mut deltas = DeltaStats::default();
    for (position, object) in objects.iter().enumerate() {
        check()?;
        let selected = match compression {
            PackCompression::Ordinary => None,
            PackCompression::Delta(options) => {
                select_entry(&objects, position, &depths, options, &mut deltas, check)?
            }
        };
        let offset = pack.bytes;
        pack.crc = crc32fast::Hasher::new();
        if let Some(selected) = selected {
            pack.put(&selected.bytes)?;
            depths.push(selected.depth);
            if selected.depth != 0 {
                deltas.entries += 1;
                deltas.max_depth = deltas.max_depth.max(selected.depth);
            }
        } else {
            write_ordinary(&mut pack, object.kind, object.data)?;
            depths.push(0);
        }
        entries.push(Entry {
            id: object.id,
            offset,
            crc: pack.crc.clone().finalize(),
        });
        observe(position as u64 + 1, u64::from(count));
        check()?;
    }
    let checksum = pack.finish()?;
    let pack_bytes = pack.bytes;
    let mut index = Output::new(format, index, limits.max_index_bytes, "index bytes");
    write_index(&entries, checksum, &mut index)?;
    index.finish()?;
    Ok(PackWritten {
        checksum,
        objects: count,
        pack_bytes,
        index_bytes: index.bytes,
        deltas,
    })
}

/// Streams one whole-object entry: its header, then zlib level 6 payload.
pub(super) fn write_ordinary(
    pack: &mut Output<'_, impl Write>,
    kind: ObjectKind,
    data: &[u8],
) -> Result<(), PackWriteError> {
    pack.put(&entry_header(kind, data.len() as u64))?;
    // Finish explicitly so buffered-write failures are reported on the success path.
    let mut encoder = ZlibEncoder::new(pack, Compression::new(6));
    encoder.write_all(data).map_err(output_error)?;
    encoder.finish().map_err(output_error)?;
    Ok(())
}

pub(super) struct SelectedEntry {
    pub(super) bytes: Vec<u8>,
    pub(super) depth: usize,
    pub(super) base: Option<usize>,
    pub(super) data_start: usize,
}

pub(super) fn select_entry(
    objects: &[PackObject<'_>],
    position: usize,
    depths: &[usize],
    options: DeltaOptions,
    stats: &mut DeltaStats,
    check: &mut impl FnMut() -> Result<(), PackWriteError>,
) -> Result<Option<SelectedEntry>, PackWriteError> {
    let object = objects[position];
    let length = object.data.len();
    if length < 8
        || length > options.max_object_bytes
        || length > u32::MAX as usize
        || options.max_depth == 0
        || options.max_candidates == 0
        || options.max_work == 0
        || options.window == 0
    {
        return Ok(None);
    }
    let candidates = (position.saturating_sub(options.window)..position)
        .rev()
        .filter(|&i| {
            let base = objects[i];
            base.kind == object.kind
                && depths[i] < options.max_depth
                && base.data.len() <= options.max_object_bytes
                && base.data.len() <= u32::MAX as usize
                && base.data.len() >= length.div_ceil(2)
                && base.data.len().div_ceil(2) <= length
        })
        .take(options.max_candidates);
    let mut best: Option<SelectedEntry> = None;
    let mut ordinary_cost = 0;
    let mut remaining = options.max_work;
    for i in candidates {
        check()?;
        if best.is_none() {
            let bytes = compressed(entry_header(object.kind, length as u64), object.data)?;
            ordinary_cost = bytes.len();
            best = Some(SelectedEntry {
                bytes,
                depth: 0,
                base: None,
                data_start: 0,
            });
            // Even before zlib bytes, a REF_DELTA needs a header and a format-sized base ID.
            if ordinary_cost.saturating_sub(1 + object.id.format().digest_len())
                <= options.min_savings
            {
                break;
            }
        }
        stats.candidates += 1;
        let before = remaining;
        let program = instructions(objects[i].data, object.data, &mut remaining, check)?;
        stats.work = stats.work.saturating_add(before - remaining);
        let Some(program) = program else { break };
        check()?;
        let mut header = entry_header_code(7, program.len() as u64);
        header.extend_from_slice(objects[i].id.as_bytes());
        let data_start = header.len();
        let bytes = compressed(header, &program)?;
        let current = best.as_ref().unwrap();
        if bytes.len() < current.bytes.len()
            && ordinary_cost.saturating_sub(bytes.len()) >= options.min_savings
        {
            best = Some(SelectedEntry {
                bytes,
                depth: depths[i] + 1,
                base: Some(i),
                data_start,
            });
        }
    }
    Ok(best)
}

fn compressed(header: Vec<u8>, data: &[u8]) -> Result<Vec<u8>, PackWriteError> {
    let mut encoder = ZlibEncoder::new(header, Compression::new(6));
    encoder.write_all(data)?;
    Ok(encoder.finish()?)
}

pub(super) fn validate<'a>(
    format: crate::ObjectFormat,
    objects: &[PackObject<'a>],
    limits: PackWriteLimits,
    check: &mut impl FnMut() -> Result<(), PackWriteError>,
) -> Result<Vec<PackObject<'a>>, PackWriteError> {
    check()?;
    if objects.len() as u64 > u64::from(limits.max_objects) {
        return Err(PackWriteError::Limit("input occurrences"));
    }
    let mut total = 0u64;
    for object in objects {
        object.id.require_format(format)?;
        check()?;
        let length = object.data.len() as u64;
        if length > limits.max_object_bytes {
            return Err(PackWriteError::Limit("object bytes"));
        }
        total = total
            .checked_add(length)
            .ok_or(PackWriteError::Limit("input bytes"))?;
        if total > limits.max_input_bytes {
            return Err(PackWriteError::Limit("input bytes"));
        }
    }
    check()?;
    let mut sorted = objects.to_vec();
    sorted.sort_unstable_by_key(|object| object.id);
    for pair in sorted.windows(2) {
        check()?;
        if pair[0].id == pair[1].id
            && (pair[0].kind != pair[1].kind || pair[0].data != pair[1].data)
        {
            return Err(PackWriteError::ConflictingDuplicate(pair[0].id));
        }
    }
    sorted.dedup_by_key(|object| object.id);
    for object in &sorted {
        check()?;
        let actual = format.hash_object(object.kind, object.data);
        if actual != object.id {
            return Err(PackWriteError::Identity {
                expected: object.id,
                actual,
            });
        }
    }
    Ok(sorted)
}

pub(super) fn entry_header(kind: ObjectKind, size: u64) -> Vec<u8> {
    let code = match kind {
        ObjectKind::Commit => 1,
        ObjectKind::Tree => 2,
        ObjectKind::Blob => 3,
        ObjectKind::Tag => 4,
    };
    entry_header_code(code, size)
}

pub(super) fn entry_header_code(code: u8, mut size: u64) -> Vec<u8> {
    let mut byte = (code << 4) | (size as u8 & 15);
    size >>= 4;
    let mut bytes = Vec::with_capacity(10);
    while size != 0 {
        bytes.push(byte | 128);
        byte = size as u8 & 127;
        size >>= 7;
    }
    bytes.push(byte);
    bytes
}

pub(crate) struct Entry {
    pub id: ObjectId,
    pub offset: u64,
    pub crc: u32,
}

pub(crate) fn encode_index(
    entries: &[Entry],
    checksum: ObjectId,
) -> Result<Vec<u8>, PackWriteError> {
    let mut bytes = Vec::new();
    let mut out = Output::new(checksum.format(), &mut bytes, u64::MAX, "index bytes");
    write_index(entries, checksum, &mut out)?;
    out.finish()?;
    Ok(bytes)
}

pub(super) fn write_index(
    entries: &[Entry],
    checksum: ObjectId,
    out: &mut Output<'_, impl Write>,
) -> Result<(), PackWriteError> {
    out.put(b"\xfftOc\0\0\0\x02")?;
    let mut fanout = [0u32; 256];
    for entry in entries {
        fanout[entry.id.as_bytes()[0] as usize] += 1;
    }
    let mut total = 0u32;
    for bucket in fanout {
        total += bucket;
        out.put(&total.to_be_bytes())?;
    }
    for entry in entries {
        out.put(entry.id.as_bytes())?;
    }
    for entry in entries {
        out.put(&entry.crc.to_be_bytes())?;
    }
    let mut large = 0u32;
    for entry in entries {
        let offset = if entry.offset < 0x8000_0000 {
            entry.offset as u32
        } else {
            if large == 0x8000_0000 {
                return Err(PackWriteError::Limit("large offsets"));
            }
            let slot = large | 0x8000_0000;
            large += 1;
            slot
        };
        out.put(&offset.to_be_bytes())?;
    }
    for entry in entries {
        if entry.offset >= 0x8000_0000 {
            out.put(&entry.offset.to_be_bytes())?;
        }
    }
    out.put(checksum.as_bytes())
}

// Preserve our limit error through flate2's io::Write boundary without conflating sink errors.
#[derive(Debug, thiserror::Error)]
#[error("output limit: {0}")]
struct OutputLimit(&'static str);

pub(super) fn output_error(error: io::Error) -> PackWriteError {
    if let Some(limit) = error
        .get_ref()
        .and_then(|e| e.downcast_ref::<OutputLimit>())
    {
        PackWriteError::Limit(limit.0)
    } else {
        PackWriteError::Io(error)
    }
}

pub(super) struct Output<'a, W> {
    sink: &'a mut W,
    pub(super) bytes: u64,
    limit: u64,
    label: &'static str,
    hash: Hasher,
    pub(super) crc: crc32fast::Hasher,
}

impl<'a, W: Write> Output<'a, W> {
    pub(super) fn new(
        format: crate::ObjectFormat,
        sink: &'a mut W,
        limit: u64,
        label: &'static str,
    ) -> Self {
        Self {
            sink,
            bytes: 0,
            limit,
            label,
            hash: Hasher::new(format),
            crc: crc32fast::Hasher::new(),
        }
    }
    pub(super) fn put(&mut self, bytes: &[u8]) -> Result<(), PackWriteError> {
        self.write_all(bytes).map_err(output_error)
    }
    pub(super) fn finish(&mut self) -> Result<ObjectId, PackWriteError> {
        let checksum = self.hash.clone().finalize();
        self.put(checksum.as_bytes())?;
        self.flush()?;
        Ok(checksum)
    }
}

impl<W: Write> Write for Output<'_, W> {
    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
        let end = self.bytes.checked_add(bytes.len() as u64);
        if end.is_none_or(|end| end > self.limit) {
            return Err(io::Error::other(OutputLimit(self.label)));
        }
        let written = self.sink.write(bytes)?;
        self.hash.update(&bytes[..written]);
        self.crc.update(&bytes[..written]);
        self.bytes += written as u64;
        Ok(written)
    }
    fn flush(&mut self) -> io::Result<()> {
        self.sink.flush()
    }
}

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

    use super::*;

    fn blob(data: &[u8]) -> PackObject<'_> {
        PackObject {
            id: ObjectId::for_blob(crate::ObjectFormat::Sha1, data),
            kind: ObjectKind::Blob,
            data,
        }
    }

    #[test]
    fn order_and_exact_duplicates_do_not_change_artifacts() {
        let (a, b) = (blob(b"a"), blob(b"b"));
        let (mut pack, mut idx, mut other_pack, mut other_idx) = (vec![], vec![], vec![], vec![]);
        let result = write_pack(
            crate::ObjectFormat::Sha1,
            &[a, b, a],
            &mut pack,
            &mut idx,
            PackWriteLimits::default(),
        )
        .unwrap();
        write_pack(
            crate::ObjectFormat::Sha1,
            &[b, a],
            &mut other_pack,
            &mut other_idx,
            PackWriteLimits::default(),
        )
        .unwrap();
        assert_eq!(result.objects, 2);
        assert_eq!(pack, other_pack);
        assert_eq!(idx, other_idx);
    }

    #[rstest]
    #[case::wrong_id(PackObject { id: ObjectId::Sha1([0;20]), ..blob(b"x") })]
    #[case::wrong_kind(PackObject { kind: ObjectKind::Tree, ..blob(b"x") })]
    fn invalid_identity_leaves_outputs_untouched(#[case] input: PackObject<'_>) {
        let (mut pack, mut idx) = (vec![], vec![]);
        assert!(matches!(
            write_pack(
                crate::ObjectFormat::Sha1,
                &[input],
                &mut pack,
                &mut idx,
                PackWriteLimits::default()
            ),
            Err(PackWriteError::Identity { .. })
        ));
        assert!(pack.is_empty());
        assert!(idx.is_empty());
    }

    #[test]
    fn conflicting_duplicates_leave_outputs_untouched() {
        let a = blob(b"a");
        let (mut pack, mut idx) = (vec![], vec![]);
        assert!(matches!(
            write_pack(
                crate::ObjectFormat::Sha1,
                &[a, PackObject { data: b"b", ..a }],
                &mut pack,
                &mut idx,
                PackWriteLimits::default()
            ),
            Err(PackWriteError::ConflictingDuplicate(_))
        ));
        assert!(pack.is_empty());
        assert!(idx.is_empty());
    }

    #[rstest]
    #[case::count(PackWriteLimits { max_objects: 1, ..PackWriteLimits::default() })]
    #[case::individual(PackWriteLimits { max_object_bytes: 0, ..PackWriteLimits::default() })]
    #[case::total_duplicates(PackWriteLimits { max_input_bytes: 1, ..PackWriteLimits::default() })]
    fn input_bounds_precede_output(#[case] limits: PackWriteLimits) {
        let (mut pack, mut idx) = (vec![], vec![]);
        assert!(matches!(
            write_pack(
                crate::ObjectFormat::Sha1,
                &[blob(b"a"), blob(b"a")],
                &mut pack,
                &mut idx,
                limits
            ),
            Err(PackWriteError::Limit(_))
        ));
        assert!(pack.is_empty());
        assert!(idx.is_empty());
    }

    #[rstest]
    #[case::pack_header(0, 2000, "pack bytes")]
    #[case::compressed_entry(14, 2000, "pack bytes")]
    #[case::index_header(2000, 0, "index bytes")]
    #[case::index_trailer(2000, 1099, "index bytes")]
    fn output_bounds_never_overrun(
        #[case] pack_limit: u64,
        #[case] index_limit: u64,
        #[case] label: &str,
    ) {
        let limits = PackWriteLimits {
            max_pack_bytes: pack_limit,
            max_index_bytes: index_limit,
            ..PackWriteLimits::default()
        };
        let (mut pack, mut idx) = (vec![], vec![]);
        assert!(
            matches!(write_pack(crate::ObjectFormat::Sha1, &[blob(b"a")], &mut pack, &mut idx, limits), Err(PackWriteError::Limit(actual)) if actual == label)
        );
        assert!(pack.len() as u64 <= pack_limit);
        assert!(idx.len() as u64 <= index_limit);
    }

    #[test]
    fn exact_limits_succeed() {
        let (mut pack, mut idx) = (vec![], vec![]);
        let first = write_pack(
            crate::ObjectFormat::Sha1,
            &[blob(b"a")],
            &mut pack,
            &mut idx,
            PackWriteLimits::default(),
        )
        .unwrap();
        let limits = PackWriteLimits {
            max_objects: 1,
            max_object_bytes: 1,
            max_input_bytes: 1,
            max_pack_bytes: first.pack_bytes,
            max_index_bytes: first.index_bytes,
        };
        let result = write_pack(
            crate::ObjectFormat::Sha1,
            &[blob(b"a")],
            &mut vec![],
            &mut vec![],
            limits,
        )
        .unwrap();
        assert_eq!(result.checksum, first.checksum);
    }

    struct Sink {
        remaining: usize,
        fail_flush: bool,
        bytes: Vec<u8>,
    }
    impl Write for Sink {
        fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
            if self.remaining == 0 {
                return Err(io::Error::other("injected write failure"));
            }
            let n = bytes.len().min(self.remaining).min(3);
            self.bytes.extend_from_slice(&bytes[..n]);
            self.remaining -= n;
            Ok(n)
        }
        fn flush(&mut self) -> io::Result<()> {
            if self.fail_flush {
                Err(io::Error::other("injected flush failure"))
            } else {
                Ok(())
            }
        }
    }

    #[rstest]
    #[case::pack_write(15, false, usize::MAX, false)]
    #[case::pack_flush(usize::MAX, true, usize::MAX, false)]
    #[case::index_write(usize::MAX, false, 1040, false)]
    #[case::index_flush(usize::MAX, false, usize::MAX, true)]
    fn sink_failures_are_reported(
        #[case] pack_remaining: usize,
        #[case] pack_flush: bool,
        #[case] index_remaining: usize,
        #[case] index_flush: bool,
    ) {
        let mut pack = Sink {
            remaining: pack_remaining,
            fail_flush: pack_flush,
            bytes: vec![],
        };
        let mut index = Sink {
            remaining: index_remaining,
            fail_flush: index_flush,
            bytes: vec![],
        };
        assert!(matches!(
            write_pack(
                crate::ObjectFormat::Sha1,
                &[blob(b"a")],
                &mut pack,
                &mut index,
                PackWriteLimits::default()
            ),
            Err(PackWriteError::Io(_))
        ));
    }

    #[test]
    fn short_writes_preserve_checksums() {
        let mut pack = Sink {
            remaining: usize::MAX,
            fail_flush: false,
            bytes: vec![],
        };
        let (mut index, mut expected_pack, mut expected_index) = (vec![], vec![], vec![]);
        write_pack(
            crate::ObjectFormat::Sha1,
            &[blob(b"abc")],
            &mut pack,
            &mut index,
            PackWriteLimits::default(),
        )
        .unwrap();
        write_pack(
            crate::ObjectFormat::Sha1,
            &[blob(b"abc")],
            &mut expected_pack,
            &mut expected_index,
            PackWriteLimits::default(),
        )
        .unwrap();
        assert_eq!(pack.bytes, expected_pack);
        assert_eq!(index, expected_index);
    }

    #[rstest]
    #[case::empty(0, &[0x30])]
    #[case::fifteen(15, &[0x3f])]
    #[case::sixteen(16, &[0xb0, 1])]
    #[case::two_kib(2048, &[0xb0, 0x80, 1])]
    #[case::maximum(u64::MAX, &[0xbf,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,15])]
    fn original_size_header_vectors(#[case] size: u64, #[case] expected: &[u8]) {
        assert_eq!(entry_header(ObjectKind::Blob, size), expected);
    }

    #[test]
    #[cfg(target_pointer_width = "64")]
    fn synthetic_large_offsets_use_ordered_64_bit_table() {
        let entries = [
            Entry {
                id: ObjectId::Sha1([0; 20]),
                offset: 12,
                crc: 0x12345678,
            },
            Entry {
                id: ObjectId::Sha1([1; 20]),
                offset: 0x7fff_ffff,
                crc: 1,
            },
            Entry {
                id: ObjectId::Sha1([2; 20]),
                offset: 0x8000_0000,
                crc: 2,
            },
            Entry {
                id: ObjectId::Sha1([3; 20]),
                offset: 0x1_0000_0000,
                crc: 3,
            },
        ];
        let mut bytes = vec![];
        let mut output = Output::new(
            crate::ObjectFormat::Sha1,
            &mut bytes,
            u64::MAX,
            "index bytes",
        );
        write_index(&entries, ObjectId::Sha1([9; 20]), &mut output).unwrap();
        output.finish().unwrap();
        assert_eq!(
            &bytes[1128..1144],
            &[
                0, 0, 0, 12, 0x7f, 0xff, 0xff, 0xff, 0x80, 0, 0, 0, 0x80, 0, 0, 1
            ]
        );
        assert_eq!(
            &bytes[1144..1160],
            &[0, 0, 0, 0, 0x80, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0]
        );
        let parsed =
            crate::pack::index::Index::parse(crate::ObjectFormat::Sha1, &bytes, 0x1_0000_0001)
                .unwrap();
        assert_eq!(parsed.offset(&bytes, 2).unwrap(), 0x8000_0000);
        assert_eq!(parsed.offset(&bytes, 3).unwrap(), 0x1_0000_0000);
    }

    #[rstest]
    #[case::tree(ObjectKind::Tree)]
    #[case::commit(ObjectKind::Commit)]
    #[case::tag(ObjectKind::Tag)]
    fn payload_syntax_is_preserved_without_parsing(#[case] kind: ObjectKind) {
        let data = b"not a structured object\0\xff";
        let id = ObjectId::for_object(kind.as_str(), data);
        let (mut pack, mut index) = (vec![], vec![]);
        write_pack(
            crate::ObjectFormat::Sha1,
            &[PackObject { id, kind, data }],
            &mut pack,
            &mut index,
            PackWriteLimits::default(),
        )
        .unwrap();
        let reader = crate::pack::Pack::open(crate::ObjectFormat::Sha1, &index, pack).unwrap();
        let restored = reader
            .read(reader.find(id).unwrap(), crate::ReadLimits::default())
            .unwrap();
        assert_eq!(restored.kind(), kind);
        assert_eq!(restored.data(), data);
    }

    #[test]
    fn empty_set_accepts_zero_input_budgets() {
        let limits = PackWriteLimits {
            max_objects: 0,
            max_object_bytes: 0,
            max_input_bytes: 0,
            max_pack_bytes: 32,
            max_index_bytes: 1072,
        };
        let written = write_pack(
            crate::ObjectFormat::Sha1,
            &[],
            &mut vec![],
            &mut vec![],
            limits,
        )
        .unwrap();
        assert_eq!(written.objects, 0);
        assert_eq!(written.pack_bytes, 32);
        assert_eq!(written.index_bytes, 1072);
    }

    #[test]
    fn zero_progress_sink_returns_write_zero() {
        let mut empty = &mut [][..];
        let error = write_pack(
            crate::ObjectFormat::Sha1,
            &[],
            &mut empty,
            &mut vec![],
            PackWriteLimits::default(),
        )
        .unwrap_err();
        assert!(
            matches!(error, PackWriteError::Io(error) if error.kind() == io::ErrorKind::WriteZero)
        );
    }

    #[test]
    fn output_counter_overflow_fails_before_sink() {
        let mut bytes = vec![];
        let mut output = Output::new(
            crate::ObjectFormat::Sha1,
            &mut bytes,
            u64::MAX,
            "pack bytes",
        );
        output.bytes = u64::MAX;
        assert!(matches!(
            output.put(b"a"),
            Err(PackWriteError::Limit("pack bytes"))
        ));
        assert!(bytes.is_empty());
    }
}

#[cfg(test)]
mod compression_tests {
    use rstest::rstest;

    use super::*;

    fn payloads() -> Vec<Vec<u8>> {
        (0..12)
            .map(|variant| {
                let mut state = 123456789u64;
                let mut bytes: Vec<u8> = (0..16384)
                    .map(|_| {
                        state ^= state << 13;
                        state ^= state >> 7;
                        state ^= state << 17;
                        state as u8
                    })
                    .collect();
                bytes[variant * 100] ^= 255;
                bytes
            })
            .collect()
    }
    fn export(data: &[Vec<u8>], options: DeltaOptions) -> (PackWritten, Vec<u8>, Vec<u8>) {
        let inputs: Vec<_> = data
            .iter()
            .map(|data| PackObject {
                id: ObjectId::for_blob(crate::ObjectFormat::Sha1, data),
                kind: ObjectKind::Blob,
                data,
            })
            .collect();
        let (mut pack, mut index) = (vec![], vec![]);
        let written = write_pack_with_compression(
            crate::ObjectFormat::Sha1,
            &inputs,
            &mut pack,
            &mut index,
            PackWriteLimits::default(),
            PackCompression::Delta(options),
        )
        .unwrap();
        (written, pack, index)
    }

    #[rstest]
    #[case::window(DeltaOptions { window: 0, ..DeltaOptions::default() })]
    #[case::candidates(DeltaOptions { max_candidates: 0, ..DeltaOptions::default() })]
    #[case::depth(DeltaOptions { max_depth: 0, ..DeltaOptions::default() })]
    #[case::size(DeltaOptions { max_object_bytes: 0, ..DeltaOptions::default() })]
    #[case::work(DeltaOptions { max_work: 0, ..DeltaOptions::default() })]
    #[case::exhausted(DeltaOptions { max_work: 1, ..DeltaOptions::default() })]
    #[case::savings(DeltaOptions { min_savings: usize::MAX, ..DeltaOptions::default() })]
    fn ordinary_fallback_is_byte_identical(#[case] options: DeltaOptions) {
        let data = payloads();
        let (written, pack, index) = export(&data, options);
        let (_, ordinary, ordinary_index) = export(
            &data,
            DeltaOptions {
                window: 0,
                ..options
            },
        );
        assert_eq!(written.deltas.entries, 0);
        assert_eq!(pack, ordinary);
        assert_eq!(index, ordinary_index);
    }

    #[rstest]
    #[case::one(1, 1, 1)]
    #[case::two(3, 2, 2)]
    #[case::default(16, 4, 4)]
    fn bounded_deterministic_internal_dependencies(
        #[case] window: usize,
        #[case] candidates: usize,
        #[case] depth: usize,
    ) {
        let mut data = payloads();
        let options = DeltaOptions {
            window,
            max_candidates: candidates,
            max_depth: depth,
            ..DeltaOptions::default()
        };
        let (written, pack, index) = export(&data, options);
        data.reverse();
        data.push(data[0].clone());
        let (_, other, other_index) = export(&data, options);
        assert_eq!(pack, other);
        assert_eq!(index, other_index);
        assert!(written.deltas.entries > 0);
        assert!(written.deltas.max_depth <= depth);
        assert!(written.deltas.candidates <= 12 * candidates.min(window) as u64);
        assert!(written.deltas.work <= 12 * options.max_work);
        let reader = crate::pack::Pack::open(crate::ObjectFormat::Sha1, &index, pack).unwrap();
        verify_payloads(&reader, &data, written.deltas.max_depth);
    }
    fn verify_payloads(reader: &crate::pack::Pack, data: &[Vec<u8>], max_delta_depth: usize) {
        for expected in data {
            let restored = reader
                .read(
                    reader
                        .find(ObjectId::for_blob(crate::ObjectFormat::Sha1, expected))
                        .unwrap(),
                    crate::ReadLimits {
                        max_delta_depth,
                        ..crate::ReadLimits::default()
                    },
                )
                .unwrap();
            assert_eq!(restored.data(), expected);
        }
    }

    #[rstest]
    #[case::blob(ObjectKind::Blob)]
    #[case::tree(ObjectKind::Tree)]
    #[case::commit(ObjectKind::Commit)]
    #[case::tag(ObjectKind::Tag)]
    fn matching_is_byte_oriented_for_every_kind(#[case] kind: ObjectKind) {
        let data = payloads();
        let inputs: Vec<_> = data
            .iter()
            .map(|data| PackObject {
                id: ObjectId::for_object(kind.as_str(), data),
                kind,
                data,
            })
            .collect();
        let (mut pack, mut index) = (vec![], vec![]);
        let written = write_pack_with_compression(
            crate::ObjectFormat::Sha1,
            &inputs,
            &mut pack,
            &mut index,
            PackWriteLimits::default(),
            PackCompression::Delta(DeltaOptions::default()),
        )
        .unwrap();
        assert!(written.deltas.entries > 0);
        let reader = crate::pack::Pack::open(crate::ObjectFormat::Sha1, &index, pack).unwrap();
        let restored = reader
            .read(
                reader.find(inputs[0].id).unwrap(),
                crate::ReadLimits::default(),
            )
            .unwrap();
        assert_eq!(restored.kind(), kind);
        assert_eq!(restored.data(), data[0]);
    }

    #[test]
    fn different_kinds_are_never_candidates() {
        let data = payloads();
        let inputs = [
            PackObject {
                id: ObjectId::for_blob(crate::ObjectFormat::Sha1, &data[0]),
                kind: ObjectKind::Blob,
                data: &data[0],
            },
            PackObject {
                id: ObjectId::for_object("tree", &data[1]),
                kind: ObjectKind::Tree,
                data: &data[1],
            },
        ];
        let written = write_pack_with_compression(
            crate::ObjectFormat::Sha1,
            &inputs,
            &mut vec![],
            &mut vec![],
            PackWriteLimits::default(),
            PackCompression::Delta(DeltaOptions::default()),
        )
        .unwrap();
        assert_eq!(written.deltas.candidates, 0);
    }

    #[test]
    fn delta_output_bound_includes_base_id_and_trailer() {
        let data = payloads();
        let (written, _, _) = export(&data, DeltaOptions::default());
        let inputs: Vec<_> = data
            .iter()
            .map(|data| PackObject {
                id: ObjectId::for_blob(crate::ObjectFormat::Sha1, data),
                kind: ObjectKind::Blob,
                data,
            })
            .collect();
        let limits = PackWriteLimits {
            max_pack_bytes: written.pack_bytes - 1,
            ..PackWriteLimits::default()
        };
        let (mut pack, mut index) = (vec![], vec![]);
        let result = write_pack_with_compression(
            crate::ObjectFormat::Sha1,
            &inputs,
            &mut pack,
            &mut index,
            limits,
            PackCompression::Delta(DeltaOptions::default()),
        );
        assert!(matches!(result, Err(PackWriteError::Limit("pack bytes"))));
        assert!(pack.len() as u64 <= limits.max_pack_bytes);
        assert!(index.is_empty());
    }

    #[test]
    fn exhausted_later_candidate_retains_completed_delta() {
        let data = payloads();
        let options = DeltaOptions {
            max_candidates: 4,
            max_work: 19000,
            ..DeltaOptions::default()
        };
        let (written, pack, index) = export(&data, options);
        assert!(written.deltas.entries > 0);
        assert!(written.deltas.candidates > u64::from(written.deltas.entries));
        assert!(written.deltas.work <= 12 * options.max_work);
        let reader = crate::pack::Pack::open(crate::ObjectFormat::Sha1, &index, pack).unwrap();
        verify_payloads(&reader, &data, written.deltas.max_depth);
    }

    #[test]
    fn objects_above_search_size_remain_streaming() {
        let data = payloads();
        let (written, _, _) = export(
            &data,
            DeltaOptions {
                max_object_bytes: 16383,
                ..DeltaOptions::default()
            },
        );
        assert_eq!(written.deltas.entries, 0);
        assert_eq!(written.deltas.candidates, 0);
        assert_eq!(written.deltas.work, 0);
    }

    #[test]
    fn short_objects_cannot_recover_ref_delta_overhead() {
        let data = vec![b"abcdefgh".to_vec(), b"abcdefgi".to_vec()];
        let (written, _, _) = export(&data, DeltaOptions::default());
        assert_eq!(written.deltas.candidates, 0);
    }

    #[test]
    fn invalid_identity_precedes_delta_output() {
        let input = PackObject {
            id: ObjectId::Sha1([0; 20]),
            kind: ObjectKind::Blob,
            data: &[1; 100],
        };
        let (mut pack, mut index) = (vec![], vec![]);
        let result = write_pack_with_compression(
            crate::ObjectFormat::Sha1,
            &[input],
            &mut pack,
            &mut index,
            PackWriteLimits::default(),
            PackCompression::Delta(DeltaOptions::default()),
        );
        assert!(matches!(result, Err(PackWriteError::Identity { .. })));
        assert!(pack.is_empty());
        assert!(index.is_empty());
    }
}

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

    #[test]
    fn prevalidation_cancellation_leaves_both_outputs_untouched() {
        let objects = [
            PackObject {
                id: ObjectId::for_blob(crate::ObjectFormat::Sha1, b"first"),
                kind: ObjectKind::Blob,
                data: b"first",
            },
            PackObject {
                id: ObjectId::Sha1([255; 20]),
                kind: ObjectKind::Blob,
                data: b"invalid identity",
            },
        ];
        let mut checks = 0;
        let (mut pack, mut index) = (vec![], vec![]);
        let result = write_controlled(
            crate::ObjectFormat::Sha1,
            &objects,
            &mut pack,
            &mut index,
            PackWriteLimits::default(),
            PackCompression::Ordinary,
            &mut || {
                checks += 1;
                if checks == 7 {
                    Err(PackWriteError::Io(io::Error::other("cancelled")))
                } else {
                    Ok(())
                }
            },
        );
        assert!(
            matches!(result, Err(PackWriteError::Io(error)) if error.to_string() == "cancelled")
        );
        assert!(pack.is_empty());
        assert!(index.is_empty());
    }
}

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

    #[test]
    fn rejects_sha256_before_writing_pack_or_index() {
        let object = PackObject {
            id: ObjectId::Sha256([1; 32]),
            kind: ObjectKind::Blob,
            data: b"a",
        };
        let mut pack = vec![];
        let mut index = vec![];
        let result = write_pack(
            crate::ObjectFormat::Sha1,
            &[object],
            &mut pack,
            &mut index,
            PackWriteLimits::default(),
        );
        assert!(matches!(result, Err(PackWriteError::ObjectFormat(_))));
        assert!(pack.is_empty());
        assert!(index.is_empty());
    }
}

#[cfg(test)]
mod dual_format_tests {
    use rstest::rstest;

    use super::*;
    use crate::ObjectFormat;

    fn blob(format: ObjectFormat) -> PackObject<'static> {
        PackObject {
            id: ObjectId::for_blob(format, b"blob"),
            kind: ObjectKind::Blob,
            data: b"blob",
        }
    }

    #[rstest]
    #[case::sha1(ObjectFormat::Sha1, ObjectFormat::Sha256)]
    #[case::sha256(ObjectFormat::Sha256, ObjectFormat::Sha1)]
    fn rejects_mixed_inputs_before_either_sink(
        #[case] format: ObjectFormat,
        #[case] other: ObjectFormat,
    ) {
        let (mut pack, mut index) = (vec![], vec![]);
        let result = write_pack(
            format,
            &[blob(format), blob(other)],
            &mut pack,
            &mut index,
            PackWriteLimits::default(),
        );
        assert!(matches!(result, Err(PackWriteError::ObjectFormat(_))));
        assert!(pack.is_empty());
        assert!(index.is_empty());
    }

    #[rstest]
    #[case::sha1(ObjectFormat::Sha1)]
    #[case::sha256(ObjectFormat::Sha256)]
    fn empty_artifact_bounds_include_both_trailers(#[case] format: ObjectFormat) {
        let limits = PackWriteLimits {
            max_objects: 0,
            max_object_bytes: 0,
            max_input_bytes: 0,
            max_pack_bytes: (12 + format.digest_len()) as u64,
            max_index_bytes: (1032 + 2 * format.digest_len()) as u64,
        };
        let (mut pack, mut index) = (vec![], vec![]);
        let written = write_pack(format, &[], &mut pack, &mut index, limits).unwrap();
        assert_eq!(written.pack_bytes, limits.max_pack_bytes);
        assert_eq!(written.index_bytes, limits.max_index_bytes);
        assert_eq!(written.checksum.format(), format);
        assert!(crate::pack::Pack::open(format, &index, pack).is_ok());
        let short = PackWriteLimits {
            max_index_bytes: limits.max_index_bytes - 1,
            ..limits
        };
        let (mut pack, mut index) = (vec![], vec![]);
        assert!(matches!(
            write_pack(format, &[], &mut pack, &mut index, short),
            Err(PackWriteError::Limit("index bytes"))
        ));
        assert_eq!(pack.len() as u64, limits.max_pack_bytes);
        assert!(index.len() as u64 <= short.max_index_bytes);
    }

    #[rstest]
    #[case::sha1(ObjectFormat::Sha1)]
    #[case::sha256(ObjectFormat::Sha256)]
    fn cancellation_during_validation_has_no_output(#[case] format: ObjectFormat) {
        let (mut pack, mut index) = (vec![], vec![]);
        let mut checks = 0;
        let result = write_controlled(
            format,
            &[blob(format)],
            &mut pack,
            &mut index,
            PackWriteLimits::default(),
            PackCompression::Ordinary,
            &mut || {
                checks += 1;
                if checks == 2 {
                    Err(PackWriteError::Limit("injected cancellation"))
                } else {
                    Ok(())
                }
            },
        );
        assert!(matches!(
            result,
            Err(PackWriteError::Limit("injected cancellation"))
        ));
        assert!(pack.is_empty());
        assert!(index.is_empty());
    }

    #[test]
    fn observed_pack_entries_do_not_imply_index_success() {
        let mut pack = Vec::new();
        let mut index = FlushFailure(Vec::new());
        let mut events = Vec::new();
        let result = write_controlled_observed(
            ObjectFormat::Sha1,
            &[blob(ObjectFormat::Sha1)],
            (&mut pack, &mut index),
            PackWriteLimits::default(),
            PackCompression::Ordinary,
            &mut || Ok(()),
            &mut |done, total| events.push((done, total)),
        );
        assert!(matches!(result, Err(PackWriteError::Io(_))));
        assert_eq!(events, [(0, 1), (1, 1)]);
    }

    struct FlushFailure(Vec<u8>);
    impl Write for FlushFailure {
        fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
            self.0.extend_from_slice(bytes);
            Ok(bytes.len())
        }
        fn flush(&mut self) -> io::Result<()> {
            Err(io::Error::other("injected flush failure"))
        }
    }

    #[rstest]
    #[case::sha1(ObjectFormat::Sha1)]
    #[case::sha256(ObjectFormat::Sha256)]
    fn failed_pack_flush_leaves_index_untouched(#[case] format: ObjectFormat) {
        let mut pack = FlushFailure(vec![]);
        let mut index = vec![];
        assert!(matches!(
            write_pack(
                format,
                &[],
                &mut pack,
                &mut index,
                PackWriteLimits::default()
            ),
            Err(PackWriteError::Io(_))
        ));
        assert_eq!(pack.0.len(), 12 + format.digest_len());
        assert!(index.is_empty());
    }
}