use core::fmt;
use core::str::FromStr;
use rust_decimal::Decimal;
use rust_decimal::prelude::ToPrimitive;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use super::validate::{Validate, Validator, ViolationCode};
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Number(Decimal);
impl Number {
pub const ZERO: Self = Self(Decimal::ZERO);
pub const ONE: Self = Self(Decimal::ONE);
#[must_use]
pub const fn new(value: Decimal) -> Self {
Self(value)
}
#[must_use]
pub const fn get(self) -> Decimal {
self.0
}
#[must_use]
pub fn scale(self) -> u32 {
self.0.scale()
}
#[must_use]
pub fn round_dp(self, dp: u32) -> Self {
Self(self.0.round_dp_with_strategy(dp, rust_decimal::RoundingStrategy::MidpointAwayFromZero))
}
#[must_use]
pub fn json_round_trips(self) -> bool {
if self.0.is_integer() && self.0.to_i64().is_some() {
return true;
}
self.0.to_f64().and_then(decimal_from_f64).is_some_and(|d| d == self.0.normalize())
}
#[must_use]
pub fn is_zero(self) -> bool {
self.0.is_zero()
}
#[must_use]
pub fn is_negative(self) -> bool {
self.0.is_sign_negative() && !self.0.is_zero()
}
#[must_use]
pub fn is_integer(self) -> bool {
self.0.is_integer()
}
pub(crate) fn validate_range(self, v: &mut Validator, min: i64, max: i64) {
let (lo, hi) = (Decimal::from(min), Decimal::from(max));
if self.0 < lo || self.0 > hi {
v.report(
ViolationCode::OutOfRange,
format!("{} is outside the allowed range {min}..={max}", self.0),
);
}
}
pub(crate) fn validate_range_with_defect(self, v: &mut Validator, min: i64, max: i64, defect: &str) {
let (lo, hi) = (Decimal::from(min), Decimal::from(max));
if self.0 < lo || self.0 > hi {
let note = super::SpecDefect::get(defect).map_or_else(String::new, |d| format!("; {}", d.note()));
v.report(
ViolationCode::OutOfRange,
format!("{} is outside the allowed range {min}..={max}{note}", self.0),
);
}
}
}
fn decimal_from_f64(f: f64) -> Option<Decimal> {
Decimal::from_str(&format!("{f}")).ok().map(|d| d.normalize())
}
impl Validate for Number {
fn validate_in(&self, v: &mut Validator) {
if !self.json_round_trips() {
v.report(
ViolationCode::Imprecise,
format!("{} carries more significant digits than a JSON number round-trip preserves", self.0),
);
}
}
}
impl fmt::Display for Number {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
impl fmt::Debug for Number {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Number({})", self.0)
}
}
impl From<Decimal> for Number {
fn from(value: Decimal) -> Self {
Self(value)
}
}
impl From<Number> for Decimal {
fn from(value: Number) -> Self {
value.0
}
}
macro_rules! from_integer {
($($t:ty),*) => {
$(impl From<$t> for Number {
fn from(value: $t) -> Self { Self(Decimal::from(value)) }
})*
};
}
from_integer!(i8, i16, i32, i64, u8, u16, u32, u64);
impl FromStr for Number {
type Err = rust_decimal::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Decimal::from_str(s).or_else(|_| Decimal::from_scientific(s)).map(Self)
}
}
impl core::ops::Add for Number {
type Output = Self;
fn add(self, rhs: Self) -> Self {
Self(self.0 + rhs.0)
}
}
impl core::ops::Sub for Number {
type Output = Self;
fn sub(self, rhs: Self) -> Self {
Self(self.0 - rhs.0)
}
}
impl core::ops::Mul for Number {
type Output = Self;
fn mul(self, rhs: Self) -> Self {
Self(self.0 * rhs.0)
}
}
impl core::iter::Sum for Number {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
Self(iter.map(|n| n.0).sum())
}
}
impl Serialize for Number {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
if self.0.is_integer()
&& let Some(i) = self.0.to_i64()
{
return s.serialize_i64(i);
}
match self.0.to_f64() {
Some(f) => s.serialize_f64(f),
None => {
Err(serde::ser::Error::custom(format!("{} cannot be represented as a JSON number", self.0)))
}
}
}
}
impl<'de> Deserialize<'de> for Number {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
struct V;
impl serde::de::Visitor<'_> for V {
type Value = Number;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a JSON number, or a string holding one")
}
fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<Number, E> {
Ok(Number(Decimal::from(v)))
}
fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<Number, E> {
Ok(Number(Decimal::from(v)))
}
fn visit_f64<E: serde::de::Error>(self, v: f64) -> Result<Number, E> {
decimal_from_f64(v)
.map(Number)
.ok_or_else(|| E::custom(format!("{v} is not a finite JSON number")))
}
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Number, E> {
v.parse().map_err(|_| E::custom(format!("{v:?} is not a number")))
}
}
d.deserialize_any(V)
}
}
#[cfg(feature = "schema")]
impl schemars::JsonSchema for Number {
fn schema_name() -> std::borrow::Cow<'static, str> {
"Number".into()
}
fn json_schema(_g: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({ "type": "number" })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn decimals_survive_the_json_boundary() {
for text in ["0.1", "0.25", "10.1", "22", "0", "-3.5", "1234.5678", "99999.99"] {
let n: Number = text.parse().unwrap();
let json = serde_json::to_string(&n).unwrap();
let back: Number = serde_json::from_str(&json).unwrap();
assert_eq!(n.get().normalize(), back.get().normalize(), "{text} did not round-trip ({json})");
}
}
#[test]
fn the_cdr_energy_identity_is_exact() {
let end: Number = "10.1".parse().unwrap();
let start: Number = "0.1".parse().unwrap();
let consumed: Number = "10.0".parse().unwrap();
assert_eq!(end - start, consumed);
}
#[test]
fn integral_values_are_written_as_json_integers() {
let n: Number = "22".parse().unwrap();
assert_eq!(serde_json::to_string(&n).unwrap(), "22");
let n: Number = "22.0".parse().unwrap();
assert_eq!(serde_json::to_string(&n).unwrap(), "22");
}
#[test]
fn a_number_sent_as_a_string_is_accepted() {
let n: Number = serde_json::from_str(r#""0.25""#).unwrap();
assert_eq!(n.to_string(), "0.25");
assert_eq!(serde_json::to_string(&n).unwrap(), "0.25");
}
#[test]
fn imprecise_values_are_reported_not_silently_rounded() {
let n: Number = "1.2345678901234567890123".parse().unwrap();
assert!(!n.json_round_trips());
assert_eq!(n.validate().unwrap_err().as_slice()[0].code, ViolationCode::Imprecise);
}
}