aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJosh Triplett <[email protected]>2025-02-16 21:06:11 +0100
committerJack O'Connor <[email protected]>2025-02-17 14:30:20 -0800
commitc0938ee148d511e63f702a6bbfbc336ad6c83322 (patch)
treedafc2822ed40384bf7d30831582bce45b1dc10a4
parent41b5c02b5718e38d9ac50523f0724a867678b46a (diff)
Add `Hash::from_slice` to handle conversion from `&[u8]` bytes
This is a convenience method, to avoid having to first call `<[u8; 32]>::try_from(slice)?`.
-rw-r--r--src/lib.rs7
-rw-r--r--src/test.rs10
2 files changed, 17 insertions, 0 deletions
diff --git a/src/lib.rs b/src/lib.rs
index 37c2c0b..355668f 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -236,6 +236,13 @@ impl Hash {
Self(bytes)
}
+ /// Create a `Hash` from its raw bytes representation as a slice.
+ ///
+ /// Returns an error if the slice is not exactly 32 bytes long.
+ pub fn from_slice(bytes: &[u8]) -> Result<Self, core::array::TryFromSliceError> {
+ Ok(Self::from_bytes(bytes.try_into()?))
+ }
+
/// Encode a `Hash` in lowercase hexadecimal.
///
/// The returned [`ArrayString`] is a fixed size and doesn't allocate memory
diff --git a/src/test.rs b/src/test.rs
index 3041b0c..506d7aa 100644
--- a/src/test.rs
+++ b/src/test.rs
@@ -763,6 +763,16 @@ fn test_hash_conversions() {
let hex = hash1.to_hex();
let hash3 = crate::Hash::from_hex(hex.as_bytes()).unwrap();
assert_eq!(hash1, hash3);
+
+ let slice1: &[u8] = bytes1.as_slice();
+ let hash4 = crate::Hash::from_slice(slice1).expect("correct length");
+ assert_eq!(hash1, hash4);
+
+ assert!(crate::Hash::from_slice(&[]).is_err());
+ assert!(crate::Hash::from_slice(&[42]).is_err());
+ assert!(crate::Hash::from_slice([42; 31].as_slice()).is_err());
+ assert!(crate::Hash::from_slice([42; 33].as_slice()).is_err());
+ assert!(crate::Hash::from_slice([42; 100].as_slice()).is_err());
}
#[test]