git_internal/internal/pack/utils.rs
1//! Shared pack-parsing helpers for reading object headers, varints, offsets, and zlib-compressed
2//! payloads as defined by Git's pack format.
3
4use std::{
5 fs,
6 io::{self, Read},
7 path::Path,
8};
9
10use crate::{
11 hash::{HashError, HashKind, ObjectHash},
12 internal::object::types::ObjectType,
13 utils::HashAlgorithm,
14};
15
16/// Checks if the reader has reached EOF (end of file).
17///
18/// It attempts to read a single byte from the reader into a buffer.
19/// If `Ok(0)` is returned, it means no byte was read, indicating
20/// that the end of the stream has been reached and there is no more
21/// data left to read.
22///
23/// Any other return value means that data was successfully read, so
24/// the reader has not reached the end yet.
25///
26/// # Arguments
27///
28/// * `reader` - The reader to check for EOF state
29/// It must implement the `std::io::Read` trait
30///
31/// # Returns
32///
33/// true if the reader reached EOF, false otherwise
34pub fn is_eof(reader: &mut dyn Read) -> bool {
35 let mut buf = [0; 1];
36 matches!(reader.read(&mut buf), Ok(0))
37}
38
39/// Reads a byte from the given stream and checks if there are more bytes to continue reading.
40///
41/// The return value includes two parts: an unsigned integer formed by the first 7 bits of the byte,
42/// and a boolean value indicating whether more bytes need to be read.
43///
44/// # Parameters
45/// * `stream`: The stream from which the byte is read.
46///
47/// # Returns
48/// Returns an `io::Result` containing a tuple. The first element is the value of the first 7 bits,
49/// and the second element is a boolean indicating whether more bytes need to be read.
50///
51pub fn read_byte_and_check_continuation<R: Read>(stream: &mut R) -> io::Result<(u8, bool)> {
52 // Create a buffer for a single byte
53 let mut bytes = [0; 1];
54
55 // Read exactly one byte from the stream into the buffer
56 stream.read_exact(&mut bytes)?;
57
58 // Extract the byte from the buffer
59 let byte = bytes[0];
60
61 // Extract the first 7 bits of the byte
62 let value = byte & 0b0111_1111;
63
64 // Check if the most significant bit (8th bit) is set, indicating more bytes to follow
65 let msb = byte >= 128;
66
67 // Return the extracted value and the continuation flag
68 Ok((value, msb))
69}
70
71/// Reads bytes from the stream and parses the first byte for type and size.
72/// Subsequent bytes are read as size bytes and are processed as variable-length
73/// integer in little-endian order. The function returns the type and the computed size.
74///
75/// # Parameters
76/// * `stream`: The stream from which the bytes are read.
77/// * `offset`: The offset of the stream.
78///
79/// # Returns
80/// Returns an `io::Result` containing a tuple of the type and the computed size.
81///
82pub fn read_type_and_varint_size<R: Read>(
83 stream: &mut R,
84 offset: &mut usize,
85) -> io::Result<(u8, usize)> {
86 let (first_byte, continuation) = read_byte_and_check_continuation(stream)?;
87
88 // Increment the offset by one byte
89 *offset += 1;
90
91 // Extract the type (bits 2, 3, 4 of the first byte)
92 let type_bits = (first_byte & 0b0111_0000) >> 4;
93
94 // Initialize size with the last 4 bits of the first byte
95 let mut size: u64 = (first_byte & 0b0000_1111) as u64;
96 let mut shift = 4; // Next byte will shift by 4 bits
97
98 let mut more_bytes = continuation;
99 while more_bytes {
100 let (next_byte, continuation) = read_byte_and_check_continuation(stream)?;
101 // Increment the offset by one byte
102 *offset += 1;
103
104 size |= (next_byte as u64) << shift;
105 shift += 7; // Each subsequent byte contributes 7 more bits
106 more_bytes = continuation;
107 }
108
109 Ok((type_bits, size as usize))
110}
111
112/// Reads a variable-length integer (VarInt) encoded in little-endian format from a source implementing the Read trait.
113///
114/// The VarInt encoding uses the most significant bit (MSB) of each byte as a continuation bit.
115/// The continuation bit being 1 indicates that there are following bytes.
116/// The actual integer value is encoded in the remaining 7 bits of each byte.
117///
118/// # Parameters
119/// * `reader`: A source implementing the Read trait (e.g., file, network stream).
120///
121/// # Returns
122/// Returns a `Result` containing either:
123/// * A tuple of the decoded `u64` value and the number of bytes read (`offset`).
124/// * An `io::Error` in case of any reading error or if the VarInt is too long.
125///
126pub fn read_varint_le<R: Read>(reader: &mut R) -> io::Result<(u64, usize)> {
127 // The decoded value
128 let mut value: u64 = 0;
129 // Bit shift for the next byte
130 let mut shift = 0;
131 // Number of bytes read
132 let mut offset = 0;
133
134 loop {
135 // A buffer to read a single byte
136 let mut buf = [0; 1];
137 // Read one byte from the reader
138 reader.read_exact(&mut buf)?;
139
140 // The byte just read
141 let byte = buf[0];
142 if shift > 63 {
143 // VarInt too long for u64
144 return Err(io::Error::new(
145 io::ErrorKind::InvalidData,
146 "VarInt too long",
147 ));
148 }
149
150 // Take the lower 7 bits of the byte
151 let byte_value = (byte & 0x7F) as u64;
152 // Add the byte value to the result, considering the shift
153 value |= byte_value << shift;
154
155 // Increment the byte count
156 offset += 1;
157 // Check if the MSB is 0 (last byte)
158 if byte & 0x80 == 0 {
159 break;
160 }
161
162 // Increment the shift for the next byte
163 shift += 7;
164 }
165
166 Ok((value, offset))
167}
168
169/// The offset for an OffsetDelta object(big-endian order)
170/// # Arguments
171///
172/// * `stream`: Input Data Stream to read
173/// # Returns
174/// * (`delta_offset`(unsigned), `consume`)
175pub fn read_offset_encoding<R: Read>(stream: &mut R) -> io::Result<(u64, usize)> {
176 // Like the object length, the offset for an OffsetDelta object
177 // is stored in a variable number of bytes,
178 // with the most significant bit of each byte indicating whether more bytes follow.
179 // However, the object length encoding allows redundant values,
180 // e.g. the 7-bit value [n] is the same as the 14- or 21-bit values [n, 0] or [n, 0, 0].
181 // Instead, the offset encoding adds 1 to the value of each byte except the least significant one.
182 // And just for kicks, the bytes are ordered from *most* to *least* significant.
183 let mut value = 0;
184 let mut offset = 0;
185 loop {
186 let (byte_value, more_bytes) = read_byte_and_check_continuation(stream)?;
187 offset += 1;
188 value = (value << 7) | byte_value as u64;
189 if !more_bytes {
190 return Ok((value, offset));
191 }
192
193 value += 1; //important!: for n >= 2 adding 2^7 + 2^14 + ... + 2^(7*(n-1)) to the result
194 }
195}
196
197/// Read the next N bytes from the reader
198///
199#[inline]
200pub fn read_bytes<R: Read, const N: usize>(stream: &mut R) -> io::Result<[u8; N]> {
201 let mut bytes = [0; N];
202 stream.read_exact(&mut bytes)?;
203
204 Ok(bytes)
205}
206
207/// Reads a partial integer from a stream. (little-endian order)
208///
209/// # Arguments
210///
211/// * `stream` - A mutable reference to a readable stream.
212/// * `bytes` - The number of bytes to read from the stream.
213/// * `present_bytes` - A mutable reference to a byte indicating which bits are present in the integer value.
214///
215/// # Returns
216///
217/// This function returns a result of type `io::Result<usize>`. If the operation is successful, the integer value
218/// read from the stream is returned as `Ok(value)`. Otherwise, an `Err` variant is returned, wrapping an `io::Error`
219/// that describes the specific error that occurred.
220pub fn read_partial_int<R: Read>(
221 stream: &mut R,
222 bytes: u8,
223 present_bytes: &mut u8,
224) -> io::Result<usize> {
225 let mut value: usize = 0;
226
227 // Iterate over the byte indices
228 for byte_index in 0..bytes {
229 // Check if the current bit is present
230 if *present_bytes & 1 != 0 {
231 // Read a byte from the stream
232 let [byte] = read_bytes(stream)?;
233
234 // Add the byte value to the integer value
235 value |= (byte as usize) << (byte_index * 8);
236 }
237
238 // Shift the present bytes to the right
239 *present_bytes >>= 1;
240 }
241
242 Ok(value)
243}
244
245/// Reads the base size and result size of a delta object from the given stream.
246///
247/// **Note**: The stream MUST be positioned at the start of the delta object.
248///
249/// The base size and result size are encoded as variable-length integers in little-endian order.
250///
251/// The base size is the size of the base object, and the result size is the size of the result object.
252///
253/// # Parameters
254/// * `stream`: The stream from which the sizes are read.
255///
256/// # Returns
257/// Returns a tuple containing the base size and result size.
258///
259pub fn read_delta_object_size<R: Read>(stream: &mut R) -> io::Result<(usize, usize)> {
260 let base_size = read_varint_le(stream)?.0 as usize;
261 let result_size = read_varint_le(stream)?.0 as usize;
262 Ok((base_size, result_size))
263}
264
265fn decimal_usize_bytes(mut value: usize, buf: &mut [u8; 20]) -> &[u8] {
266 if value == 0 {
267 return b"0";
268 }
269
270 let mut cursor = buf.len();
271 while value > 0 {
272 cursor -= 1;
273 buf[cursor] = b'0' + (value % 10) as u8;
274 value /= 10;
275 }
276 &buf[cursor..]
277}
278
279/// Stream `"<type> <size>\0<content>"` through `hasher` without allocating and
280/// finalize it into an [`ObjectHash`] of the hasher's own kind.
281fn hash_loose_object(mut hasher: HashAlgorithm, type_bytes: &[u8], data: &[u8]) -> ObjectHash {
282 let mut len_buf = [0; 20];
283 let len_bytes = decimal_usize_bytes(data.len(), &mut len_buf);
284 // Header: "<type> <size>\0"
285 hasher.update(type_bytes);
286 hasher.update(b" ");
287 hasher.update(len_bytes);
288 hasher.update(b"\0");
289 // Decompressed data(raw content)
290 hasher.update(data);
291 hasher.finalize_object_hash()
292}
293
294/// Calculate the object ID of the given object with an explicit repository `kind`.
295/// <br> "`<type> <size>\0<content>`"
296/// <br> data: The decompressed content of the object
297///
298/// Does not consult the thread-local [`HashKind`]. Delta types have no
299/// loose-object header and fail closed with [`HashError::UnsupportedObjectType`].
300pub fn calculate_object_hash_for_kind(
301 kind: HashKind,
302 obj_type: ObjectType,
303 data: &[u8],
304) -> Result<ObjectHash, HashError> {
305 let type_bytes = obj_type
306 .to_bytes()
307 .ok_or(HashError::UnsupportedObjectType {
308 operation: "calculate_object_hash_for_kind",
309 kind,
310 object_type: obj_type,
311 expected: kind.size(),
312 actual: 0,
313 payload_len: data.len(),
314 })?;
315 Ok(hash_loose_object(
316 HashAlgorithm::new_for_kind(kind),
317 type_bytes,
318 data,
319 ))
320}
321
322/// Calculate the object ID of the given object with the thread-local [`HashKind`]
323/// (SHA-1 or SHA-256).
324/// <br> "`<type> <size>\0<content>`"
325/// <br> data: The decompressed content of the object
326///
327/// Legacy entry point using the thread-local [`HashKind`] (digest dispatch now
328/// goes through [`HashAlgorithm`]); prefer [`calculate_object_hash_for_kind`].
329pub fn calculate_object_hash(obj_type: ObjectType, data: &[u8]) -> ObjectHash {
330 let type_bytes = obj_type
331 .to_bytes()
332 .expect("calculate_object_hash called with a delta type that has no loose-object header");
333 hash_loose_object(HashAlgorithm::new(), type_bytes, data)
334}
335/// Create an empty directory or clear the existing directory.
336pub fn create_empty_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
337 let dir = path.as_ref();
338 // 删除整个文件夹
339 if dir.exists() {
340 fs::remove_dir_all(dir)?;
341 }
342 // 重新创建文件夹
343 fs::create_dir_all(dir)?;
344 Ok(())
345}
346
347/// Count the number of files in a directory and its subdirectories.
348pub fn count_dir_files(path: &Path) -> io::Result<usize> {
349 let mut count = 0;
350 for entry in fs::read_dir(path)? {
351 let entry = entry?;
352 let path = entry.path();
353 if path.is_dir() {
354 count += count_dir_files(&path)?;
355 } else {
356 count += 1;
357 }
358 }
359 Ok(count)
360}
361
362/// Count the time taken to execute a block of code.
363#[macro_export]
364macro_rules! time_it {
365 ($msg:expr, $block:block) => {{
366 let start = std::time::Instant::now();
367 let result = $block;
368 let elapsed = start.elapsed();
369 // println!("{}: {:?}", $msg, elapsed);
370 tracing::info!("{}: {:?}", $msg, elapsed);
371 result
372 }};
373}
374
375#[cfg(test)]
376mod tests {
377 use std::{
378 io,
379 io::{Cursor, Read},
380 };
381
382 use crate::{
383 hash::{HashKind, set_hash_kind_for_test},
384 internal::{object::types::ObjectType, pack::utils::*},
385 };
386
387 #[test]
388 fn test_calc_obj_hash() {
389 let _guard = set_hash_kind_for_test(HashKind::Sha1);
390 let hash = calculate_object_hash(ObjectType::Blob, b"a".as_ref());
391 assert_eq!(hash.to_string(), "2e65efe2a145dda7ee51d1741299f848e5bf752e");
392 }
393 #[test]
394 fn test_calc_obj_hash_sha256() {
395 let _guard = set_hash_kind_for_test(HashKind::Sha256);
396 let hash = calculate_object_hash(ObjectType::Blob, b"a".as_ref());
397 assert_eq!(
398 hash.to_string(),
399 "eb337bcee2061c5313c9a1392116b6c76039e9e30d71467ae359b36277e17dc7"
400 );
401 }
402
403 #[test]
404 fn test_calc_empty_obj_hash() {
405 let _guard = set_hash_kind_for_test(HashKind::Sha1);
406 let hash = calculate_object_hash(ObjectType::Blob, b"".as_ref());
407 assert_eq!(hash.to_string(), "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391");
408 }
409
410 #[test]
411 fn eof() {
412 let mut reader = Cursor::new(&b""[..]);
413 assert!(is_eof(&mut reader));
414 }
415
416 #[test]
417 fn not_eof() {
418 let mut reader = Cursor::new(&b"abc"[..]);
419 assert!(!is_eof(&mut reader));
420 }
421
422 #[test]
423 fn eof_midway() {
424 let mut reader = Cursor::new(&b"abc"[..]);
425 reader.read_exact(&mut [0; 2]).unwrap();
426 assert!(!is_eof(&mut reader));
427 }
428
429 #[test]
430 fn reader_error() {
431 struct BrokenReader;
432 impl Read for BrokenReader {
433 fn read(&mut self, _: &mut [u8]) -> io::Result<usize> {
434 Err(io::Error::other("error"))
435 }
436 }
437
438 let mut reader = BrokenReader;
439 assert!(!is_eof(&mut reader));
440 }
441
442 /// Test case for a byte without a continuation bit (most significant bit is 0)
443 #[test]
444 fn test_read_byte_and_check_continuation_no_continuation() {
445 let data = [0b0101_0101]; // 85 in binary, highest bit is 0
446 let mut cursor = Cursor::new(data);
447 let (value, more_bytes) = read_byte_and_check_continuation(&mut cursor).unwrap();
448
449 assert_eq!(value, 85); // Expected value is 85
450 assert!(!more_bytes); // No more bytes are expected
451 }
452
453 /// Test case for a byte with a continuation bit (most significant bit is 1)
454 #[test]
455 fn test_read_byte_and_check_continuation_with_continuation() {
456 let data = [0b1010_1010]; // 170 in binary, highest bit is 1
457 let mut cursor = Cursor::new(data);
458 let (value, more_bytes) = read_byte_and_check_continuation(&mut cursor).unwrap();
459
460 assert_eq!(value, 42); // Expected value is 42 (170 - 128)
461 assert!(more_bytes); // More bytes are expected
462 }
463
464 /// Test cases for edge values, like the minimum and maximum byte values
465 #[test]
466 fn test_read_byte_and_check_continuation_edge_cases() {
467 // Test the minimum value (0)
468 let data = [0b0000_0000];
469 let mut cursor = Cursor::new(data);
470 let (value, more_bytes) = read_byte_and_check_continuation(&mut cursor).unwrap();
471
472 assert_eq!(value, 0); // Expected value is 0
473 assert!(!more_bytes); // No more bytes are expected
474
475 // Test the maximum value (255)
476 let data = [0b1111_1111];
477 let mut cursor = Cursor::new(data);
478 let (value, more_bytes) = read_byte_and_check_continuation(&mut cursor).unwrap();
479
480 assert_eq!(value, 127); // Expected value is 127 (255 - 128)
481 assert!(more_bytes); // More bytes are expected
482 }
483
484 /// Test with a single byte where msb is 0 (no continuation)
485 #[test]
486 fn test_single_byte_no_continuation() {
487 let data = [0b0101_0101]; // Type: 5 (101), Size: 5 (0101)
488 let mut offset: usize = 0;
489 let mut cursor = Cursor::new(data);
490 let (type_bits, size) = read_type_and_varint_size(&mut cursor, &mut offset).unwrap();
491
492 assert_eq!(offset, 1); // Offset is 1
493 assert_eq!(type_bits, 5); // Expected type is 2
494 assert_eq!(size, 5); // Expected size is 5
495 }
496
497 /// Test with multiple bytes, where continuation occurs
498 #[test]
499 fn test_multiple_bytes_with_continuation() {
500 // Type: 5 (101), Sizes: 5 (0101), 3 (0000011) in little-endian order
501 let data = [0b1101_0101, 0b0000_0011]; // Second byte's msb is 0
502 let mut offset: usize = 0;
503 let mut cursor = Cursor::new(data);
504 let (type_bits, size) = read_type_and_varint_size(&mut cursor, &mut offset).unwrap();
505
506 assert_eq!(offset, 2); // Offset is 2
507 assert_eq!(type_bits, 5); // Expected type is 5
508 // Expected size 000000110101
509 // 110101 = 1 * 2^5 + 1 * 2^4 + 0 * 2^3 + 1 * 2^2 + 0 * 2^1 + 1 * 2^0= 53
510 assert_eq!(size, 53);
511 }
512
513 /// Test with edge case where size is spread across multiple bytes
514 #[test]
515 fn test_edge_case_size_spread_across_bytes() {
516 // Type: 1 (001), Sizes: 15 (1111) in little-endian order
517 let data = [0b0001_1111, 0b0000_0010]; // Second byte's msb is 1 (continuation)
518 let mut offset: usize = 0;
519 let mut cursor = Cursor::new(data);
520 let (type_bits, size) = read_type_and_varint_size(&mut cursor, &mut offset).unwrap();
521
522 assert_eq!(offset, 1); // Offset is 1
523 assert_eq!(type_bits, 1); // Expected type is 1
524 // Expected size is 15
525 assert_eq!(size, 15);
526 }
527
528 /// Test reading VarInt encoded in little-endian format from a stream.
529 #[test]
530 fn test_read_varint_le_single_byte() {
531 // Single byte: 0x05 (binary: 0000 0101)
532 // Represents the value 5 with no continuation bit set.
533 let data = vec![0x05];
534 let mut cursor = Cursor::new(data);
535 let (value, offset) = read_varint_le(&mut cursor).unwrap();
536
537 assert_eq!(value, 5);
538 assert_eq!(offset, 1);
539 }
540
541 /// Test reading VarInt encoded in little-endian format with multiple bytes from a stream.
542 #[test]
543 fn test_read_varint_le_multiple_bytes() {
544 // Two bytes: 0x85, 0x01 (binary: 1000 0101, 0000 0001)
545 // Represents the value 133. First byte has the continuation bit set.
546 let data = vec![0x85, 0x01];
547 let mut cursor = Cursor::new(data);
548 let (value, offset) = read_varint_le(&mut cursor).unwrap();
549
550 assert_eq!(value, 133);
551 assert_eq!(offset, 2);
552 }
553
554 /// Test reading VarInt encoded in little-endian format with multiple bytes from a stream.
555 #[test]
556 fn test_read_varint_le_large_number() {
557 // Five bytes: 0xFF, 0xFF, 0xFF, 0xFF, 0xF (binary: 1111 1111, 1111 1111, 1111 1111, 1111 1111, 0000 1111)
558 // Represents the value 134,217,727. All continuation bits are set except in the last byte.
559 let data = vec![0xFF, 0xFF, 0xFF, 0xFF, 0xF];
560 let mut cursor = Cursor::new(data);
561 let (value, offset) = read_varint_le(&mut cursor).unwrap();
562
563 assert_eq!(value, 0xFFFFFFFF);
564 assert_eq!(offset, 5);
565 }
566
567 /// Test reading VarInt encoded in little-endian format with zero value.
568 #[test]
569 fn test_read_varint_le_zero() {
570 // Single byte: 0x00 (binary: 0000 0000)
571 // Represents the value 0 with no continuation bit set.
572 let data = vec![0x00];
573 let mut cursor = Cursor::new(data);
574 let (value, offset) = read_varint_le(&mut cursor).unwrap();
575
576 assert_eq!(value, 0);
577 assert_eq!(offset, 1);
578 }
579
580 /// Test reading VarInt encoded in little-endian format that is too long.
581 #[test]
582 fn test_read_varint_le_too_long() {
583 let data = vec![
584 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01,
585 ];
586 let mut cursor = Cursor::new(data);
587 let result = read_varint_le(&mut cursor);
588
589 assert!(result.is_err());
590 }
591
592 /// Test reading offset encoding for an OffsetDelta object.
593 #[test]
594 fn test_read_offset_encoding() {
595 let data: Vec<u8> = vec![0b_1101_0101, 0b_0000_0101];
596 let mut cursor = Cursor::new(data);
597 let result = read_offset_encoding(&mut cursor);
598 assert!(result.is_ok());
599 assert_eq!(result.unwrap(), (11013, 2));
600 }
601
602 /// `calculate_object_hash_for_kind` follows the explicit kind under the opposite
603 /// thread-local kind, agrees with `ObjectHash::from_type_and_data_for_kind`, and fails
604 /// closed for delta types; the legacy entry point follows the thread-local kind.
605 #[test]
606 fn calculate_object_hash_for_kind_ignores_thread_local() {
607 let data = b"hello pack";
608 for (kind, other) in [
609 (HashKind::Sha1, HashKind::Sha256),
610 (HashKind::Sha256, HashKind::Sha1),
611 ] {
612 let _guard = set_hash_kind_for_test(other);
613 let explicit = calculate_object_hash_for_kind(kind, ObjectType::Blob, data).unwrap();
614 assert_eq!(explicit.kind(), kind);
615 assert_eq!(
616 explicit,
617 ObjectHash::from_type_and_data_for_kind(kind, ObjectType::Blob, data).unwrap()
618 );
619 assert_eq!(calculate_object_hash(ObjectType::Blob, data).kind(), other);
620 {
621 let _same = set_hash_kind_for_test(kind);
622 assert_eq!(calculate_object_hash(ObjectType::Blob, data), explicit);
623 }
624 let err =
625 calculate_object_hash_for_kind(kind, ObjectType::OffsetDelta, data).unwrap_err();
626 assert_eq!(
627 err,
628 HashError::UnsupportedObjectType {
629 operation: "calculate_object_hash_for_kind",
630 kind,
631 object_type: ObjectType::OffsetDelta,
632 expected: kind.size(),
633 actual: 0,
634 payload_len: data.len(),
635 }
636 );
637 }
638 }
639}