use serde::{Deserialize, Serialize};
#[derive(Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Decimal(String);
impl Decimal {
pub fn new(s: impl Into<String>) -> Self {
Self(s.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn into_string(self) -> String {
self.0
}
pub fn to_f64(&self) -> Option<f64> {
self.0.parse().ok()
}
#[cfg(feature = "rust_decimal")]
#[cfg_attr(docsrs, doc(cfg(feature = "rust_decimal")))]
pub fn to_decimal(&self) -> std::result::Result<rust_decimal::Decimal, rust_decimal::Error> {
use std::str::FromStr;
rust_decimal::Decimal::from_str(&self.0)
}
}
impl std::fmt::Debug for Decimal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Debug::fmt(&self.0, f)
}
}
impl std::fmt::Display for Decimal {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl AsRef<str> for Decimal {
fn as_ref(&self) -> &str {
&self.0
}
}
impl From<String> for Decimal {
fn from(s: String) -> Self {
Self(s)
}
}
impl From<&str> for Decimal {
fn from(s: &str) -> Self {
Self(s.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn decimal_roundtrip_json() {
let d = Decimal::from("12.75");
let s = serde_json::to_string(&d).unwrap();
assert_eq!(s, "\"12.75\"");
let back: Decimal = serde_json::from_str(&s).unwrap();
assert_eq!(back, d);
}
#[test]
fn decimal_deserializes_preserves_format() {
let d: Decimal = serde_json::from_str("\"0.10\"").unwrap();
assert_eq!(d.as_str(), "0.10");
}
#[test]
fn decimal_debug_prints_as_string() {
let d = Decimal::from("12.75");
assert_eq!(format!("{d:?}"), "\"12.75\"");
assert_eq!(format!("{d}"), "12.75");
}
#[test]
fn decimal_to_f64_parses() {
assert_eq!(Decimal::from("12.75").to_f64(), Some(12.75));
}
#[test]
fn decimal_to_f64_surfaces_parse_error() {
assert_eq!(Decimal::from("not a decimal").to_f64(), None);
}
#[cfg(feature = "rust_decimal")]
#[test]
fn decimal_to_decimal_parses() {
use std::str::FromStr;
let d = Decimal::from("12.75").to_decimal().unwrap();
assert_eq!(d, rust_decimal::Decimal::from_str("12.75").unwrap());
}
#[cfg(feature = "rust_decimal")]
#[test]
fn decimal_to_decimal_preserves_scale() {
use std::str::FromStr;
let d = Decimal::from("0.10").to_decimal().unwrap();
assert_eq!(d, rust_decimal::Decimal::from_str("0.10").unwrap());
}
#[cfg(feature = "rust_decimal")]
#[test]
fn decimal_to_decimal_surfaces_parse_error() {
assert!(Decimal::from("not a decimal").to_decimal().is_err());
}
}