Skip to content

Commit 86455d5

Browse files
authored
feat: make Zeroizing transparent for cheap conversions (#761)
Sometimes libraries want to be generic across types like `Vec<u8>` and `Box<[u8]>`. Therefore, they use bounds like `T: AsRef<[u8]>`. The `Zeroizing<Vec<u8>>` type should be transparently equivalent to `Vec<u8>` in this regard. This allows `Zeroizing` to be used with all such bounds. Signed-off-by: Nathaniel McCallum <[email protected]>
1 parent 3bd7698 commit 86455d5

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

zeroize/src/lib.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -580,6 +580,26 @@ where
580580
}
581581
}
582582

583+
impl<T, Z> AsRef<T> for Zeroizing<Z>
584+
where
585+
T: ?Sized,
586+
Z: AsRef<T> + Zeroize,
587+
{
588+
fn as_ref(&self) -> &T {
589+
self.0.as_ref()
590+
}
591+
}
592+
593+
impl<T, Z> AsMut<T> for Zeroizing<Z>
594+
where
595+
T: ?Sized,
596+
Z: AsMut<T> + Zeroize,
597+
{
598+
fn as_mut(&mut self) -> &mut T {
599+
self.0.as_mut()
600+
}
601+
}
602+
583603
impl<Z> Zeroize for Zeroizing<Z>
584604
where
585605
Z: Zeroize,
@@ -700,6 +720,9 @@ mod tests {
700720
#[cfg(feature = "alloc")]
701721
use alloc::boxed::Box;
702722

723+
#[cfg(feature = "alloc")]
724+
use alloc::vec::Vec;
725+
703726
#[derive(Clone, Debug, PartialEq)]
704727
struct ZeroizedOnDrop(u64);
705728

@@ -865,4 +888,16 @@ mod tests {
865888
boxed_arr.zeroize();
866889
assert_eq!(boxed_arr.as_ref(), &[0u8; 3]);
867890
}
891+
892+
#[cfg(feature = "alloc")]
893+
#[test]
894+
fn asref() {
895+
let mut buffer: Zeroizing<Vec<u8>> = Default::default();
896+
let _asmut: &mut [u8] = buffer.as_mut();
897+
let _asref: &[u8] = buffer.as_ref();
898+
899+
let mut buffer: Zeroizing<Box<[u8]>> = Default::default();
900+
let _asmut: &mut [u8] = buffer.as_mut();
901+
let _asref: &[u8] = buffer.as_ref();
902+
}
868903
}

0 commit comments

Comments
 (0)