Skip to content

Commit

Permalink
feat: make Zeroizing transparent for cheap conversions
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 <[email protected]>
  • Loading branch information
npmccallum committed Apr 20, 2022
1 parent 3bd7698 commit 7662ee9
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions zeroize/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -580,6 +580,26 @@ where
}
}

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

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

impl<Z> Zeroize for Zeroizing<Z>
where
Z: Zeroize,
Expand Down Expand Up @@ -865,4 +885,15 @@ mod tests {
boxed_arr.zeroize();
assert_eq!(boxed_arr.as_ref(), &[0u8; 3]);
}

#[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 7662ee9

Please sign in to comment.