aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorJosh Triplett <[email protected]>2025-11-17 15:03:12 -0800
committerJack O'Connor <[email protected]>2025-11-24 12:44:37 -0800
commit308b95dfa15d5a0aa8cb3c5534ffd90d76122c46 (patch)
tree79a01d4e01b3700167ba22d888fed42ec936bf8a /src
parenteae9bf376a1c4797df7be6e49e735c0a5d91dcb0 (diff)
Add `Hash::as_slice()` for convenient serialization to bytes
`Hash::as_bytes()` returns the hash as an array of bytes. However, sometimes it's useful to have the hash as a slice of bytes instead, such as for serialization via an API that takes `&[u8]`. While `.as_bytes().as_slice()` works for this, it'd be more convenient to have a direct `.as_slice()` on hashes.
Diffstat (limited to 'src')
-rw-r--r--src/lib.rs8
-rw-r--r--src/test.rs3
2 files changed, 11 insertions, 0 deletions
diff --git a/src/lib.rs b/src/lib.rs
index 217314c..f27f903 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -253,6 +253,14 @@ impl Hash {
Self(bytes)
}
+ /// The raw bytes of the `Hash`, as a slice. Useful for serialization. Note that byte arrays
+ /// don't provide constant-time equality checking, so if you need to compare hashes, prefer
+ /// the `Hash` type.
+ #[inline]
+ pub const fn as_slice(&self) -> &[u8] {
+ self.0.as_slice()
+ }
+
/// Create a `Hash` from its raw bytes representation as a slice.
///
/// Returns an error if the slice is not exactly 32 bytes long.
diff --git a/src/test.rs b/src/test.rs
index 771ed74..8b6b292 100644
--- a/src/test.rs
+++ b/src/test.rs
@@ -756,6 +756,9 @@ fn test_hash_conversions() {
let hash4 = crate::Hash::from_slice(slice1).expect("correct length");
assert_eq!(hash1, hash4);
+ let slice2 = hash1.as_slice();
+ assert_eq!(slice1, slice2);
+
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());