Skip to main content

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