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
69 /// hash of `self`.69 /// hash of `self`.
70 pub fn verify_checksum(&self, desired: impl AsRef<gix_hash::oid>) -> Result<(), Error> {70 pub fn verify_checksum(&self, desired: impl AsRef<gix_hash::oid>) -> Result<(), Error> {
71 let desired = desired.as_ref();71 let desired = desired.as_ref();
72 let mut hasher = gix_features::hash::hasher(desired.kind());72 let actual_id = crate::compute_hash(desired.kind(), self.kind, self.data);
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());
77 if desired != actual_id {73 if desired != actual_id {
78 return Err(Error::ChecksumMismatch {74 return Err(Error::ChecksumMismatch {
79 desired: desired.into(),75 desired: desired.into(),
gix-object/src/lib.rs+11−0
@@ -375,3 +375,14 @@ pub mod decode { · 374 unmodified lines
375 Ok((kind, size, size_end + 1))375 Ok((kind, size, size_end + 1))
376 }376 }
377}377}
378
379/// A standalone function to compute a hash of kind `hash_kind` for an object of `object_kind` and its `data`.
380pub 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
4 4
5mod encode;5mod encode;
6mod immutable;6mod immutable;
7mod loose;
8
9#[test]
10fn 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}
7 21
8type Result<T = ()> = std::result::Result<T, Box<dyn std::error::Error>>;22type Result<T = ()> = std::result::Result<T, Box<dyn std::error::Error>>;
9 23