Skip to content

Commit 521c894

Browse files
committed
Don't hardcode Sha1 (#413)
1 parent 85b9f13 commit 521c894

File tree

4 files changed

+28
-1
lines changed

4 files changed

+28
-1
lines changed

git-hash/src/lib.rs

+10
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,16 @@ impl Kind {
144144
}
145145
}
146146

147+
/// Returns the kind of hash that would fit the given `hex_len`, or `None` if there is no fitting hash.
148+
/// Note that 0 as `hex_len` fits always yields Sha1.
149+
#[inline]
150+
pub const fn from_hex_len(hex_len: usize) -> Option<Self> {
151+
Some(match hex_len {
152+
0..=40 => Kind::Sha1,
153+
_ => return None,
154+
})
155+
}
156+
147157
/// Converts a size in bytes as obtained by `Kind::len_in_bytes()` into the corresponding hash kind, if possible.
148158
///
149159
/// **Panics** if the hash length doesn't match a known hash.

git-hash/src/owned/prefix.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,7 @@ impl Prefix {
123123
hex::FromHexError::OddLength | hex::FromHexError::InvalidStringLength => panic!("This is already checked"),
124124
})?;
125125

126-
let mut bytes = ObjectId::null(crate::Kind::Sha1);
126+
let mut bytes = ObjectId::null(crate::Kind::from_hex_len(value.len()).expect("hex-len is already checked"));
127127
let dst = bytes.as_mut_slice();
128128
let copy_len = src.len();
129129
dst[..copy_len].copy_from_slice(&src);

git-hash/tests/integration.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1+
mod kind;
12
mod oid;

git-hash/tests/kind/mod.rs

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
mod from_hex_len {
2+
use git_hash::Kind;
3+
4+
#[test]
5+
fn some_sha1() {
6+
assert_eq!(Kind::from_hex_len(0), Some(Kind::Sha1));
7+
assert_eq!(Kind::from_hex_len(10), Some(Kind::Sha1));
8+
assert_eq!(Kind::from_hex_len(20), Some(Kind::Sha1));
9+
assert_eq!(Kind::from_hex_len(40), Some(Kind::Sha1));
10+
}
11+
12+
#[test]
13+
fn none_if_there_is_no_fit() {
14+
assert_eq!(Kind::from_hex_len(65), None);
15+
}
16+
}

0 commit comments

Comments
 (0)