use core::ops::{Deref, DerefMut};
use core::ptr;
use core::sync::atomic;
use super::error::Error;
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub struct Seed([u8; Seed::BYTES]);
impl From<[u8; 32]> for Seed {
fn from(seed: [u8; 32]) -> Self {
Seed(seed)
}
}
impl Seed {
pub const BYTES: usize = 32;
pub fn new(seed: [u8; Seed::BYTES]) -> Self {
Seed(seed)
}
pub fn from_slice(seed: &[u8]) -> Result<Self, Error> {
let mut seed_ = [0u8; Seed::BYTES];
if seed.len() != seed_.len() {
return Err(Error::InvalidSeed);
}
seed_.copy_from_slice(seed);
Ok(Seed::new(seed_))
}
pub fn wipe(self) {
Mem::wipe(self.0)
}
}
#[cfg(feature = "random")]
impl Default for Seed {
fn default() -> Self {
let mut seed = [0u8; Seed::BYTES];
getrandom::getrandom(&mut seed).expect("RNG failure");
Seed(seed)
}
}
#[cfg(feature = "random")]
impl Seed {
pub fn generate() -> Self {
Seed::default()
}
}
impl Deref for Seed {
type Target = [u8; Seed::BYTES];
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for Seed {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
pub(crate) struct Mem;
impl Mem {
#[inline]
pub fn wipe<T: Default>(mut x: impl AsMut<[T]>) {
let x = x.as_mut();
for i in 0..x.len() {
unsafe {
ptr::write_volatile(x.as_mut_ptr().add(i), T::default());
}
}
atomic::compiler_fence(atomic::Ordering::SeqCst);
atomic::fence(atomic::Ordering::SeqCst);
}
}