use serde_with::{DeserializeFromStr, SerializeDisplay};
use std::convert::From;
use std::fmt;
pub const MAX_LENGTH_BYTES: usize = 32;
#[derive(Debug, Clone, PartialEq, SerializeDisplay, DeserializeFromStr)]
pub struct Secret([u8; 32]);
impl Secret {
pub fn as_bytes(&self) -> &[u8; 32] {
&self.0
}
}
impl fmt::Display for Secret {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let s = String::from_utf8_lossy(&self.0);
write!(f, "{}", s)
}
}
use crate::kdf;
impl From<kdf::Key> for Secret {
fn from(key: kdf::Key) -> Self {
let bytes: [u8; 32] = key.into();
Secret(bytes)
}
}
impl From<u64> for Secret {
fn from(num: u64) -> Self {
let bytes = num.to_le_bytes();
let mut arr = [0u8; 32];
arr[..8].copy_from_slice(&bytes[..8]);
Secret(arr)
}
}
use std::str::FromStr;
impl FromStr for Secret {
type Err = SecretParserError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.len() > MAX_LENGTH_BYTES {
Err(SecretParserError::StringTooLongError)
} else {
let mut arr = [0u8; 32];
arr[..s.len()].copy_from_slice(s.as_bytes());
Ok(Secret(arr))
}
}
}
impl From<Secret> for [u8; 32] {
fn from(item: Secret) -> Self {
item.0
}
}
#[derive(Debug, thiserror::Error)]
pub enum SecretParserError {
#[error("The given string has more than the max allowed bytes of {MAX_LENGTH_BYTES}")]
StringTooLongError,
}