Skip to content
This repository was archived by the owner on Nov 30, 2022. It is now read-only.

Commit be8b9f1

Browse files
committed
Add method as_mut_bytes
We implement `as_bytes` on hash types; in order to be able to modify a hash it would be useful to iterate the inner byte array mutable. Add a `as_mut_bytes` method to all hash types and also to any hash created with `hash_newtype`.
1 parent 07fac40 commit be8b9f1

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

Diff for: src/util.rs

+23-1
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ macro_rules! borrow_slice_impl(
7070
)
7171
);
7272

73-
/// Adds a method `as_bytes` to a given type `$ty`.
73+
/// Adds methods `as_bytes` and `as_mut_bytes` to a given type `$ty`.
7474
#[macro_export]
7575
macro_rules! as_bytes_impl(
7676
($ty:ident, $len:expr) => (
@@ -82,6 +82,11 @@ macro_rules! as_bytes_impl(
8282
pub fn as_bytes(&self) -> &[u8; $len] {
8383
&self.0
8484
}
85+
86+
/// Returns `self` as a mutable byte array reference.
87+
pub fn as_mut_bytes(&mut self) -> &mut [u8; $len] {
88+
&mut self.0
89+
}
8590
}
8691
);
8792
);
@@ -149,6 +154,11 @@ macro_rules! hash_newtype {
149154
pub fn as_bytes(&self) -> &[u8; $len] {
150155
&self.0.as_bytes()
151156
}
157+
158+
/// Returns `self` as a mutable byte array reference.
159+
pub fn as_mut_bytes(&mut self) -> &mut [u8; $len] {
160+
self.0.as_mut_bytes()
161+
}
152162
}
153163

154164
impl $crate::_export::_core::convert::From<$hash> for $newtype {
@@ -279,4 +289,16 @@ mod test {
279289
let got = format!("{:#x}", TestHash::all_zeros());
280290
assert_eq!(got, want)
281291
}
292+
293+
#[test]
294+
fn as_mut_bytes() {
295+
let mut hash = TestHash::all_zeros();
296+
for b in hash.as_mut_bytes().iter_mut() {
297+
*b = 0xff;
298+
}
299+
300+
let got = format!("{:#x}", hash);
301+
let want = "0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff";
302+
assert_eq!(got, want)
303+
}
282304
}

0 commit comments

Comments
 (0)