Skip to content

Commit

Permalink
feat: add file::Index::usize_offset_by_id() and `range::into_usize_…
Browse files Browse the repository at this point in the history
…or_panic()` (#279)
  • Loading branch information
Byron committed Dec 21, 2021
1 parent 51b991b commit e14096e
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
14 changes: 14 additions & 0 deletions git-chunk/src/file/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,20 @@ impl Index {
.ok_or(offset_by_kind::Error { kind })
}

/// Find a chunk of `kind` and return its offset as usize range into the data if found.
///
///
/// # Panics
///
/// - if the usize conversion fails, which isn't expected as memory maps can't be created if files are too large
/// to require such offsets.
pub fn usize_offset_by_id(&self, kind: crate::Id) -> Result<Range<usize>, offset_by_kind::Error> {
self.chunks
.iter()
.find_map(|c| (c.kind == kind).then(|| crate::range::into_usize_or_panic(c.offset.clone())))
.ok_or(offset_by_kind::Error { kind })
}

/// Find a chunk of `kind` and return its data slice based on its offset.
pub fn data_by_id<'a>(&self, data: &'a [u8], kind: crate::Id) -> Result<&'a [u8], data_by_kind::Error> {
let offset = self.offset_by_id(kind)?;
Expand Down
9 changes: 9 additions & 0 deletions git-chunk/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,15 @@ pub mod range {
let end = end.try_into().ok()?;
Some(Range { start, end })
}

/// Similar to [`into_usize()`], but panics assuming that the memory map couldn't be created if offsets
/// stored are too high.
///
/// This is only true for correctly formed files, as it's entirely possible to provide out of bounds offsets
/// which are checked for separately - we wouldn't be here if that was the case.
pub fn into_usize_or_panic(range: Range<file::Offset>) -> Range<usize> {
into_usize(range).expect("memory maps can't be created if files are too large")
}
}

///
Expand Down

0 comments on commit e14096e

Please sign in to comment.