use std::collections::HashMap;
#[derive(Debug, PartialEq, Eq)]
pub struct CryptConfig {
items: HashMap<String, CryptObject>
}
impl CryptConfig {
pub (crate) fn new() -> Self {
Self {
items: HashMap::new()
}
}
pub (crate) fn add_item(&mut self, identifier: String, value: CryptObject) {
self.items.insert(identifier, value);
}
pub fn get<S>(&self, ident: S) -> Option<&CryptObject>
where
S: Into<String>
{
self.items.get(&ident.into())
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum CryptObject {
Identifier(String),
String(String),
Body(CryptConfig),
Null,
}
impl CryptObject {
pub fn unwrap_identifier(&self) -> &String {
match self {
Self::Identifier(ident) => ident,
_ => panic!("Unwrapped a non-identifier crypt object!")
}
}
pub fn expect_identifier(&self, msg: &str) -> &String {
match self {
Self::Identifier(ident) => ident,
_ => panic!("{}", msg)
}
}
pub fn unwrap_identifier_or<'a>(&'a self, other: &'a String) -> &'a String {
match self {
Self::Identifier(ident) => ident,
_ => other
}
}
pub fn unwrap_string(&self) -> &String {
match self {
Self::String(s) => s,
_ => panic!("Unwrapped a non-identifier crypt object!")
}
}
pub fn expect_string(&self, msg: &str) -> &String {
match self {
Self::String(s) => s,
_ => panic!("{}", msg)
}
}
pub fn unwrap_string_or<'a>(&'a self, other: &'a String) -> &'a String {
match self {
Self::String(s) => s,
_ => other
}
}
pub fn unwrap_nested_config(&self) -> &CryptConfig {
match self {
Self::Body(b) => b,
_ => panic!("Unwrapped a non-identifier crypt object!")
}
}
pub fn expect_nested_config(&self, msg: &str) -> &CryptConfig {
match self {
Self::Body(b) => b,
_ => panic!("{}", msg)
}
}
}
impl<'a> TryInto<&'a String> for &'a CryptObject {
type Error = CryptConversionError;
fn try_into(self) -> Result<&'a String, Self::Error> {
match self {
CryptObject::String(v) => Ok(v),
CryptObject::Identifier(id) => Ok(id),
_ => Err(CryptConversionError::CannotConvertToString)
}
}
}
impl<'a> TryInto<&'a CryptConfig> for &'a CryptObject {
type Error = CryptConversionError;
fn try_into(self) -> Result<&'a CryptConfig, Self::Error> {
match self {
CryptObject::Body(b) => Ok(b),
_ => Err(CryptConversionError::CannotConvertToNestedConfig)
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum CryptConversionError {
CannotConvertToString,
CannotConvertToNestedConfig,
CannotConvertToIdentifier,
}
impl std::fmt::Display for CryptConversionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::CannotConvertToString => write!(f, "Crypt object cannot be converted to string!"),
Self::CannotConvertToIdentifier => write!(f, "Crypt object cannot be converted to an identifier!"),
Self::CannotConvertToNestedConfig => write!(f, "Crypt object cannot be converted to a nested config!"),
}
}
}