dengel / dengel-git
PublicCommit
bb7110d//! Parser for pack-*.idx version 2 files.
//!
//! Format source: git-reference/Documentation/gitformat-pack.adoc,
//! section "Version 2 pack-*.idx files" (Documentation, not C source -
//! permitted under the clean-room rule).
use std::fs;
use std::io;
use std::path::Path;
const IDX_V2_MAGIC: [u8; 4] = [0xff, b't', b'O', b'c'];
const OID_LEN: usize = 20; // sha1 only for this spike
#[derive(Debug, Clone)]
pub struct IdxEntry {
pub oid: String,
pub offset: u64,
pub crc32: u32,
}
#[derive(Debug)]
pub struct Idx {
pub entries: Vec<IdxEntry>,
}
fn read_u32_be(bytes: &[u8], at: usize) -> u32 {
u32::from_be_bytes(bytes[at..at + 4].try_into().unwrap())
}
fn read_u64_be(bytes: &[u8], at: usize) -> u64 {
u64::from_be_bytes(bytes[at..at + 8].try_into().unwrap())
}
fn hex(bytes: &[u8]) -> String {
bytes.iter().map(|b| format!("{:02x}", b)).collect()
}
/// Parse a version-2 .idx file. Panics (via assert) on v1 or malformed
/// input - the spike's corpus is generated by a current git, which
/// always writes v2, so v1 support is out of scope.
pub fn parse(path: &Path) -> io::Result<Idx> {
let data = fs::read(path)?;
assert!(data.len() >= 8, "idx file too short for header");
assert_eq!(
&data[0..4],
&IDX_V2_MAGIC,
"not a v2 idx file (bad magic) - v1 idx is out of scope for this spike"
);
let version = read_u32_be(&data, 4);
assert_eq!(version, 2, "expected idx version 2, got {}", version);
// Fan-out table: 256 4-byte big-endian counts. fanout[255] = total objects.
let fanout_start = 8;
let fanout_end = fanout_start + 256 * 4;
let object_count = read_u32_be(&data, fanout_end - 4) as usize;
// OID table: object_count * 20 bytes, sorted.
let oid_table_start = fanout_end;
let oid_table_end = oid_table_start + object_count * OID_LEN;
// CRC32 table: object_count * 4 bytes.
let crc_table_start = oid_table_end;
let crc_table_end = crc_table_start + object_count * 4;
// Offset table: object_count * 4 bytes. MSB set => index into
// the large-offset table (8-byte entries) that follows.
let offset_table_start = crc_table_end;
let offset_table_end = offset_table_start + object_count * 4;
let large_offset_table_start = offset_table_end;
let mut entries = Vec::with_capacity(object_count);
for i in 0..object_count {
let oid_bytes = &data[oid_table_start + i * OID_LEN..oid_table_start + (i + 1) * OID_LEN];
let oid = hex(oid_bytes);
let crc32 = read_u32_be(&data, crc_table_start + i * 4);
let raw_offset = read_u32_be(&data, offset_table_start + i * 4);
let offset = if raw_offset & 0x8000_0000 != 0 {
let large_index = (raw_offset & 0x7fff_ffff) as usize;
read_u64_be(&data, large_offset_table_start + large_index * 8)
} else {
raw_offset as u64
};
entries.push(IdxEntry { oid, offset, crc32 });
}
Ok(Idx { entries })
}
