use serde::{Deserialize, Serialize};
use super::error::CarbonFootprintClassError;
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct CarbonFootprintClass(String);
impl CarbonFootprintClass {
pub const MAX_LEN: usize = 8;
pub fn new(label: impl Into<String>) -> Result<Self, CarbonFootprintClassError> {
let label = label.into();
if label.trim().is_empty() {
return Err(CarbonFootprintClassError::Empty);
}
if label.chars().any(char::is_control) {
return Err(CarbonFootprintClassError::ControlCharacter(label));
}
let len = label.chars().count();
if len > Self::MAX_LEN {
return Err(CarbonFootprintClassError::TooLong {
label,
len,
max: Self::MAX_LEN,
});
}
Ok(Self(label))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for CarbonFootprintClass {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl TryFrom<String> for CarbonFootprintClass {
type Error = CarbonFootprintClassError;
fn try_from(label: String) -> Result<Self, Self::Error> {
Self::new(label)
}
}
impl From<CarbonFootprintClass> for String {
fn from(class: CarbonFootprintClass) -> Self {
class.0
}
}