Skip to content

Commit 308b95d

Browse files
joshtriplettoconnor663
authored andcommitted
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.
1 parent eae9bf3 commit 308b95d

File tree

2 files changed

+11
-0
lines changed

2 files changed

+11
-0
lines changed

src/lib.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,6 +253,14 @@ impl Hash {
253253
Self(bytes)
254254
}
255255

256+
/// The raw bytes of the `Hash`, as a slice. Useful for serialization. Note that byte arrays
257+
/// don't provide constant-time equality checking, so if you need to compare hashes, prefer
258+
/// the `Hash` type.
259+
#[inline]
260+
pub const fn as_slice(&self) -> &[u8] {
261+
self.0.as_slice()
262+
}
263+
256264
/// Create a `Hash` from its raw bytes representation as a slice.
257265
///
258266
/// Returns an error if the slice is not exactly 32 bytes long.

src/test.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -756,6 +756,9 @@ fn test_hash_conversions() {
756756
let hash4 = crate::Hash::from_slice(slice1).expect("correct length");
757757
assert_eq!(hash1, hash4);
758758

759+
let slice2 = hash1.as_slice();
760+
assert_eq!(slice1, slice2);
761+
759762
assert!(crate::Hash::from_slice(&[]).is_err());
760763
assert!(crate::Hash::from_slice(&[42]).is_err());
761764
assert!(crate::Hash::from_slice([42; 31].as_slice()).is_err());

0 commit comments

Comments
 (0)