use crate::sodium::utils;
use std::ops::{Deref, DerefMut};
pub struct SecretBytes(Box<[u8]>);
impl SecretBytes {
pub fn new(mut bytes: Box<[u8]>) -> Self {
utils::mlock(&mut bytes).unwrap();
Self(bytes)
}
pub fn move_from(bytes: &mut [u8]) -> Self {
let result = bytes.to_vec().into();
utils::memzero(bytes);
result
}
pub fn allocate(len: usize) -> Self {
Self::new(vec![0; len].into_boxed_slice())
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn as_ptr(&self) -> *const u8 {
self.0.as_ptr()
}
}
impl Clone for SecretBytes {
fn clone(&self) -> Self {
Self::new(self.0.clone())
}
}
impl From<Vec<u8>> for SecretBytes {
fn from(bytes: Vec<u8>) -> Self {
Self(bytes.into_boxed_slice())
}
}
impl Deref for SecretBytes {
type Target = [u8];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for SecretBytes {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl Drop for SecretBytes {
fn drop(&mut self) {
utils::munlock(&mut self.0).unwrap();
}
}