use core::array::TryFromSliceError;
use zeroize::Zeroize;
use crate::sealed::Sealed;
pub const KEY_SIZE: usize = KEY_SIZE_U32 as usize;
pub const KEY_SIZE_U32: u32 = 32;
pub trait GenericKey : Sealed {
#[doc(hidden)]
fn ptr(&self) -> *const u8;
}
#[repr(transparent)]
#[derive(Clone)]
pub struct Key {
inner: [u8; KEY_SIZE]
}
arb_key! { struct Key::new([u8; 32]) }
impl Key {
pub const fn new(inner: [u8; KEY_SIZE]) -> Self {
Self { inner }
}
pub const fn as_ref(&self) -> KeyRef {
KeyRef::new(&self.inner)
}
}
impl Zeroize for Key {
#[inline]
fn zeroize(&mut self) {
self.inner.zeroize();
}
}
opaque_dbg! { Key }
impl Sealed for Key {}
impl GenericKey for Key {
#[doc(hidden)]
#[inline]
fn ptr(&self) -> *const u8 {
self.inner.as_ptr()
}
}
impl From<[u8; KEY_SIZE]> for Key {
#[inline]
fn from(value: [u8; KEY_SIZE]) -> Self {
Self::new(value, )
}
}
impl Drop for Key {
#[inline]
fn drop(&mut self) {
self.zeroize();
}
}
#[repr(transparent)]
pub struct KeyRef<'r> {
inner: &'r [u8; KEY_SIZE]
}
impl<'r> KeyRef<'r> {
pub const fn new(inner: &'r [u8; KEY_SIZE]) -> Self {
Self { inner }
}
pub const fn copy(&self) -> Key {
Key::new(*self.inner, )
}
}
opaque_dbg! { KeyRef<'r> }
impl<'r> Sealed for KeyRef<'r> {}
impl<'r> GenericKey for KeyRef<'r> {
#[doc(hidden)]
#[inline]
fn ptr(&self) -> *const u8 {
self.inner.as_ptr()
}
}
impl<'r> From<&'r [u8; KEY_SIZE]> for KeyRef<'r> {
#[inline]
fn from(value: &'r [u8; KEY_SIZE]) -> Self {
Self::new(value)
}
}
impl<'r> TryFrom<&'r [u8]> for KeyRef<'r> {
type Error = TryFromSliceError;
#[inline]
fn try_from(value: &'r [u8]) -> Result<Self, Self::Error> {
value.try_into().map(Self::new)
}
}