use std::fmt::{Display, Formatter};
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct Pointer(Vec<u8>);
#[derive(Debug)]
pub enum PointerError {
NonAscii,
NonHex,
TooLong,
}
impl Pointer {
pub fn new(ascii_bytes: Vec<u8>) -> Result<Pointer, PointerError> {
let ascii_bytes = if ascii_bytes.starts_with(b"0x") {
ascii_bytes[2..].to_vec()
} else {
ascii_bytes
};
if ascii_bytes.len() > 255 {
return Err(PointerError::TooLong);
}
let pointer_str = std::str::from_utf8(&ascii_bytes).or(Err(PointerError::NonAscii))?;
if pointer_str.chars().all(|c| char::is_ascii_hexdigit(&c)) {
Ok(Pointer(ascii_bytes))
} else {
Err(PointerError::NonHex)
}
}
pub fn null() -> Pointer {
Pointer(vec![b'0'])
}
pub fn is_null(&self) -> bool {
self.0.len() == 1 && self.0[0] == b'0'
}
}
impl Display for Pointer {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let pointer_str = std::str::from_utf8(&self.0).expect("Invalid pointer: non-UTF-8");
write!(f, "0x{}", pointer_str)
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum Compression {
Off,
Zlib,
Zstd,
}
impl Compression {
pub fn to_str(&self) -> &'static str {
match self {
Compression::Off => "off",
Compression::Zlib => "zlib",
Compression::Zstd => "zstd",
}
}
pub fn parse(compression: &str) -> Option<Self> {
match compression {
"off" => Some(Compression::Off),
"zlib" => Some(Compression::Zlib),
"zstd" => Some(Compression::Zstd),
_ => None,
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum PasswordHashAlgo {
Plain,
Sha256,
Sha512,
Pbkdf2Sha256,
Pbkdf2Sha512,
}
impl PasswordHashAlgo {
pub fn to_str(&self) -> &'static str {
match self {
PasswordHashAlgo::Plain => "plain",
PasswordHashAlgo::Sha256 => "sha256",
PasswordHashAlgo::Sha512 => "sha512",
PasswordHashAlgo::Pbkdf2Sha256 => "pbkdf2+sha256",
PasswordHashAlgo::Pbkdf2Sha512 => "pbkdf2+sha512",
}
}
pub fn parse(algo: &str) -> Option<PasswordHashAlgo> {
match algo {
"plain" => Some(PasswordHashAlgo::Plain),
"sha256" => Some(PasswordHashAlgo::Sha256),
"sha512" => Some(PasswordHashAlgo::Sha512),
"pbkdf2+sha256" => Some(PasswordHashAlgo::Pbkdf2Sha256),
"pbkdf2+sha512" => Some(PasswordHashAlgo::Pbkdf2Sha512),
_ => None,
}
}
}