use std::fmt;
use std::str::FromStr;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::Error;
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct Decimal(String);
pub(crate) fn is_plain_decimal(s: &str) -> bool {
let digits = s.strip_prefix('-').unwrap_or(s);
let (whole, fraction) = match digits.split_once('.') {
Some((w, f)) => (w, Some(f)),
None => (digits, None),
};
!whole.is_empty()
&& whole.bytes().all(|b| b.is_ascii_digit())
&& fraction.is_none_or(|f| !f.is_empty() && f.bytes().all(|b| b.is_ascii_digit()))
}
impl Decimal {
pub fn new(value: impl Into<String>) -> Result<Self, Error> {
let value = value.into();
if is_plain_decimal(&value) {
Ok(Decimal(value))
} else {
Err(Error::invalid(format!(
"{value:?} is not a decimal such as \"150.00\""
)))
}
}
pub fn as_str(&self) -> &str {
&self.0
}
#[cfg(feature = "client")]
pub(crate) fn from_trusted(value: String) -> Self {
Decimal(value)
}
}
impl From<i64> for Decimal {
fn from(value: i64) -> Self {
Decimal(value.to_string())
}
}
impl From<u64> for Decimal {
fn from(value: u64) -> Self {
Decimal(value.to_string())
}
}
impl FromStr for Decimal {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Decimal::new(s)
}
}
impl TryFrom<&str> for Decimal {
type Error = Error;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Decimal::new(value)
}
}
impl TryFrom<String> for Decimal {
type Error = Error;
fn try_from(value: String) -> Result<Self, Self::Error> {
Decimal::new(value)
}
}
impl fmt::Display for Decimal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl AsRef<str> for Decimal {
fn as_ref(&self) -> &str {
&self.0
}
}
impl Serialize for Decimal {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.0)
}
}
impl<'de> Deserialize<'de> for Decimal {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let value = String::deserialize(deserializer)?;
if is_plain_decimal(&value) {
Ok(Decimal(value))
} else {
Err(serde::de::Error::custom(format!(
"money must be a plain decimal, got {value:?}"
)))
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepts_plain_decimals_only() {
for good in ["0", "150", "150.00", "-1.5", "0.000000000001"] {
assert!(Decimal::new(good).is_ok(), "{good}");
}
for bad in ["", "-", "1.", ".5", "1e3", "1,5", " 1", "+1", "NaN", "١٢"] {
assert!(Decimal::new(bad).is_err(), "{bad}");
}
}
#[test]
fn deserializes_strings_and_refuses_numbers() {
let d: Decimal = serde_json::from_str("\"9.832104\"").unwrap();
assert_eq!(d.as_str(), "9.832104");
assert!(serde_json::from_str::<Decimal>("9.832104").is_err());
assert!(serde_json::from_str::<Decimal>("\"150,00\"").is_err());
assert_eq!(serde_json::to_string(&d).unwrap(), "\"9.832104\"");
}
}