use tokio::sync::mpsc;
pub use crate::internal::pack::index_entry::IndexEntry;
use crate::{
errors::GitError,
hash::{HashKind, ObjectHash},
utils::HashAlgorithm,
};
pub const IDX_MAGIC: u32 = 0xff74_4f63;
pub const IDX_VERSION_V2: u32 = 2;
const IDX_PREALLOC_CAP: usize = 1 << 16;
pub fn validate_idx_v2_header(
magic: u32,
version: u32,
kind: HashKind,
context: &str,
) -> Result<(), GitError> {
if magic != IDX_MAGIC {
return Err(GitError::InvalidPackFile(format!(
"Invalid pack index magic {magic:#010x} for {context} ({kind} repository)"
)));
}
if version != IDX_VERSION_V2 {
return Err(GitError::InvalidPackFile(format!(
"Only pack index v2 is supported for {context}: got version {version} (this crate reads and writes v2 only; {kind} repository, {}-byte object names)",
kind.size()
)));
}
Ok(())
}
#[derive(Debug, Clone)]
pub struct IdxV2 {
pub entries: Vec<IndexEntry>,
pub pack_hash: ObjectHash,
pub idx_hash: ObjectHash,
}
struct IdxHashingReader<R> {
inner: R,
hasher: HashAlgorithm,
}
impl<R: std::io::Read> IdxHashingReader<R> {
fn read_exact_hashed(&mut self, buf: &mut [u8]) -> Result<(), GitError> {
self.inner
.read_exact(buf)
.map_err(|e| GitError::InvalidPackFile(format!("Read index error: {e}")))?;
self.hasher.update(buf);
Ok(())
}
fn read_u32_hashed(&mut self) -> Result<u32, GitError> {
let mut buf = [0u8; 4];
self.read_exact_hashed(&mut buf)?;
Ok(u32::from_be_bytes(buf))
}
}
pub fn parse_idx_v2(bytes: &[u8], kind: HashKind) -> Result<IdxV2, GitError> {
parse_idx_v2_from(std::io::Cursor::new(bytes), kind, bytes.len() as u64)
}
pub fn parse_idx_v2_from<R: std::io::Read>(
reader: R,
kind: HashKind,
total_len: u64,
) -> Result<IdxV2, GitError> {
let hs = kind.size();
let mut reader = IdxHashingReader {
inner: reader,
hasher: HashAlgorithm::new_for_kind(kind),
};
let magic = reader.read_u32_hashed()?;
let version = reader.read_u32_hashed()?;
validate_idx_v2_header(magic, version, kind, "index parsing")?;
let mut fanout = [0u32; 256];
for i in 0..256 {
fanout[i] = reader.read_u32_hashed()?;
if i > 0 && fanout[i] < fanout[i - 1] {
return Err(GitError::InvalidPackFile(format!(
"Pack index fanout is not monotonic at entry {i}"
)));
}
}
let object_num = fanout[255] as usize;
let fixed = 8u64 + 256 * 4 + 2 * hs as u64;
let per_object = (hs + 4 + 4) as u64;
let declared = fixed + per_object * object_num as u64;
if declared > total_len {
return Err(GitError::InvalidPackFile(format!(
"Pack index declares {object_num} objects ({declared} bytes) but is only {total_len} bytes long"
)));
}
let mut entries: Vec<IndexEntry> = Vec::with_capacity(object_num.min(IDX_PREALLOC_CAP));
let mut per_first_byte = [0u32; 256];
let mut name = vec![0u8; hs];
for i in 0..object_num {
reader.read_exact_hashed(&mut name)?;
let hash = ObjectHash::from_bytes_for_kind(kind, &name)
.map_err(|e| GitError::InvalidPackFile(format!("Pack index object name {i}: {e}")))?;
if let Some(prev) = entries.last()
&& prev.hash.as_ref() >= name.as_slice()
{
return Err(GitError::InvalidPackFile(format!(
"Pack index object names are not strictly ascending at entry {i}"
)));
}
per_first_byte[name[0] as usize] += 1;
entries.push(IndexEntry {
hash,
crc32: 0,
offset: 0,
});
}
let mut running = 0u32;
for (byte, count) in per_first_byte.iter().enumerate() {
running += count;
if fanout[byte] != running {
return Err(GitError::InvalidPackFile(format!(
"Pack index fanout[{byte:#04x}] is {} but {running} object names start at or below it",
fanout[byte]
)));
}
}
for entry in entries.iter_mut() {
entry.crc32 = reader.read_u32_hashed()?;
}
let mut large_slots = Vec::new();
for (i, entry) in entries.iter_mut().enumerate() {
let raw_offset = reader.read_u32_hashed()?;
if raw_offset & 0x8000_0000 == 0 {
entry.offset = u64::from(raw_offset);
} else {
large_slots.push((i, (raw_offset & 0x7fff_ffff) as usize));
}
}
let large_count = large_slots
.iter()
.map(|&(_, slot)| slot + 1)
.max()
.unwrap_or(0);
if large_count > large_slots.len() {
return Err(GitError::InvalidPackFile(format!(
"Pack index references large-offset slot {} but only {} objects use the large table",
large_count - 1,
large_slots.len()
)));
}
if declared + (large_count as u64) * 8 > total_len {
return Err(GitError::InvalidPackFile(
"Pack index is truncated before its large-offset table".to_string(),
));
}
let mut large_offsets = Vec::with_capacity(large_count);
for _ in 0..large_count {
let mut buf = [0u8; 8];
reader.read_exact_hashed(&mut buf)?;
large_offsets.push(u64::from_be_bytes(buf));
}
for (i, slot) in large_slots {
entries[i].offset = large_offsets[slot];
}
let mut seen_offsets = std::collections::HashSet::with_capacity(entries.len());
for entry in &entries {
if !seen_offsets.insert(entry.offset) {
return Err(GitError::InvalidPackFile(format!(
"Pack index lists offset {} more than once",
entry.offset
)));
}
}
let mut pack_hash_buf = vec![0u8; hs];
reader.read_exact_hashed(&mut pack_hash_buf)?;
let pack_hash = ObjectHash::from_bytes_for_kind(kind, &pack_hash_buf)
.map_err(|e| GitError::InvalidPackFile(format!("Pack index pack checksum: {e}")))?;
let computed = reader.hasher.clone().finalize_object_hash();
let mut idx_hash_buf = vec![0u8; hs];
reader
.inner
.read_exact(&mut idx_hash_buf)
.map_err(|e| GitError::InvalidPackFile(format!("Read index error: {e}")))?;
let idx_hash = ObjectHash::from_bytes_for_kind(kind, &idx_hash_buf)
.map_err(|e| GitError::InvalidPackFile(format!("Pack index checksum: {e}")))?;
if computed != idx_hash {
return Err(GitError::InvalidPackFile(format!(
"Pack index checksum {idx_hash} does not match calculated checksum {computed} ({kind})"
)));
}
let mut trailing = [0u8; 1];
let extra = reader
.inner
.read(&mut trailing)
.map_err(|e| GitError::InvalidPackFile(format!("Read index error: {e}")))?;
if extra != 0 {
return Err(GitError::InvalidPackFile(
"Pack index has trailing data after checksum".to_string(),
));
}
Ok(IdxV2 {
entries,
pack_hash,
idx_hash,
})
}
pub struct IdxBuilder {
sender: Option<mpsc::Sender<Vec<u8>>>,
inner_hash: HashAlgorithm, object_number: usize,
pack_hash: ObjectHash,
}
pub fn parse_idx_v1(bytes: &[u8]) -> Result<IdxV2, GitError> {
const FANOUT_LEN: usize = 256 * 4;
const ENTRY_LEN: usize = 4 + 20;
const TRAILER_LEN: usize = 20 + 20;
if bytes.len() < FANOUT_LEN + TRAILER_LEN {
return Err(GitError::InvalidPackFile(
"pack index v1 is too short".to_string(),
));
}
let mut fanout = [0u32; 256];
for (slot, chunk) in bytes[..FANOUT_LEN].as_chunks::<4>().0.iter().enumerate() {
fanout[slot] = u32::from_be_bytes(*chunk);
}
for pair in fanout.windows(2) {
if pair[0] > pair[1] {
return Err(GitError::InvalidPackFile(
"pack index v1 fanout table is not monotonic".to_string(),
));
}
}
let object_count = fanout[255] as usize;
let expected_len = FANOUT_LEN
.checked_add(object_count.saturating_mul(ENTRY_LEN))
.and_then(|len| len.checked_add(TRAILER_LEN))
.ok_or_else(|| GitError::InvalidPackFile("pack index v1 size overflow".to_string()))?;
if bytes.len() != expected_len {
return Err(GitError::InvalidPackFile(format!(
"pack index v1 length {} does not match fanout object count {object_count}",
bytes.len()
)));
}
let trailer_start = FANOUT_LEN + object_count * ENTRY_LEN;
let mut hasher = HashAlgorithm::new_for_kind(HashKind::Sha1);
hasher.update(&bytes[..trailer_start + 20]);
let computed = hasher.finalize_object_hash();
let idx_hash_bytes = &bytes[trailer_start + 20..trailer_start + 40];
if computed.as_ref() != idx_hash_bytes {
return Err(GitError::InvalidPackFile(
"pack index v1 checksum mismatch".to_string(),
));
}
let pack_hash = ObjectHash::Sha1(
bytes[trailer_start..trailer_start + 20]
.try_into()
.map_err(|_| GitError::InvalidPackFile("pack index v1 pack hash".to_string()))?,
);
let idx_hash = ObjectHash::Sha1(
idx_hash_bytes
.try_into()
.map_err(|_| GitError::InvalidPackFile("pack index v1 idx hash".to_string()))?,
);
let mut entries = Vec::with_capacity(object_count);
for index in 0..object_count {
let start = FANOUT_LEN + index * ENTRY_LEN;
let offset = u32::from_be_bytes(
bytes[start..start + 4]
.try_into()
.map_err(|_| GitError::InvalidPackFile("pack index v1 offset".to_string()))?,
) as u64;
let hash = ObjectHash::Sha1(
bytes[start + 4..start + ENTRY_LEN]
.try_into()
.map_err(|_| GitError::InvalidPackFile("pack index v1 object name".to_string()))?,
);
entries.push(IndexEntry {
hash,
crc32: 0,
offset,
});
}
Ok(IdxV2 {
entries,
pack_hash,
idx_hash,
})
}
impl IdxBuilder {
pub fn new(object_number: usize, sender: mpsc::Sender<Vec<u8>>, pack_hash: ObjectHash) -> Self {
Self {
sender: Some(sender),
inner_hash: HashAlgorithm::new_for_kind(pack_hash.kind()),
object_number,
pack_hash,
}
}
pub fn hash_kind(&self) -> HashKind {
self.pack_hash.kind()
}
pub fn drop_sender(&mut self) {
self.sender.take(); }
async fn send_data(&mut self, data: Vec<u8>) -> Result<(), GitError> {
if let Some(sender) = &self.sender {
self.inner_hash.update(&data);
sender.send(data).await.map_err(|e| {
GitError::IOError(std::io::Error::new(
std::io::ErrorKind::BrokenPipe,
format!("Failed to send idx data: {e}"),
))
})?;
}
Ok(())
}
async fn send_data_without_update_hash(&mut self, data: Vec<u8>) -> Result<(), GitError> {
if let Some(sender) = &self.sender {
sender.send(data).await.map_err(|e| {
GitError::IOError(std::io::Error::new(
std::io::ErrorKind::BrokenPipe,
format!("Failed to send idx data: {e}"),
))
})?;
}
Ok(())
}
async fn send_u32(&mut self, v: u32) -> Result<(), GitError> {
self.send_data(v.to_be_bytes().to_vec()).await
}
async fn send_u64(&mut self, v: u64) -> Result<(), GitError> {
self.send_data(v.to_be_bytes().to_vec()).await
}
async fn write_header(&mut self) -> Result<(), GitError> {
let header: [u8; 8] = [0xFF, 0x74, 0x4F, 0x63, 0, 0, 0, 2];
self.send_data(header.to_vec()).await
}
async fn write_fanout(&mut self, entries: &mut [IndexEntry]) -> Result<(), GitError> {
entries.sort_by_key(|entry| entry.hash);
let mut fanout = [0u32; 256];
for entry in entries.iter() {
fanout[entry.hash.to_data()[0] as usize] += 1;
}
for i in 1..fanout.len() {
fanout[i] += fanout[i - 1];
}
for &count in fanout.iter() {
self.send_u32(count).await?;
}
Ok(())
}
async fn write_names(&mut self, entries: &Vec<IndexEntry>) -> Result<(), GitError> {
for e in entries {
self.send_data(e.hash.to_data().clone()).await?;
}
Ok(())
}
async fn write_crc32(&mut self, entries: &Vec<IndexEntry>) -> Result<(), GitError> {
for e in entries {
self.send_u32(e.crc32).await?;
}
Ok(())
}
async fn write_offsets(&mut self, entries: &Vec<IndexEntry>) -> Result<(), GitError> {
let mut large = vec![];
for e in entries {
if e.offset <= 0x7FFF_FFFF {
self.send_u32(e.offset as u32).await?;
} else {
let marker = 0x8000_0000 | large.len() as u32;
self.send_u32(marker).await?;
large.push(e.offset);
}
}
for v in large {
self.send_u64(v).await?;
}
Ok(())
}
async fn write_trailer(&mut self) -> Result<(), GitError> {
self.send_data(self.pack_hash.to_data()).await?;
let idx_hash = self.inner_hash.clone().finalize();
self.send_data_without_update_hash(idx_hash).await?;
Ok(())
}
pub async fn write_idx(&mut self, mut entries: Vec<IndexEntry>) -> Result<(), GitError> {
if entries.len() != self.object_number {
return Err(GitError::ConversionError(format!(
"entries length {} != object_number {}",
entries.len(),
self.object_number
)));
}
let kind = self.hash_kind();
for entry in &entries {
entry.hash.ensure_kind(kind)?;
}
self.write_header().await?;
self.write_fanout(&mut entries).await?;
self.write_names(&entries).await?;
self.write_crc32(&entries).await?;
self.write_offsets(&entries).await?;
self.write_trailer().await?;
self.drop_sender();
Ok(())
}
}
#[cfg(test)]
mod tests {
use tokio::sync::mpsc;
use crate::{
errors::GitError,
hash::ObjectHash,
internal::pack::{index_entry::IndexEntry, pack_index::IdxBuilder},
};
fn fake_sha1(n: u8) -> ObjectHash {
ObjectHash::Sha1([n; 20])
}
fn build_entries_sha1(n: usize) -> Vec<IndexEntry> {
(0..n)
.map(|i| IndexEntry {
hash: fake_sha1(i as u8),
crc32: 0x12345678 + i as u32,
offset: 0x10 + (i as u64) * 3,
})
.collect()
}
#[tokio::test]
async fn test_idx_builder_sha1_basic() -> Result<(), GitError> {
let (tx, mut rx) = mpsc::channel::<Vec<u8>>(4096);
let object_number = 3;
let pack_hash = fake_sha1(0xAA);
let mut builder = IdxBuilder::new(object_number, tx, pack_hash);
let entries = build_entries_sha1(object_number);
builder.write_idx(entries).await?;
let mut out: Vec<u8> = Vec::new();
while let Some(chunk) = rx.recv().await {
out.extend_from_slice(&chunk);
}
assert_eq!(&out[0..8], &[0xFF, 0x74, 0x4F, 0x63, 0, 0, 0, 2]);
let fanout_start = 8;
let fanout_end = fanout_start + 256 * 4;
let fanout_bytes = &out[fanout_start..fanout_end];
let mut fanout = [0u32; 256];
fanout[0] = 1;
fanout[1] = 2;
fanout[2] = 3;
for item in fanout.iter_mut().skip(3) {
*item = 3;
}
for (i, val) in fanout.iter().enumerate() {
let idx = i * 4;
let v = u32::from_be_bytes([
fanout_bytes[idx],
fanout_bytes[idx + 1],
fanout_bytes[idx + 2],
fanout_bytes[idx + 3],
]);
assert_eq!(v, *val, "fanout mismatch at index {i}");
}
let names_start = fanout_end;
let names_end = names_start + object_number * 20; let names_bytes = &out[names_start..names_end];
for i in 0..object_number {
let name = &names_bytes[i * 20..i * 20 + 20];
assert!(name.iter().all(|b| *b == i as u8));
}
let crc_start = names_end;
let crc_end = crc_start + object_number * 4;
let crc_bytes = &out[crc_start..crc_end];
for i in 0..object_number {
let expected = 0x12345678 + i as u32;
let actual = u32::from_be_bytes([
crc_bytes[4 * i],
crc_bytes[4 * i + 1],
crc_bytes[4 * i + 2],
crc_bytes[4 * i + 3],
]);
assert_eq!(expected, actual);
}
let offset_start = crc_end;
let offset_end = offset_start + object_number * 4;
let offsets_bytes = &out[offset_start..offset_end];
for i in 0..object_number {
let expected = 0x10 + (i as u64) * 3;
let actual = u32::from_be_bytes([
offsets_bytes[i * 4],
offsets_bytes[i * 4 + 1],
offsets_bytes[i * 4 + 2],
offsets_bytes[i * 4 + 3],
]);
assert_eq!(expected as u32, actual);
}
let trailer_pack_hash_start = offset_end;
let trailer_pack_hash_end = trailer_pack_hash_start + 20;
let pack_hash_bytes = &out[trailer_pack_hash_start..trailer_pack_hash_end];
assert!(pack_hash_bytes.iter().all(|b| *b == 0xAA));
let idx_hash = &out[trailer_pack_hash_end..trailer_pack_hash_end + 20];
assert_eq!(idx_hash.len(), 20);
Ok(())
}
#[tokio::test]
async fn blake3_idx_v2() -> Result<(), GitError> {
use super::{IDX_MAGIC, IDX_VERSION_V2, validate_idx_v2_header};
use crate::{
hash::{HashKind, set_hash_kind_for_test},
utils::HashAlgorithm,
};
let _guard = set_hash_kind_for_test(HashKind::Sha1);
let fake_blake3 = |n: u8| ObjectHash::Blake3([n; 32]);
let object_number = 4;
let pack_hash = fake_blake3(0xAA);
let large_offset: u64 = 0x1_2345_6789;
let entries: Vec<IndexEntry> = (0..object_number)
.map(|i| IndexEntry {
hash: fake_blake3(i as u8),
crc32: 0x1234_5678 + i as u32,
offset: if i == object_number - 1 {
large_offset
} else {
0x10 + (i as u64) * 3
},
})
.collect();
let (tx, mut rx) = mpsc::channel::<Vec<u8>>(4096);
let mut builder = IdxBuilder::new(object_number, tx, pack_hash);
assert_eq!(builder.hash_kind(), HashKind::Blake3);
builder.write_idx(entries).await?;
let mut out: Vec<u8> = Vec::new();
while let Some(chunk) = rx.recv().await {
out.extend_from_slice(&chunk);
}
assert_eq!(
out.len(),
8 + 256 * 4 + object_number * (32 + 4 + 4) + 8 + 32 + 32
);
assert_eq!(&out[0..8], &[0xFF, 0x74, 0x4F, 0x63, 0, 0, 0, 2]);
let names_start = 8 + 256 * 4;
for i in 0..object_number {
let name = &out[names_start + i * 32..names_start + (i + 1) * 32];
assert_eq!(name, &[i as u8; 32]);
assert_eq!(
ObjectHash::from_bytes_for_kind(HashKind::Blake3, name).unwrap(),
fake_blake3(i as u8)
);
}
let offsets_start = names_start + object_number * 32 + object_number * 4;
let last_slot = &out[offsets_start + 3 * 4..offsets_start + 4 * 4];
assert_eq!(
u32::from_be_bytes(last_slot.try_into().unwrap()),
0x8000_0000
);
let large_table = &out[offsets_start + 4 * 4..offsets_start + 4 * 4 + 8];
assert_eq!(
u64::from_be_bytes(large_table.try_into().unwrap()),
large_offset
);
let trailer_start = out.len() - 64;
assert_eq!(&out[trailer_start..trailer_start + 32], pack_hash.as_ref());
let mut idx_hasher = HashAlgorithm::new_for_kind(HashKind::Blake3);
idx_hasher.update(&out[..trailer_start + 32]);
let expected_idx_hash = idx_hasher.finalize_object_hash();
assert_eq!(expected_idx_hash.kind(), HashKind::Blake3);
assert_eq!(&out[trailer_start + 32..], expected_idx_hash.as_ref());
assert_ne!(
&out[trailer_start + 32..],
ObjectHash::new_for_kind(HashKind::Sha256, &out[..trailer_start + 32]).as_ref()
);
assert!(
validate_idx_v2_header(IDX_MAGIC, IDX_VERSION_V2, HashKind::Blake3, "test").is_ok()
);
for version in [1u32, 3] {
let err =
validate_idx_v2_header(IDX_MAGIC, version, HashKind::Blake3, "test").unwrap_err();
let msg = err.to_string();
assert!(
msg.contains("Only pack index v2")
&& msg.contains("blake3")
&& msg.contains("32-byte"),
"{msg}"
);
assert!(validate_idx_v2_header(IDX_MAGIC, version, HashKind::Sha1, "test").is_err());
assert!(validate_idx_v2_header(IDX_MAGIC, version, HashKind::Sha256, "test").is_err());
}
let err = validate_idx_v2_header(0x1234_5678, IDX_VERSION_V2, HashKind::Blake3, "test")
.unwrap_err();
assert!(err.to_string().contains("magic"), "{err}");
let parsed = super::parse_idx_v2(&out, HashKind::Blake3).unwrap();
assert_eq!(parsed.entries.len(), object_number);
for (i, entry) in parsed.entries.iter().enumerate() {
assert_eq!(entry.hash, fake_blake3(i as u8));
assert_eq!(entry.crc32, 0x1234_5678 + i as u32);
}
assert_eq!(parsed.entries[object_number - 1].offset, large_offset);
assert_eq!(parsed.entries[0].offset, 0x10);
assert_eq!(parsed.pack_hash, pack_hash);
let mut dup = out.clone();
let slot1 = offsets_start + 4;
dup[slot1..slot1 + 4].copy_from_slice(&0x10u32.to_be_bytes());
let mut reseal = HashAlgorithm::new_for_kind(HashKind::Blake3);
reseal.update(&dup[..trailer_start + 32]);
let reseal = reseal.finalize_object_hash();
dup[trailer_start + 32..].copy_from_slice(reseal.as_ref());
let err = super::parse_idx_v2(&dup, HashKind::Blake3).unwrap_err();
assert!(err.to_string().contains("more than once"), "{err}");
let mut hostile = Vec::new();
hostile.extend_from_slice(&IDX_MAGIC.to_be_bytes());
hostile.extend_from_slice(&IDX_VERSION_V2.to_be_bytes());
for _ in 0..255 {
hostile.extend_from_slice(&0u32.to_be_bytes());
}
hostile.extend_from_slice(&u32::MAX.to_be_bytes());
let sparse = std::io::Read::chain(std::io::Cursor::new(hostile), std::io::repeat(0u8));
let err = super::parse_idx_v2_from(sparse, HashKind::Blake3, u64::MAX).unwrap_err();
assert!(err.to_string().contains("not strictly ascending"), "{err}");
assert_eq!(parsed.idx_hash, expected_idx_hash);
let err = super::parse_idx_v2(&out, HashKind::Sha256).unwrap_err();
assert!(err.to_string().contains("checksum"), "{err}");
let mut corrupted = out.clone();
corrupted[names_start + 3] ^= 0x01;
assert!(super::parse_idx_v2(&corrupted, HashKind::Blake3).is_err());
assert!(super::parse_idx_v2(&out[..out.len() - 1], HashKind::Blake3).is_err());
let mut hostile = out.clone();
hostile[8 + 255 * 4..8 + 256 * 4].copy_from_slice(&u32::MAX.to_be_bytes());
let err = super::parse_idx_v2(&hostile, HashKind::Blake3).unwrap_err();
assert!(err.to_string().contains("declares"), "{err}");
let mut skewed = out.clone();
skewed[8..12].copy_from_slice(&0u32.to_be_bytes()); let err = super::parse_idx_v2(&skewed, HashKind::Blake3).unwrap_err();
assert!(err.to_string().contains("fanout"), "{err}");
let (tx, _rx) = mpsc::channel::<Vec<u8>>(64);
let mut builder = IdxBuilder::new(1, tx, pack_hash);
let err = builder
.write_idx(vec![IndexEntry {
hash: ObjectHash::Sha256([7; 32]),
crc32: 0,
offset: 12,
}])
.await
.unwrap_err();
assert!(matches!(err, GitError::InvalidHashValue(_)), "{err:?}");
Ok(())
}
#[tokio::test]
async fn test_idx_builder_sha256_basic() -> Result<(), GitError> {
use crate::{
hash::{HashKind, set_hash_kind_for_test},
utils::HashAlgorithm,
};
let _guard = set_hash_kind_for_test(HashKind::Sha1);
let fake = |n: u8| ObjectHash::Sha256([n; 32]);
let object_number = 3;
let pack_hash = fake(0xBB);
let entries: Vec<IndexEntry> = (0..object_number)
.map(|i| IndexEntry {
hash: fake(i as u8),
crc32: i as u32,
offset: 0x20 + (i as u64) * 5,
})
.collect();
let (tx, mut rx) = mpsc::channel::<Vec<u8>>(4096);
let mut builder = IdxBuilder::new(object_number, tx, pack_hash);
assert_eq!(builder.hash_kind(), HashKind::Sha256);
builder.write_idx(entries).await?;
let mut out = Vec::new();
while let Some(chunk) = rx.recv().await {
out.extend_from_slice(&chunk);
}
assert_eq!(
out.len(),
8 + 256 * 4 + object_number * (32 + 4 + 4) + 32 + 32
);
assert_eq!(&out[0..8], &[0xFF, 0x74, 0x4F, 0x63, 0, 0, 0, 2]);
let names_start = 8 + 256 * 4;
for i in 0..object_number {
assert_eq!(
&out[names_start + i * 32..names_start + (i + 1) * 32],
&[i as u8; 32]
);
}
let trailer_start = out.len() - 64;
assert_eq!(&out[trailer_start..trailer_start + 32], pack_hash.as_ref());
let mut hasher = HashAlgorithm::new_for_kind(HashKind::Sha256);
hasher.update(&out[..trailer_start + 32]);
assert_eq!(
&out[trailer_start + 32..],
hasher.finalize_object_hash().as_ref()
);
let parsed = super::parse_idx_v2(&out, HashKind::Sha256).unwrap();
assert_eq!(parsed.entries.len(), object_number);
assert_eq!(parsed.entries[1].offset, 0x25);
assert_eq!(parsed.pack_hash, pack_hash);
assert!(super::parse_idx_v2(&out, HashKind::Blake3).is_err());
Ok(())
}
#[test]
fn parse_idx_v1_reads_entries_and_verifies_checksum() {
use crate::{
hash::{HashKind, ObjectHash},
utils::HashAlgorithm,
};
let object_hash = ObjectHash::Sha1([0x42u8; 20]);
let pack_hash = ObjectHash::Sha1([0x77u8; 20]);
let mut bytes = vec![0u8; 256 * 4];
for slot in 0x42..256usize {
bytes[slot * 4..slot * 4 + 4].copy_from_slice(&1u32.to_be_bytes());
}
bytes.extend_from_slice(&12u32.to_be_bytes());
bytes.extend_from_slice(object_hash.as_ref());
bytes.extend_from_slice(pack_hash.as_ref());
let mut hasher = HashAlgorithm::new_for_kind(HashKind::Sha1);
hasher.update(&bytes);
let idx_hash = hasher.finalize_object_hash();
bytes.extend_from_slice(idx_hash.as_ref());
let parsed = super::parse_idx_v1(&bytes).expect("v1 index must parse");
assert_eq!(parsed.entries.len(), 1);
assert_eq!(parsed.entries[0].hash, object_hash);
assert_eq!(parsed.entries[0].offset, 12);
assert_eq!(parsed.entries[0].crc32, 0, "v1 carries no CRC table");
assert_eq!(parsed.pack_hash, pack_hash);
assert_eq!(parsed.idx_hash, idx_hash);
let mut corrupt = bytes.clone();
let last = corrupt.len() - 1;
corrupt[last] ^= 0xFF;
assert!(
super::parse_idx_v1(&corrupt).is_err(),
"checksum must fail closed"
);
}
}