use std::fmt;
use std::str::FromStr;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct NumberSeparators {
decimal: char,
group: char,
}
impl NumberSeparators {
pub fn new(decimal: char, group: char) -> Result<Self, NumberSeparatorsError> {
if decimal == group || decimal.is_ascii_digit() || group.is_ascii_digit() {
return Err(NumberSeparatorsError(format!("{decimal}{group}")));
}
Ok(Self { decimal, group })
}
#[must_use]
pub const fn decimal(self) -> char {
self.decimal
}
#[must_use]
pub const fn group(self) -> char {
self.group
}
}
impl FromStr for NumberSeparators {
type Err = NumberSeparatorsError;
fn from_str(text: &str) -> Result<Self, NumberSeparatorsError> {
let mut chars = text.chars();
match (chars.next(), chars.next(), chars.next()) {
(Some(decimal), Some(group), None) => Self::new(decimal, group),
_ => Err(NumberSeparatorsError(text.to_owned())),
}
}
}
impl fmt::Display for NumberSeparators {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}{}", self.decimal, self.group)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct NumberSeparatorsError(pub String);
impl fmt::Display for NumberSeparatorsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{:?} are no number separators: write the decimal separator, then another group \
separator, neither a digit, such as .,",
self.0
)
}
}
impl std::error::Error for NumberSeparatorsError {}
impl serde::Serialize for NumberSeparators {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> serde::Deserialize<'de> for NumberSeparators {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let text = String::deserialize(deserializer)?;
text.parse().map_err(serde::de::Error::custom)
}
}
#[cfg(feature = "development")]
impl schemars::JsonSchema for NumberSeparators {
fn schema_name() -> std::borrow::Cow<'static, str> {
"NumberSeparators".into()
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"description": "The decimal separator, then another group separator, neither a digit, such as \".,\".",
"type": "string",
"minLength": 2,
"maxLength": 2
})
}
}