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
// SPDX-License-Identifier: Apache-2.0
//! Pack builder for creating packfiles.
use std::collections::{HashMap, VecDeque};
use heddle_format::{compression::CompressionConfig, delta::DeltaEncoder};
use super::{
ObjectType, PackLogicalId, PackObjectId, PackObjectRecord, PackStats,
append_container_checksum, compress_pack_payload, encode_tagged_entry,
encode_tagged_entry_parts, pack_container_spec, pack_identity::logical_id_from_objects,
pack_index::PackIndex, write_container_header,
};
use crate::{object::ContentHash, store::Result};
const MIN_DELTA_SIZE: usize = 64;
/// Maximum depth for delta chains (matches Git's default).
const MAX_DELTA_CHAIN_DEPTH: usize = 50;
/// Default number of recent objects to try as delta bases (Git default: 10).
const DEFAULT_DELTA_WINDOW: usize = 10;
type GroupedPackMap = HashMap<ObjectType, Vec<PackObjectRecord>>;
/// Pack builder for creating packfiles.
pub struct PackBuilder {
objects: Vec<PackObjectRecord>,
compression: CompressionConfig,
delta_window: usize,
}
/// A recent object in the sliding window, with cached hash index for fast delta estimation.
struct WindowEntry {
hash: ContentHash,
data: Vec<u8>,
index: HashMap<[u8; 4], Vec<usize>>,
chain_depth: usize,
}
impl PackBuilder {
/// Create a new pack builder.
pub fn new(compression: CompressionConfig) -> Self {
Self {
objects: Vec::new(),
compression,
delta_window: DEFAULT_DELTA_WINDOW,
}
}
/// Create a pack builder tuned for repacking an existing object corpus.
///
/// `delta_window` controls how many recently sorted objects are considered
/// as delta bases. A zero-sized window disables delta-base selection.
pub fn for_repack(compression: CompressionConfig, delta_window: usize) -> Self {
Self {
objects: Vec::new(),
compression,
delta_window,
}
}
/// Add an object to the pack.
pub fn add(&mut self, hash: ContentHash, obj_type: ObjectType, data: Vec<u8>) {
self.add_id(PackObjectId::Hash(hash), obj_type, data);
}
pub fn add_id(&mut self, id: PackObjectId, obj_type: ObjectType, data: Vec<u8>) {
self.objects.push(PackObjectRecord {
id,
obj_type,
data,
delta_base: None,
path_hint: None,
});
}
/// Add an object with a path hint for better delta grouping.
///
/// Objects sharing the same path (e.g. successive versions of `src/main.rs`)
/// will be sorted together for delta encoding, producing much better
/// compression ratios than size-only ordering.
pub fn add_with_path(
&mut self,
hash: ContentHash,
obj_type: ObjectType,
data: Vec<u8>,
path: Option<String>,
) {
self.add_with_path_id(PackObjectId::Hash(hash), obj_type, data, path);
}
pub fn add_with_path_id(
&mut self,
id: PackObjectId,
obj_type: ObjectType,
data: Vec<u8>,
path: Option<String>,
) {
self.objects.push(PackObjectRecord {
id,
obj_type,
data,
delta_base: None,
path_hint: path,
});
}
/// Compute the logical identity of the objects currently in this builder.
///
/// Path hints, compression, output order, and later delta-base selection do
/// not participate in this root-spool-scoped identity.
pub fn logical_id(&self) -> PackLogicalId {
logical_id_from_objects(
self.objects
.iter()
.map(|record| (record.id, record.obj_type, record.data.as_slice())),
)
}
/// Build the packfile and index.
///
/// Returns the pack data, index data, and statistics.
pub fn build(self) -> Result<(Vec<u8>, Vec<u8>, PackStats)> {
let mut pack_data = Vec::new();
let mut index = PackIndex::new();
write_container_header(
&mut pack_data,
pack_container_spec(),
self.objects.len() as u64,
);
let mut total_uncompressed = 0u64;
let mut total_compressed = 0u64;
let mut delta_count = 0u64;
let object_count = self.objects.len() as u64;
let grouped = Self::group_by_type(self.objects);
for (obj_type, mut objects) in grouped {
if objects.len() < 2
|| matches!(
obj_type,
ObjectType::State | ObjectType::StateAttachment | ObjectType::AnnotatedTag
)
|| self.compression.max_delta_size == 0
|| objects
.iter()
.all(|record| record.data.len() < MIN_DELTA_SIZE)
{
// Single objects, states, all-small groups, or transfer-tuned packs
// with delta disabled: write entries directly without constructing
// sliding-window indexes that cannot produce a delta.
for record in objects {
let offset = pack_data.len() as u64;
index.add(record.id, offset);
total_uncompressed += record.data.len() as u64;
let compressed = compress_pack_payload(&record.data, &self.compression)?;
total_compressed += compressed.len() as u64;
Self::write_entry(&mut pack_data, &record, obj_type, &compressed)?;
}
} else {
Self::sort_for_delta_window(&mut objects);
Self::encode_with_sliding_window(
&mut pack_data,
&mut index,
&mut total_uncompressed,
&mut total_compressed,
&mut delta_count,
obj_type,
objects,
&self.compression,
self.delta_window,
)?;
}
}
index.sort();
append_container_checksum(&mut pack_data);
let stats = PackStats {
object_count,
total_uncompressed,
total_compressed,
delta_count,
compression_ratio: total_compressed as f64 / total_uncompressed as f64,
};
Ok((pack_data, index.to_bytes(), stats))
}
/// Sort objects for optimal delta window traversal.
///
/// Sorts by: file extension → basename → size descending.
/// This ensures files with the same extension are adjacent (like Git sorting
/// `.rs` files together), within that group same-named files are adjacent,
/// and within that the largest comes first (best delta base candidate).
fn sort_for_delta_window(objects: &mut [PackObjectRecord]) {
objects.sort_by(|a, b| {
let key_a = Self::sort_key(&a.path_hint);
let key_b = Self::sort_key(&b.path_hint);
key_a.cmp(&key_b).then(b.data.len().cmp(&a.data.len()))
});
}
/// Extract a sort key from a path: (extension, basename_without_extension).
/// Objects without paths sort last.
fn sort_key(path: &Option<String>) -> (String, String) {
match path {
Some(p) => {
let filename = p.rsplit('/').next().unwrap_or(p);
if let Some(dot_pos) = filename.rfind('.') {
let ext = filename[dot_pos + 1..].to_string();
let stem = filename[..dot_pos].to_string();
(ext, stem)
} else {
(String::new(), filename.to_string())
}
}
None => ("\u{FFFF}".to_string(), String::new()),
}
}
/// Encode objects using a sliding window for delta base selection.
///
/// For each object, tries delta encoding against the W most recent objects
/// in the window, picking the base that produces the smallest delta. This
/// is the same approach Git uses with `--window=10`.
#[allow(clippy::too_many_arguments)]
fn encode_with_sliding_window(
pack_data: &mut Vec<u8>,
index: &mut PackIndex,
total_uncompressed: &mut u64,
total_compressed: &mut u64,
delta_count: &mut u64,
obj_type: ObjectType,
objects: Vec<PackObjectRecord>,
compression: &CompressionConfig,
delta_window: usize,
) -> Result<()> {
let mut window: VecDeque<WindowEntry> =
VecDeque::with_capacity(delta_window.min(objects.len()));
for record in objects {
let hash = match record.id {
PackObjectId::Hash(hash) => hash,
PackObjectId::StateId(_) | PackObjectId::AnnotatedTag(_) => {
let offset = pack_data.len() as u64;
index.add(record.id, offset);
*total_uncompressed += record.data.len() as u64;
let compressed = compress_pack_payload(&record.data, compression)?;
*total_compressed += compressed.len() as u64;
Self::write_entry(pack_data, &record, obj_type, &compressed)?;
continue;
}
};
let data = record.data;
let offset = pack_data.len() as u64;
index.add(PackObjectId::Hash(hash), offset);
*total_uncompressed += data.len() as u64;
// Try delta against each window entry, pick the best
let mut best_base_idx: Option<usize> = None;
let mut best_delta_estimate = usize::MAX;
if data.len() >= MIN_DELTA_SIZE {
for (i, entry) in window.iter().enumerate() {
// Skip if this base is already at max chain depth
if entry.chain_depth >= MAX_DELTA_CHAIN_DEPTH {
continue;
}
// Skip if base is too small
if entry.data.len() < MIN_DELTA_SIZE {
continue;
}
let estimate = DeltaEncoder::estimate_delta_size_with_index(
&entry.index,
&entry.data,
&data,
);
if estimate < best_delta_estimate {
best_delta_estimate = estimate;
best_base_idx = Some(i);
}
}
}
// Decide: delta or raw?
let (final_data, entry_type, base_hash, chain_depth) =
if let Some(base_idx) = best_base_idx {
let base_entry = &window[base_idx];
let delta =
DeltaEncoder::encode_with_index(&base_entry.index, &base_entry.data, &data);
let delta_compressed = compress_pack_payload(&delta, compression)?;
if delta_compressed.len() < data.len() {
*delta_count += 1;
let bh = base_entry.hash;
let depth = base_entry.chain_depth + 1;
(delta_compressed, ObjectType::Delta, Some(bh), depth)
} else {
let compressed = compress_pack_payload(&data, compression)?;
(compressed, obj_type, None, 0)
}
} else {
let compressed = compress_pack_payload(&data, compression)?;
(compressed, obj_type, None, 0)
};
*total_compressed += final_data.len() as u64;
Self::write_entry_parts(
pack_data,
PackObjectId::Hash(hash),
entry_type,
data.len(),
base_hash.map(PackObjectId::Hash),
&final_data,
)?;
if delta_window > 0 {
// Build the index once, then reuse it for all future comparisons.
let entry_index = DeltaEncoder::build_index(&data);
if window.len() >= delta_window {
window.pop_front();
}
window.push_back(WindowEntry {
hash,
data,
index: entry_index,
chain_depth,
});
}
}
Ok(())
}
fn group_by_type(objects: Vec<PackObjectRecord>) -> GroupedPackMap {
let mut groups: GroupedPackMap = HashMap::new();
for record in objects {
groups.entry(record.obj_type).or_default().push(record);
}
groups
}
/// Write a pack entry with varint-encoded sizes.
///
/// Format per entry:
/// ```text
/// [tagged_id][type+uncompressed_size: varint][compressed_size: varint]
/// [tagged_base_id (delta only)][compressed_data]
/// ```
///
/// The compressed data is raw zstd — no wrapper header — since the
/// entry already records both sizes.
fn write_entry(
pack: &mut Vec<u8>,
record: &PackObjectRecord,
obj_type: ObjectType,
compressed: &[u8],
) -> Result<()> {
encode_tagged_entry(pack, record, obj_type, compressed)
}
fn write_entry_parts(
pack: &mut Vec<u8>,
id: PackObjectId,
obj_type: ObjectType,
uncompressed_size: usize,
delta_base: Option<PackObjectId>,
compressed: &[u8],
) -> Result<()> {
encode_tagged_entry_parts(
pack,
id,
obj_type,
uncompressed_size,
delta_base,
compressed,
)
}
}