History

feat: add `encode::compute_hash()` for an easy way to obtain object hashes.

Sebastian Thiel committed 3 years ago

Commit ebf3fd41 parent 45a0ac14 files · +26 −5Browse files

Unified · Split

4 files
  1. gix-object/src/data.rs +1 −5
  2. gix-object/src/lib.rs +11 −0
  3. gix-object/tests/loose/mod.rs +0 −0
  4. gix-object/tests/object.rs +14 −0
gix-object/src/data.rs+1−5
@@ -69,11 +69,7 @@ pub mod verify { · 68 unmodified lines
6969 /// hash of `self`.
7070 pub fn verify_checksum(&self, desired: impl AsRef<gix_hash::oid>) -> Result<(), Error> {
7171 let desired = desired.as_ref();
72− let mut hasher = gix_features::hash::hasher(desired.kind());
73− hasher.update(&crate::encode::loose_header(self.kind, self.data.len()));
74− hasher.update(self.data);
75−
76− let actual_id = gix_hash::ObjectId::from(hasher.digest());
72+ let actual_id = crate::compute_hash(desired.kind(), self.kind, self.data);
7773 if desired != actual_id {
7874 return Err(Error::ChecksumMismatch {
7975 desired: desired.into(),
gix-object/src/lib.rs+11−0
@@ -375,3 +375,14 @@ pub mod decode { · 374 unmodified lines
375375 Ok((kind, size, size_end + 1))
376376 }
377377 }
378+
379+/// A standalone function to compute a hash of kind `hash_kind` for an object of `object_kind` and its `data`.
380+pub fn compute_hash(hash_kind: gix_hash::Kind, object_kind: Kind, data: &[u8]) -> gix_hash::ObjectId {
381+ let header = encode::loose_header(object_kind, data.len());
382+
383+ let mut hasher = gix_features::hash::hasher(hash_kind);
384+ hasher.update(&header);
385+ hasher.update(data);
386+
387+ hasher.digest().into()
388+}
gix-object/tests/loose/mod.rsrenamed from gix-object/tests/loose.rs+0−0

File renamed without changes.

gix-object/tests/object.rs+14−0
@@ -4,6 +4,20 @@ use gix_hash::ObjectId; · 3 unmodified lines
44
55 mod encode;
66 mod immutable;
7+mod loose;
8+
9+#[test]
10+fn compute_hash() {
11+ let hk = gix_hash::Kind::Sha1;
12+ assert_eq!(
13+ gix_object::compute_hash(hk, gix_object::Kind::Blob, &[]),
14+ gix_hash::ObjectId::empty_blob(hk)
15+ );
16+ assert_eq!(
17+ gix_object::compute_hash(hk, gix_object::Kind::Tree, &[]),
18+ gix_hash::ObjectId::empty_tree(hk)
19+ );
20+}
721
822 type Result<T = ()> = std::result::Result<T, Box<dyn std::error::Error>>;
923