use std::fmt;
use std::str::FromStr;
use serde::{Deserialize, Deserializer, Serialize};
#[derive(Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(transparent)]
pub struct Decimal(String);
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("not a decimal string: {0:?}")]
pub struct NotADecimal(pub String);
fn is_decimal(text: &str) -> bool {
let digits = text.strip_prefix('-').unwrap_or(text);
let (whole, fraction) = match digits.split_once('.') {
Some((whole, fraction)) => (whole, Some(fraction)),
None => (digits, None),
};
let all_digits = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit());
all_digits(whole) && fraction.is_none_or(all_digits)
}
impl Decimal {
pub fn as_str(&self) -> &str {
&self.0
}
pub fn to_f64(&self) -> f64 {
self.0.parse().unwrap_or(f64::NAN)
}
pub fn to_i64(&self) -> Option<i64> {
self.0.parse().ok()
}
pub fn is_negative(&self) -> bool {
self.0.starts_with('-') && self.0.bytes().any(|b| (b'1'..=b'9').contains(&b))
}
#[cfg(feature = "rust_decimal")]
pub fn to_decimal(&self) -> Result<rust_decimal::Decimal, rust_decimal::Error> {
self.0.parse()
}
}
impl fmt::Debug for Decimal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Decimal({})", self.0)
}
}
impl fmt::Display for Decimal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl FromStr for Decimal {
type Err = NotADecimal;
fn from_str(text: &str) -> Result<Self, Self::Err> {
if is_decimal(text) {
Ok(Decimal(text.to_string()))
} else {
Err(NotADecimal(text.to_string()))
}
}
}
impl TryFrom<String> for Decimal {
type Error = NotADecimal;
fn try_from(text: String) -> Result<Self, Self::Error> {
if is_decimal(&text) {
Ok(Decimal(text))
} else {
Err(NotADecimal(text))
}
}
}
impl From<i64> for Decimal {
fn from(value: i64) -> Self {
Decimal(value.to_string())
}
}
impl AsRef<str> for Decimal {
fn as_ref(&self) -> &str {
&self.0
}
}
impl<'de> Deserialize<'de> for Decimal {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let text = String::deserialize(deserializer)?;
Decimal::try_from(text).map_err(serde::de::Error::custom)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn reads_the_wire_and_refuses_a_float() {
for text in ["416161000000", "-58000000", "39.75", "0.3018", "1.000", "0"] {
let value: Decimal = serde_json::from_str(&format!("\"{text}\"")).unwrap();
assert_eq!(value.as_str(), text);
assert_eq!(value.to_string(), text);
}
for text in ["\"1e5\"", "\"\"", "\"1.\"", "\".5\"", "42", "null"] {
assert!(serde_json::from_str::<Decimal>(text).is_err(), "{text}");
}
assert_eq!("39.75".parse::<Decimal>().unwrap().to_f64(), 39.75);
assert_eq!(
"-58000000".parse::<Decimal>().unwrap().to_i64(),
Some(-58_000_000)
);
assert!("-0.5".parse::<Decimal>().unwrap().is_negative());
assert!(!"-0".parse::<Decimal>().unwrap().is_negative());
assert_eq!(format!("{:?}", Decimal::from(7)), "Decimal(7)");
}
#[cfg(feature = "rust_decimal")]
#[test]
fn converts_to_rust_decimal() {
let value: Decimal = "0.3018".parse().unwrap();
assert_eq!(value.to_decimal().unwrap().to_string(), "0.3018");
}
}