diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/lib.rs | 7 | ||||
| -rw-r--r-- | src/test.rs | 10 |
2 files changed, 17 insertions, 0 deletions
@@ -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] |
