1use core::fmt;
4use core::str::FromStr;
5
6use rust_decimal::Decimal;
7use rust_decimal::prelude::ToPrimitive;
8use serde::{Deserialize, Deserializer, Serialize, Serializer};
9
10use super::validate::{Validate, Validator, ViolationCode};
11
12#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
54pub struct Number(Decimal);
55
56impl Number {
57 pub const ZERO: Self = Self(Decimal::ZERO);
59 pub const ONE: Self = Self(Decimal::ONE);
61
62 #[must_use]
64 pub const fn new(value: Decimal) -> Self {
65 Self(value)
66 }
67
68 #[must_use]
70 pub const fn get(self) -> Decimal {
71 self.0
72 }
73
74 #[must_use]
76 pub fn scale(self) -> u32 {
77 self.0.scale()
78 }
79
80 #[must_use]
82 pub fn round_dp(self, dp: u32) -> Self {
83 Self(self.0.round_dp_with_strategy(dp, rust_decimal::RoundingStrategy::MidpointAwayFromZero))
84 }
85
86 #[must_use]
91 pub fn json_round_trips(self) -> bool {
92 if self.0.is_integer() && self.0.to_i64().is_some() {
93 return true;
94 }
95 self.0.to_f64().and_then(decimal_from_f64).is_some_and(|d| d == self.0.normalize())
96 }
97
98 #[must_use]
100 pub fn is_zero(self) -> bool {
101 self.0.is_zero()
102 }
103
104 #[must_use]
106 pub fn is_negative(self) -> bool {
107 self.0.is_sign_negative() && !self.0.is_zero()
108 }
109
110 #[must_use]
115 pub fn is_integer(self) -> bool {
116 self.0.is_integer()
117 }
118
119 pub(crate) fn validate_range(self, v: &mut Validator, min: i64, max: i64) {
121 let (lo, hi) = (Decimal::from(min), Decimal::from(max));
122 if self.0 < lo || self.0 > hi {
123 v.report(
124 ViolationCode::OutOfRange,
125 format!("{} is outside the allowed range {min}..={max}", self.0),
126 );
127 }
128 }
129
130 pub(crate) fn validate_range_with_defect(self, v: &mut Validator, min: i64, max: i64, defect: &str) {
137 let (lo, hi) = (Decimal::from(min), Decimal::from(max));
138 if self.0 < lo || self.0 > hi {
139 let note = super::SpecDefect::get(defect).map_or_else(String::new, |d| format!("; {}", d.note()));
140 v.report(
141 ViolationCode::OutOfRange,
142 format!("{} is outside the allowed range {min}..={max}{note}", self.0),
143 );
144 }
145 }
146}
147
148fn decimal_from_f64(f: f64) -> Option<Decimal> {
151 Decimal::from_str(&format!("{f}")).ok().map(|d| d.normalize())
152}
153
154impl Validate for Number {
155 fn validate_in(&self, v: &mut Validator) {
156 if !self.json_round_trips() {
157 v.report(
158 ViolationCode::Imprecise,
159 format!("{} carries more significant digits than a JSON number round-trip preserves", self.0),
160 );
161 }
162 }
163}
164
165impl fmt::Display for Number {
166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167 fmt::Display::fmt(&self.0, f)
168 }
169}
170
171impl fmt::Debug for Number {
172 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
173 write!(f, "Number({})", self.0)
174 }
175}
176
177impl From<Decimal> for Number {
178 fn from(value: Decimal) -> Self {
179 Self(value)
180 }
181}
182
183impl From<Number> for Decimal {
184 fn from(value: Number) -> Self {
185 value.0
186 }
187}
188
189macro_rules! from_integer {
190 ($($t:ty),*) => {
191 $(impl From<$t> for Number {
192 fn from(value: $t) -> Self { Self(Decimal::from(value)) }
193 })*
194 };
195}
196from_integer!(i8, i16, i32, i64, u8, u16, u32, u64);
197
198impl FromStr for Number {
199 type Err = rust_decimal::Error;
200 fn from_str(s: &str) -> Result<Self, Self::Err> {
201 Decimal::from_str(s).or_else(|_| Decimal::from_scientific(s)).map(Self)
202 }
203}
204
205impl core::ops::Add for Number {
206 type Output = Self;
207 fn add(self, rhs: Self) -> Self {
208 Self(self.0 + rhs.0)
209 }
210}
211
212impl core::ops::Sub for Number {
213 type Output = Self;
214 fn sub(self, rhs: Self) -> Self {
215 Self(self.0 - rhs.0)
216 }
217}
218
219impl core::ops::Mul for Number {
220 type Output = Self;
221 fn mul(self, rhs: Self) -> Self {
222 Self(self.0 * rhs.0)
223 }
224}
225
226impl core::iter::Sum for Number {
227 fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
228 Self(iter.map(|n| n.0).sum())
229 }
230}
231
232impl Serialize for Number {
233 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
234 if self.0.is_integer()
239 && let Some(i) = self.0.to_i64()
240 {
241 return s.serialize_i64(i);
242 }
243 match self.0.to_f64() {
244 Some(f) => s.serialize_f64(f),
245 None => {
246 Err(serde::ser::Error::custom(format!("{} cannot be represented as a JSON number", self.0)))
247 }
248 }
249 }
250}
251
252impl<'de> Deserialize<'de> for Number {
253 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
254 struct V;
255 impl serde::de::Visitor<'_> for V {
256 type Value = Number;
257 fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258 f.write_str("a JSON number, or a string holding one")
259 }
260 fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<Number, E> {
261 Ok(Number(Decimal::from(v)))
262 }
263 fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<Number, E> {
264 Ok(Number(Decimal::from(v)))
265 }
266 fn visit_f64<E: serde::de::Error>(self, v: f64) -> Result<Number, E> {
267 decimal_from_f64(v)
270 .map(Number)
271 .ok_or_else(|| E::custom(format!("{v} is not a finite JSON number")))
272 }
273 fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Number, E> {
274 v.parse().map_err(|_| E::custom(format!("{v:?} is not a number")))
275 }
276 }
277 d.deserialize_any(V)
278 }
279}
280
281#[cfg(feature = "schema")]
282impl schemars::JsonSchema for Number {
283 fn schema_name() -> std::borrow::Cow<'static, str> {
284 "Number".into()
285 }
286 fn json_schema(_g: &mut schemars::SchemaGenerator) -> schemars::Schema {
287 schemars::json_schema!({ "type": "number" })
288 }
289}
290
291#[cfg(test)]
292mod tests {
293 use super::*;
294
295 #[test]
296 fn decimals_survive_the_json_boundary() {
297 for text in ["0.1", "0.25", "10.1", "22", "0", "-3.5", "1234.5678", "99999.99"] {
298 let n: Number = text.parse().unwrap();
299 let json = serde_json::to_string(&n).unwrap();
300 let back: Number = serde_json::from_str(&json).unwrap();
301 assert_eq!(n.get().normalize(), back.get().normalize(), "{text} did not round-trip ({json})");
302 }
303 }
304
305 #[test]
306 fn the_cdr_energy_identity_is_exact() {
307 let end: Number = "10.1".parse().unwrap();
309 let start: Number = "0.1".parse().unwrap();
310 let consumed: Number = "10.0".parse().unwrap();
311 assert_eq!(end - start, consumed);
312 }
313
314 #[test]
315 fn integral_values_are_written_as_json_integers() {
316 let n: Number = "22".parse().unwrap();
317 assert_eq!(serde_json::to_string(&n).unwrap(), "22");
318 let n: Number = "22.0".parse().unwrap();
319 assert_eq!(serde_json::to_string(&n).unwrap(), "22");
320 }
321
322 #[test]
323 fn a_number_sent_as_a_string_is_accepted() {
324 let n: Number = serde_json::from_str(r#""0.25""#).unwrap();
325 assert_eq!(n.to_string(), "0.25");
326 assert_eq!(serde_json::to_string(&n).unwrap(), "0.25");
327 }
328
329 #[test]
330 fn imprecise_values_are_reported_not_silently_rounded() {
331 let n: Number = "1.2345678901234567890123".parse().unwrap();
332 assert!(!n.json_round_trips());
333 assert_eq!(n.validate().unwrap_err().as_slice()[0].code, ViolationCode::Imprecise);
334 }
335}