#![allow(
clippy::cast_possible_truncation,
clippy::cast_possible_wrap,
clippy::cast_sign_loss
)]
use core::cmp::Ordering;
use core::fmt;
use core::hash::{Hash, Hasher};
use core::ops::{Add, AddAssign, Div, Mul, Neg, Sub, SubAssign};
use core::str::FromStr;
use serde::{Deserialize, Serialize};
use crate::validate::{Validate, ValidationPath, Violations};
#[derive(Clone, Copy, Default)]
pub struct Decimal {
mantissa: i64,
scale: u8,
}
const POW10_U64: [u64; 19] = [
1,
10,
100,
1_000,
10_000,
100_000,
1_000_000,
10_000_000,
100_000_000,
1_000_000_000,
10_000_000_000,
100_000_000_000,
1_000_000_000_000,
10_000_000_000_000,
100_000_000_000_000,
1_000_000_000_000_000,
10_000_000_000_000_000,
100_000_000_000_000_000,
1_000_000_000_000_000_000,
];
const fn pow10_i128(exp: u32) -> i128 {
let mut result: i128 = 1;
let mut left = exp;
while left > 0 {
result *= 10;
left -= 1;
}
result
}
const ACCUMULATE_LIMIT: u128 = u128::MAX / 16;
impl Decimal {
pub const ZERO: Self = Self {
mantissa: 0,
scale: 0,
};
pub const ONE: Self = Self {
mantissa: 1,
scale: 0,
};
pub const MAX_SCALE: u8 = 18;
#[must_use]
pub const fn new(mantissa: i64, scale: u8) -> Self {
assert!(
scale <= Self::MAX_SCALE,
"a Decimal scale may not exceed Decimal::MAX_SCALE"
);
Self { mantissa, scale }
}
#[must_use]
pub const fn try_new(mantissa: i64, scale: u8) -> Option<Self> {
if scale > Self::MAX_SCALE {
return None;
}
Some(Self { mantissa, scale })
}
#[must_use]
pub const fn from_i64(value: i64) -> Self {
Self {
mantissa: value,
scale: 0,
}
}
#[must_use]
pub const fn mantissa(self) -> i64 {
self.mantissa
}
#[must_use]
pub const fn scale(self) -> u8 {
self.scale
}
#[must_use]
pub const fn is_zero(self) -> bool {
self.mantissa == 0
}
#[must_use]
pub const fn signum(self) -> i32 {
if self.mantissa < 0 {
-1
} else if self.mantissa > 0 {
1
} else {
0
}
}
#[must_use]
pub const fn eq_exact(self, other: Self) -> bool {
self.mantissa == other.mantissa && self.scale == other.scale
}
#[must_use]
pub const fn normalized(mut self) -> Self {
while self.scale > 0 && self.mantissa % 10 == 0 {
self.mantissa /= 10;
self.scale -= 1;
}
if self.mantissa == 0 {
self.scale = 0;
}
self
}
#[must_use]
pub const fn rescale(self, scale: u8) -> Option<Self> {
if scale > Self::MAX_SCALE {
return None;
}
if scale == self.scale {
return Some(self);
}
if scale > self.scale {
let factor = POW10_U64[(scale - self.scale) as usize];
let Some(mantissa) = self.mantissa.checked_mul(factor as i64) else {
return None;
};
return Some(Self { mantissa, scale });
}
let factor = POW10_U64[(self.scale - scale) as usize] as i64;
if self.mantissa % factor != 0 {
return None;
}
Some(Self {
mantissa: self.mantissa / factor,
scale,
})
}
#[must_use]
pub const fn round_to(self, scale: u8) -> Option<Self> {
if scale >= self.scale {
return self.rescale(scale);
}
let drop = (self.scale - scale) as u32;
let negative = self.mantissa < 0;
let magnitude = self.mantissa.unsigned_abs() as u128;
let rounded = round_off(magnitude, drop, false);
if rounded > i64::MAX as u128 {
return None;
}
let mantissa = rounded as i64;
Some(Self {
mantissa: if negative { -mantissa } else { mantissa },
scale,
})
}
#[must_use]
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
let scale = if self.scale > rhs.scale {
self.scale
} else {
rhs.scale
};
let (Some(a), Some(b)) = (self.to_i128_at(scale), rhs.to_i128_at(scale)) else {
return None;
};
narrow(a + b, scale)
}
#[must_use]
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
let scale = if self.scale > rhs.scale {
self.scale
} else {
rhs.scale
};
let (Some(a), Some(b)) = (self.to_i128_at(scale), rhs.to_i128_at(scale)) else {
return None;
};
narrow(a - b, scale)
}
#[must_use]
pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
let scale = self.scale as u32 + rhs.scale as u32;
let product = self.mantissa as i128 * rhs.mantissa as i128;
if scale <= Self::MAX_SCALE as u32 {
return narrow(product, scale as u8);
}
let drop = scale - Self::MAX_SCALE as u32;
let negative = product < 0;
let rounded = round_off(product.unsigned_abs(), drop, false);
if rounded > i64::MAX as u128 {
return None;
}
let mantissa = rounded as i64;
Some(Self {
mantissa: if negative { -mantissa } else { mantissa },
scale: Self::MAX_SCALE,
})
}
#[must_use]
pub const fn checked_div(self, rhs: Self, scale: u8) -> Option<Self> {
if rhs.mantissa == 0 || scale > Self::MAX_SCALE {
return None;
}
let shift = scale as i32 + rhs.scale as i32 - self.scale as i32;
let negative = (self.mantissa < 0) != (rhs.mantissa < 0);
let mut numerator = self.mantissa.unsigned_abs() as u128;
let denominator = rhs.mantissa.unsigned_abs() as u128;
let shift = shift + 1;
let mut extra_drop = 0u32;
if shift >= 0 {
let up = shift as u32;
if up > 38 {
return None;
}
let factor = pow10_i128(up) as u128;
let Some(scaled) = numerator.checked_mul(factor) else {
return None;
};
numerator = scaled;
} else {
let down = (-shift) as u32;
if down > 38 {
return None;
}
extra_drop = down;
}
let quotient = if extra_drop > 0 {
let factor = pow10_i128(extra_drop) as u128;
let Some(scaled) = denominator.checked_mul(factor) else {
return None;
};
numerator / scaled
} else {
numerator / denominator
};
let remainder_is_zero = if extra_drop > 0 {
let factor = pow10_i128(extra_drop) as u128;
match denominator.checked_mul(factor) {
Some(scaled) => numerator.is_multiple_of(scaled),
None => return None,
}
} else {
numerator.is_multiple_of(denominator)
};
let rounded = round_off(quotient, 1, !remainder_is_zero);
if rounded > i64::MAX as u128 {
return None;
}
let mantissa = rounded as i64;
Some(Self {
mantissa: if negative { -mantissa } else { mantissa },
scale,
})
}
#[must_use]
pub const fn checked_pow10(self, exp: i32) -> Option<Self> {
if exp == 0 {
return Some(self);
}
if exp > 40 || exp < -40 {
return if self.mantissa == 0 {
Some(Self::ZERO)
} else {
None
};
}
if exp < 0 {
let want = self.scale as i32 - exp;
if want <= Self::MAX_SCALE as i32 {
return Some(Self {
mantissa: self.mantissa,
scale: want as u8,
});
}
let surplus = want - Self::MAX_SCALE as i32;
let surplus = surplus as u32;
if surplus > 18 {
return None;
}
let factor = POW10_U64[surplus as usize] as i64;
if self.mantissa % factor != 0 {
return None;
}
return Some(Self {
mantissa: self.mantissa / factor,
scale: Self::MAX_SCALE,
});
}
let mut left = exp as u32;
let mut mantissa = self.mantissa;
let mut scale = self.scale;
while left > 0 && scale > 0 {
scale -= 1;
left -= 1;
}
while left > 0 {
let step = if left > 18 { 18 } else { left };
let Some(next) = mantissa.checked_mul(POW10_U64[step as usize] as i64) else {
return None;
};
mantissa = next;
left -= step;
}
Some(Self { mantissa, scale })
}
#[must_use]
pub const fn checked_abs(self) -> Option<Self> {
let Some(mantissa) = self.mantissa.checked_abs() else {
return None;
};
Some(Self {
mantissa,
scale: self.scale,
})
}
#[must_use]
pub const fn checked_neg(self) -> Option<Self> {
let Some(mantissa) = self.mantissa.checked_neg() else {
return None;
};
Some(Self {
mantissa,
scale: self.scale,
})
}
#[must_use]
pub const fn min(self, other: Self) -> Self {
match self.compare(other) {
Ordering::Greater => other,
_ => self,
}
}
#[must_use]
pub const fn max(self, other: Self) -> Self {
match self.compare(other) {
Ordering::Less => other,
_ => self,
}
}
#[must_use]
pub const fn compare(self, other: Self) -> Ordering {
let scale = if self.scale > other.scale {
self.scale
} else {
other.scale
};
match (self.to_i128_at(scale), other.to_i128_at(scale)) {
(Some(a), Some(b)) => {
if a < b {
Ordering::Less
} else if a > b {
Ordering::Greater
} else {
Ordering::Equal
}
}
_ => {
if self.mantissa < other.mantissa {
Ordering::Less
} else if self.mantissa > other.mantissa {
Ordering::Greater
} else {
Ordering::Equal
}
}
}
}
const fn to_i128_at(self, scale: u8) -> Option<i128> {
if scale < self.scale {
return None;
}
let factor = pow10_i128((scale - self.scale) as u32);
Some(self.mantissa as i128 * factor)
}
#[allow(clippy::too_many_lines)]
pub const fn from_ascii(bytes: &[u8]) -> Result<Self, ParseDecimalError> {
let n = bytes.len();
let mut i = 0usize;
while i < n && is_space(bytes[i]) {
i += 1;
}
let mut negative = false;
if i < n && (bytes[i] == b'+' || bytes[i] == b'-') {
negative = bytes[i] == b'-';
i += 1;
}
let mut magnitude: u128 = 0;
let mut fraction_digits: i64 = 0;
let mut skipped_integer_digits: i64 = 0;
let mut round_digit: u8 = 0;
let mut sticky = false;
let mut dropped_any = false;
let mut seen_digit = false;
let mut seen_point = false;
while i < n {
let byte = bytes[i];
if byte == b'.' {
if seen_point {
return Err(ParseDecimalError::Invalid);
}
seen_point = true;
i += 1;
continue;
}
if byte < b'0' || byte > b'9' {
break;
}
seen_digit = true;
let digit = byte - b'0';
if magnitude < ACCUMULATE_LIMIT {
magnitude = magnitude * 10 + digit as u128;
if seen_point {
fraction_digits += 1;
}
} else {
if !seen_point {
skipped_integer_digits += 1;
}
if dropped_any {
if digit != 0 {
sticky = true;
}
} else {
round_digit = digit;
dropped_any = true;
}
}
i += 1;
}
if !seen_digit {
return Err(ParseDecimalError::Invalid);
}
let mut rounded_off = false;
if dropped_any {
if round_digit > 5 || (round_digit == 5 && (sticky || magnitude % 2 == 1)) {
magnitude += 1;
}
rounded_off = true;
}
let mut exponent: i64 = 0;
if i < n && (bytes[i] == b'e' || bytes[i] == b'E') {
i += 1;
let mut exponent_negative = false;
if i < n && (bytes[i] == b'+' || bytes[i] == b'-') {
exponent_negative = bytes[i] == b'-';
i += 1;
}
let mut seen_exponent_digit = false;
while i < n && bytes[i] >= b'0' && bytes[i] <= b'9' {
seen_exponent_digit = true;
if exponent < 1_000_000 {
exponent = exponent * 10 + (bytes[i] - b'0') as i64;
}
i += 1;
}
if !seen_exponent_digit {
return Err(ParseDecimalError::Invalid);
}
if exponent_negative {
exponent = -exponent;
}
}
while i < n && is_space(bytes[i]) {
i += 1;
}
if i != n {
return Err(ParseDecimalError::Invalid);
}
let mut scale = fraction_digits - skipped_integer_digits - exponent;
if magnitude == 0 {
if scale < 0 || scale > Self::MAX_SCALE as i64 {
scale = 0;
}
return Ok(Self {
mantissa: 0,
scale: scale as u8,
});
}
if scale < 0 {
let shift = -scale;
if shift > 38 {
return Err(ParseDecimalError::Overflow);
}
let factor = pow10_i128(shift as u32) as u128;
let Some(scaled) = magnitude.checked_mul(factor) else {
return Err(ParseDecimalError::Overflow);
};
magnitude = scaled;
scale = 0;
} else if scale > Self::MAX_SCALE as i64 {
let drop = scale - Self::MAX_SCALE as i64;
if drop > 39 {
magnitude = 0;
} else {
let dropped = drop as u32;
magnitude = round_off(magnitude, dropped, false);
}
scale = Self::MAX_SCALE as i64;
rounded_off = true;
}
while magnitude > i64::MAX as u128 {
if scale == 0 {
return Err(ParseDecimalError::Overflow);
}
magnitude = round_off(magnitude, 1, false);
scale -= 1;
rounded_off = true;
}
let _ = rounded_off;
let mantissa = magnitude as i64;
Ok(Self {
mantissa: if negative { -mantissa } else { mantissa },
scale: scale as u8,
})
}
#[must_use]
pub const fn from_literal(text: &str) -> Self {
let bytes = text.as_bytes();
let mut digits = [0u8; 64];
let mut len = 0usize;
let mut i = 0usize;
while i < bytes.len() {
if bytes[i] != b'_' {
assert!(len < 64, "decimal literal is too long");
digits[len] = bytes[i];
len += 1;
}
i += 1;
}
let (kept, _) = digits.split_at(len);
match Self::from_ascii(kept) {
Ok(value) => value,
Err(ParseDecimalError::Invalid) => panic!("not a decimal number"),
Err(ParseDecimalError::Overflow) => panic!("decimal number out of range"),
}
}
#[must_use]
#[allow(clippy::cast_precision_loss)] pub fn to_f64_lossy(self) -> f64 {
const POW10_F64: [f64; 19] = [
1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15,
1e16, 1e17, 1e18,
];
let mantissa = self.mantissa as f64;
mantissa / POW10_F64[self.scale as usize]
}
#[must_use]
pub fn from_f64_lossy(value: f64) -> Option<Self> {
if !value.is_finite() {
return None;
}
let mut buffer = TextBuffer::new();
if fmt::Write::write_fmt(&mut buffer, format_args!("{value:e}")).is_err() {
return None;
}
Self::from_ascii(buffer.as_bytes()).ok()
}
}
const fn round_off(magnitude: u128, digits: u32, sticky: bool) -> u128 {
if digits == 0 {
return magnitude;
}
if digits > 38 {
return 0;
}
let divisor = pow10_i128(digits) as u128;
let quotient = magnitude / divisor;
let remainder = magnitude % divisor;
let half = divisor / 2;
if remainder > half || (remainder == half && (sticky || quotient % 2 == 1)) {
quotient + 1
} else {
quotient
}
}
const fn narrow(mantissa: i128, scale: u8) -> Option<Decimal> {
if mantissa > i64::MAX as i128 || mantissa < i64::MIN as i128 {
return None;
}
Some(Decimal {
mantissa: mantissa as i64,
scale,
})
}
const fn is_space(byte: u8) -> bool {
matches!(byte, b' ' | b'\t' | b'\n' | b'\r')
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ParseDecimalError {
Invalid,
Overflow,
}
impl fmt::Display for ParseDecimalError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
ParseDecimalError::Invalid => "not a decimal number",
ParseDecimalError::Overflow => "decimal number out of range",
})
}
}
#[cfg(feature = "std")]
impl std::error::Error for ParseDecimalError {}
impl FromStr for Decimal {
type Err = ParseDecimalError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
Self::from_ascii(text.as_bytes())
}
}
impl fmt::Debug for Decimal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Decimal({self})")
}
}
impl fmt::Display for Decimal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.scale == 0 {
return write!(f, "{}", self.mantissa);
}
let magnitude = self.mantissa.unsigned_abs();
let divisor = POW10_U64[self.scale as usize];
let sign = if self.mantissa < 0 { "-" } else { "" };
write!(
f,
"{sign}{}.{:0width$}",
magnitude / divisor,
magnitude % divisor,
width = self.scale as usize
)
}
}
impl PartialEq for Decimal {
fn eq(&self, other: &Self) -> bool {
self.compare(*other) == Ordering::Equal
}
}
impl Eq for Decimal {}
impl PartialOrd for Decimal {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Decimal {
fn cmp(&self, other: &Self) -> Ordering {
self.compare(*other)
}
}
impl Hash for Decimal {
fn hash<H: Hasher>(&self, state: &mut H) {
let normalized = self.normalized();
normalized.mantissa.hash(state);
normalized.scale.hash(state);
}
}
macro_rules! binary_op {
($trait:ident, $method:ident, $checked:ident, $what:literal) => {
impl $trait for Decimal {
type Output = Decimal;
fn $method(self, rhs: Decimal) -> Decimal {
self.$checked(rhs)
.expect(concat!("Decimal ", $what, " overflowed"))
}
}
};
}
binary_op!(Add, add, checked_add, "addition");
binary_op!(Sub, sub, checked_sub, "subtraction");
binary_op!(Mul, mul, checked_mul, "multiplication");
impl Div for Decimal {
type Output = Decimal;
fn div(self, rhs: Decimal) -> Decimal {
self.checked_div(rhs, Decimal::MAX_SCALE)
.expect("Decimal division by zero or overflow")
}
}
impl Neg for Decimal {
type Output = Decimal;
fn neg(self) -> Decimal {
self.checked_neg().expect("Decimal negation overflowed")
}
}
impl AddAssign for Decimal {
fn add_assign(&mut self, rhs: Decimal) {
*self = *self + rhs;
}
}
impl SubAssign for Decimal {
fn sub_assign(&mut self, rhs: Decimal) {
*self = *self - rhs;
}
}
impl core::iter::Sum for Decimal {
fn sum<I: Iterator<Item = Decimal>>(iter: I) -> Decimal {
iter.fold(Decimal::ZERO, |total, value| total + value)
}
}
macro_rules! from_integer {
($($ty:ty),*) => {
$(
impl From<$ty> for Decimal {
fn from(value: $ty) -> Self {
Self { mantissa: i64::from(value), scale: 0 }
}
}
)*
};
}
from_integer!(i8, i16, i32, i64, u8, u16, u32);
impl TryFrom<u64> for Decimal {
type Error = ParseDecimalError;
fn try_from(value: u64) -> Result<Self, Self::Error> {
i64::try_from(value)
.map(Self::from_i64)
.map_err(|_| ParseDecimalError::Overflow)
}
}
impl TryFrom<Decimal> for i64 {
type Error = ParseDecimalError;
fn try_from(value: Decimal) -> Result<Self, Self::Error> {
value
.rescale(0)
.map(Decimal::mantissa)
.ok_or(ParseDecimalError::Invalid)
}
}
const TEXT_CAPACITY: usize = 40;
struct TextBuffer {
bytes: [u8; TEXT_CAPACITY],
len: usize,
}
impl TextBuffer {
const fn new() -> Self {
Self {
bytes: [0; TEXT_CAPACITY],
len: 0,
}
}
fn as_bytes(&self) -> &[u8] {
&self.bytes[..self.len]
}
fn as_str(&self) -> &str {
core::str::from_utf8(self.as_bytes()).unwrap_or("0")
}
}
impl fmt::Write for TextBuffer {
fn write_str(&mut self, text: &str) -> fmt::Result {
let end = self.len + text.len();
if end > TEXT_CAPACITY {
return Err(fmt::Error);
}
self.bytes[self.len..end].copy_from_slice(text.as_bytes());
self.len = end;
Ok(())
}
}
const RAW_TOKEN: &str = "$serde_json::private::RawValue";
impl Serialize for Decimal {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct as _;
let mut buffer = TextBuffer::new();
if fmt::Write::write_fmt(&mut buffer, format_args!("{self}")).is_err() {
return Err(serde::ser::Error::custom("decimal is too long to render"));
}
let mut raw = serializer.serialize_struct(RAW_TOKEN, 1)?;
raw.serialize_field(RAW_TOKEN, buffer.as_str())?;
raw.end()
}
}
impl<'de> Deserialize<'de> for Decimal {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
deserializer.deserialize_newtype_struct(RAW_TOKEN, DecimalVisitor)
}
}
struct DecimalVisitor;
impl<'de> serde::de::Visitor<'de> for DecimalVisitor {
type Value = Decimal;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a JSON number")
}
fn visit_i64<E: serde::de::Error>(self, value: i64) -> Result<Decimal, E> {
Ok(Decimal::from_i64(value))
}
fn visit_u64<E: serde::de::Error>(self, value: u64) -> Result<Decimal, E> {
Decimal::try_from(value).map_err(|_| E::custom("number out of range for a decimal"))
}
fn visit_f64<E: serde::de::Error>(self, value: f64) -> Result<Decimal, E> {
Decimal::from_f64_lossy(value)
.ok_or_else(|| E::custom("number is not a finite decimal in range"))
}
fn visit_newtype_struct<D: serde::Deserializer<'de>>(
self,
deserializer: D,
) -> Result<Decimal, D::Error> {
deserializer.deserialize_any(DecimalVisitor)
}
fn visit_map<A: serde::de::MapAccess<'de>>(self, mut map: A) -> Result<Decimal, A::Error> {
use serde::de::Error as _;
let Some(RawKey) = map.next_key::<RawKey>()? else {
return Err(A::Error::custom("expected a JSON number"));
};
let RawToken(value) = map.next_value::<RawToken>()?;
Ok(value)
}
}
struct RawKey;
impl<'de> Deserialize<'de> for RawKey {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct KeyVisitor;
impl serde::de::Visitor<'_> for KeyVisitor {
type Value = RawKey;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a raw value marker")
}
fn visit_str<E: serde::de::Error>(self, _value: &str) -> Result<RawKey, E> {
Ok(RawKey)
}
}
deserializer.deserialize_identifier(KeyVisitor)
}
}
struct RawToken(Decimal);
impl<'de> Deserialize<'de> for RawToken {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct TokenVisitor;
impl serde::de::Visitor<'_> for TokenVisitor {
type Value = RawToken;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("a JSON number")
}
fn visit_str<E: serde::de::Error>(self, token: &str) -> Result<RawToken, E> {
use serde::de::Unexpected;
let trimmed = token.trim();
let unexpected = match trimmed.as_bytes().first() {
Some(b'"') => Some(Unexpected::Str(trimmed.trim_matches('"'))),
Some(b'{') => Some(Unexpected::Map),
Some(b'[') => Some(Unexpected::Seq),
Some(b't') => Some(Unexpected::Bool(true)),
Some(b'f') => Some(Unexpected::Bool(false)),
Some(b'n') => Some(Unexpected::Unit),
_ => None,
};
if let Some(unexpected) = unexpected {
return Err(E::invalid_type(unexpected, &"a JSON number"));
}
Decimal::from_ascii(trimmed.as_bytes())
.map(RawToken)
.map_err(|error| {
let expected: &str = match error {
ParseDecimalError::Overflow => "a decimal number in range",
ParseDecimalError::Invalid => "a decimal number",
};
E::invalid_value(Unexpected::Other(trimmed), &expected)
})
}
}
deserializer.deserialize_str(TokenVisitor)
}
}
impl Validate for Decimal {
fn validate_at(&self, _path: &mut ValidationPath, _out: &mut Violations) {}
}
#[macro_export]
macro_rules! decimal {
($($token:tt)+) => {
const {
$crate::types::Decimal::from_literal(::core::stringify!($($token)+))
}
};
}
#[cfg(test)]
mod tests {
use super::*;
use alloc::string::ToString;
#[test]
fn the_scale_the_station_sent_survives_the_round_trip() {
let value: Decimal = serde_json::from_str("2935.600").unwrap();
assert_eq!(value.scale(), 3);
assert_eq!(value.mantissa(), 2_935_600);
assert_eq!(serde_json::to_string(&value).unwrap(), "2935.600");
assert_eq!(value.to_string(), "2935.600");
let short: Decimal = serde_json::from_str("2935.6").unwrap();
assert_eq!(value, short);
assert!(!value.eq_exact(short));
}
#[test]
fn a_difference_of_two_registers_is_exact() {
let start: Decimal = "0.1".parse().unwrap();
let stop: Decimal = "10.2".parse().unwrap();
assert_eq!((stop - start).to_string(), "10.1");
}
#[test]
fn every_json_number_spelling_parses() {
for (text, expected) in [
("0", "0"),
("-0", "0"),
("42", "42"),
("-17.25", "-17.25"),
("0.00", "0.00"),
("1e3", "1000"),
("1.5E+3", "1500"),
("15e-1", "1.5"),
("2E-4", "0.0002"),
("0.000000000000000001", "0.000000000000000001"),
("9223372036854775807", "9223372036854775807"),
] {
let value: Decimal = text.parse().unwrap_or_else(|_| panic!("{text}"));
assert_eq!(value.to_string(), expected, "{text}");
}
for text in ["", "-", "abc", "1.2.3", "1e", "NaN", "1 2", "--1"] {
assert!(text.parse::<Decimal>().is_err(), "{text} should not parse");
}
}
#[test]
fn excess_precision_rounds_half_to_even_rather_than_failing() {
let value: Decimal = "0.12345678901234567895".parse().unwrap();
assert_eq!(value.scale(), Decimal::MAX_SCALE);
assert_eq!(value.to_string(), "0.123456789012345679");
assert_eq!("1e30".parse::<Decimal>(), Err(ParseDecimalError::Overflow));
}
#[test]
fn arithmetic_is_exact_and_checked() {
let a = decimal!(1.05);
let b = decimal!(2.1);
assert_eq!((a + b).to_string(), "3.15");
assert_eq!((b - a).to_string(), "1.05");
assert_eq!((a * b).to_string(), "2.205");
assert_eq!(a.checked_div(b, 4).unwrap().to_string(), "0.5000");
assert_eq!(
decimal!(1).checked_div(decimal!(3), 5).unwrap().to_string(),
"0.33333"
);
assert_eq!(
decimal!(2).checked_div(decimal!(3), 5).unwrap().to_string(),
"0.66667"
);
assert_eq!(decimal!(0.125).round_to(2).unwrap().to_string(), "0.12");
assert_eq!(decimal!(0.135).round_to(2).unwrap().to_string(), "0.14");
assert_eq!(Decimal::new(i64::MAX, 0).checked_add(Decimal::ONE), None);
assert_eq!(decimal!(1).checked_div(Decimal::ZERO, 2), None);
}
#[test]
fn an_absurd_exponent_is_refused_rather_than_overflowing() {
assert_eq!(decimal!(1.5).checked_pow10(i32::MIN), None);
assert_eq!(decimal!(1.5).checked_pow10(i32::MAX), None);
assert_eq!(Decimal::ZERO.checked_pow10(i32::MIN), Some(Decimal::ZERO));
assert_eq!(decimal!(1).checked_pow10(19), None);
assert_eq!(
decimal!(1).checked_pow10(18).unwrap().mantissa(),
10i64.pow(18)
);
}
#[test]
fn a_change_of_unit_prefix_only_moves_the_point() {
let kwh = decimal!(2935.600);
assert_eq!(kwh.checked_pow10(3).unwrap().to_string(), "2935600");
assert_eq!(kwh.checked_pow10(-3).unwrap().to_string(), "2.935600");
assert_eq!(decimal!(1.5).checked_pow10(1).unwrap().to_string(), "15");
}
#[test]
fn comparison_is_numeric_and_ordering_is_total() {
assert_eq!(decimal!(2.50), decimal!(2.5));
assert!(decimal!(2.5) < decimal!(10));
assert!(decimal!(-1) < Decimal::ZERO);
assert_eq!(decimal!(1.10).min(decimal!(1.2)), decimal!(1.1));
assert_eq!(decimal!(1.10).max(decimal!(1.2)), decimal!(1.2));
assert_eq!(decimal!(2.500).normalized().to_string(), "2.5");
}
#[test]
fn every_serde_json_entry_point_agrees() {
let value: Decimal = serde_json::from_str("1.230").unwrap();
assert_eq!(serde_json::to_value(value).unwrap().to_string(), "1.23");
let from_value: Decimal = serde_json::from_value(serde_json::json!(1.23)).unwrap();
assert_eq!(from_value, decimal!(1.23));
let from_int: Decimal = serde_json::from_value(serde_json::json!(7)).unwrap();
assert_eq!(from_int, decimal!(7));
let mut de = serde_json::Deserializer::from_str("2935.600");
let traced: Decimal = serde_path_to_error::deserialize(&mut de).unwrap();
assert!(traced.eq_exact(decimal!(2935.600)));
}
#[test]
fn a_wrong_json_type_still_reads_as_a_type_error() {
let error = serde_json::from_str::<Decimal>("\"42\"").unwrap_err();
assert!(
error.to_string().starts_with("invalid type: string"),
"{error}"
);
assert_eq!(error.classify(), serde_json::error::Category::Data);
for (text, expected) in [
("true", "invalid type: boolean"),
("null", "invalid type: null"),
("[]", "invalid type: sequence"),
("{}", "invalid type: map"),
] {
let error = serde_json::from_str::<Decimal>(text).unwrap_err();
assert!(error.to_string().starts_with(expected), "{text}: {error}");
}
}
#[test]
fn floating_point_conversion_is_available_but_has_to_be_asked_for() {
assert_eq!(Decimal::from_f64_lossy(0.1).unwrap(), decimal!(0.1));
assert_eq!(
Decimal::from_f64_lossy(1e18).unwrap().to_string(),
"1000000000000000000"
);
assert_eq!(Decimal::from_f64_lossy(f64::NAN), None);
assert_eq!(Decimal::from_f64_lossy(1e300), None);
assert!((decimal!(2935.600).to_f64_lossy() - 2935.6).abs() < 1e-9);
}
#[test]
fn equal_values_hash_equally_whatever_their_scale() {
use core::hash::BuildHasher;
let state = std::collections::hash_map::RandomState::new();
assert_eq!(
state.hash_one(decimal!(2.50)),
state.hash_one(decimal!(2.5))
);
assert_eq!(
state.hash_one(Decimal::ZERO),
state.hash_one(decimal!(0.000))
);
}
}