Skip to content

Commit

Permalink
feat: make Zeroizing transparent for cheap conversions (#761)
Browse files Browse the repository at this point in the history
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 <nathaniel@profian.com>
  • Loading branch information
npmccallum committed Apr 20, 2022
1 parent 3bd7698 commit 86455d5
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions zeroize/src/lib.rs
Expand Up @@ -580,6 +580,26 @@ where
}
}

impl<T, Z> AsRef<T> for Zeroizing<Z>
where
T: ?Sized,
Z: AsRef<T> + Zeroize,
{
fn as_ref(&self) -> &T {
self.0.as_ref()
}
}

impl<T, Z> AsMut<T> for Zeroizing<Z>
where
T: ?Sized,
Z: AsMut<T> + Zeroize,
{
fn as_mut(&mut self) -> &mut T {
self.0.as_mut()
}
}

impl<Z> Zeroize for Zeroizing<Z>
where
Z: Zeroize,
Expand Down Expand Up @@ -700,6 +720,9 @@ mod tests {
#[cfg(feature = "alloc")]
use alloc::boxed::Box;

#[cfg(feature = "alloc")]
use alloc::vec::Vec;

#[derive(Clone, Debug, PartialEq)]
struct ZeroizedOnDrop(u64);

Expand Down Expand Up @@ -865,4 +888,16 @@ mod tests {
boxed_arr.zeroize();
assert_eq!(boxed_arr.as_ref(), &[0u8; 3]);
}

#[cfg(feature = "alloc")]
#[test]
fn asref() {
let mut buffer: Zeroizing<Vec<u8>> = Default::default();
let _asmut: &mut [u8] = buffer.as_mut();
let _asref: &[u8] = buffer.as_ref();

let mut buffer: Zeroizing<Box<[u8]>> = Default::default();
let _asmut: &mut [u8] = buffer.as_mut();
let _asref: &[u8] = buffer.as_ref();
}
}

0 comments on commit 86455d5

Please sign in to comment.