Skip to main content

surrealdb_expr/val/
number.rs

1//! Numeric value type used throughout SurrealDB.
2//!
3//! This module defines Number, a discriminated union over Int (i64), Float (f64),
4//! and Decimal (rust_decimal::Decimal), and implements arithmetic, comparison,
5//! and conversions. For storage in index keys, Numbers are serialized with a
6//! canonical, lexicographic encoding (via expr::decimal::DecimalLexEncoder)
7//! so that byte-wise ordering matches numeric ordering and numerically-equal
8//! values across variants normalize to identical bytes.
9//!
10//! Key points:
11//! - Ordering: PartialOrd/Ord behavior aims to reflect mathematical ordering across variants; for
12//!   index keys we rely on DecimalLexEncoder to preserve ordering at the byte level.
13//! - Normalization in keys: 0 (Int), 0.0 (Float) and 0dec (Decimal) encode to the same byte
14//!   sequence for keys, so UNIQUE indexes treat them as equal.
15//! - Special float values: NaN, +∞ and −∞ are given fixed encodings that fit in the total ordering
16//!   used by keys (see DecimalLexEncoder docs).
17//! - Stream-friendly: the numeric encoding contains an in-band terminator and appends a 0x00 byte,
18//!   allowing concatenation in composite keys without ambiguity during decoding.
19
20use std::cmp::Ordering;
21use std::f64::consts::PI;
22use std::fmt::{self, Debug, Display, Formatter};
23use std::hash;
24use std::iter::{Product, Sum};
25use std::ops::{self, Add, Div, Mul, Neg, Rem, Sub};
26use std::str::FromStr;
27
28use anyhow::{Result, bail, ensure};
29use fastnum::D128;
30use revision::revisioned;
31use rust_decimal::Decimal;
32use rust_decimal::prelude::*;
33use storekey::{BorrowDecode, Encode};
34use surrealdb_types::{SqlFormat, ToSql, fmt_non_finite_f64, write_sql};
35
36use super::IndexFormat;
37use crate::expr::Error;
38use crate::expr::decimal::DecimalLexEncoder;
39use crate::val::{TryAdd, TryDiv, TryFloatDiv, TryMul, TryNeg, TryPow, TryRem, TrySub};
40
41#[derive(Copy, Clone, Encode, BorrowDecode)]
42pub enum NumberKind {
43	Int,
44	Float,
45	Decimal,
46}
47
48#[revisioned(revision = 1)]
49#[derive(Clone, Copy, Debug)]
50#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
51pub enum Number {
52	Int(i64),
53	Float(f64),
54	Decimal(Decimal),
55	// Add new variants here
56}
57
58impl Default for Number {
59	fn default() -> Self {
60		Self::Int(0)
61	}
62}
63
64macro_rules! from_prim_ints {
65	($($int: ty),*) => {
66		$(
67			impl From<$int> for Number {
68				fn from(i: $int) -> Self {
69					Self::Int(i as i64)
70				}
71			}
72		)*
73	};
74}
75
76// Only integer types that always fit losslessly into an i64 are converted
77// infallibly here. Wider types are handled below so they store the value
78// correctly (as a Decimal when it exceeds i64) instead of truncating.
79from_prim_ints!(i8, i16, i32, i64, isize, u8, u16, u32);
80
81// `u64`/`usize` can exceed i64::MAX but always fit within Decimal's 96-bit
82// mantissa, so the conversion is lossless and infallible: store as an Int when
83// it fits, otherwise as a Decimal.
84impl From<u64> for Number {
85	fn from(i: u64) -> Self {
86		match i64::try_from(i) {
87			Ok(v) => Self::Int(v),
88			Err(_) => Self::Decimal(Decimal::from(i)),
89		}
90	}
91}
92
93impl From<usize> for Number {
94	fn from(i: usize) -> Self {
95		// usize is at most 64 bits wide on every supported target.
96		Self::from(i as u64)
97	}
98}
99
100// `i128`/`u128` can exceed Decimal's range (2^96), so the conversion is
101// fallible: store as an Int when it fits in i64, otherwise as a Decimal, and
102// error rather than silently truncate when the value is too large for either.
103impl TryFrom<i128> for Number {
104	type Error = Error;
105	fn try_from(i: i128) -> Result<Self, Self::Error> {
106		if let Ok(v) = i64::try_from(i) {
107			Ok(Self::Int(v))
108		} else if let Some(v) = Decimal::from_i128(i) {
109			Ok(Self::Decimal(v))
110		} else {
111			Err(Error::TryFrom(i.to_string(), "Number"))
112		}
113	}
114}
115
116impl TryFrom<u128> for Number {
117	type Error = Error;
118	fn try_from(i: u128) -> Result<Self, Self::Error> {
119		if let Ok(v) = i64::try_from(i) {
120			Ok(Self::Int(v))
121		} else if let Some(v) = Decimal::from_u128(i) {
122			Ok(Self::Decimal(v))
123		} else {
124			Err(Error::TryFrom(i.to_string(), "Number"))
125		}
126	}
127}
128
129impl From<f32> for Number {
130	fn from(f: f32) -> Self {
131		Self::Float(f as f64)
132	}
133}
134
135impl From<f64> for Number {
136	fn from(f: f64) -> Self {
137		Self::Float(f)
138	}
139}
140
141impl From<Decimal> for Number {
142	fn from(v: Decimal) -> Self {
143		Self::Decimal(v)
144	}
145}
146
147impl From<surrealdb_types::Number> for Number {
148	fn from(v: surrealdb_types::Number) -> Self {
149		match v {
150			surrealdb_types::Number::Int(i) => Self::Int(i),
151			surrealdb_types::Number::Float(f) => Self::Float(f),
152			surrealdb_types::Number::Decimal(d) => Self::Decimal(d),
153		}
154	}
155}
156
157impl From<Number> for surrealdb_types::Number {
158	fn from(v: Number) -> Self {
159		match v {
160			Number::Int(i) => Self::Int(i),
161			Number::Float(f) => Self::Float(f),
162			Number::Decimal(d) => Self::Decimal(d),
163		}
164	}
165}
166
167impl FromStr for Number {
168	type Err = ();
169	fn from_str(s: &str) -> Result<Self, Self::Err> {
170		// Attempt to parse as i64
171		match s.parse::<i64>() {
172			// Store it as an i64
173			Ok(v) => Ok(Self::Int(v)),
174			// It wasn't parsed as a i64 so parse as a float
175			_ => match s.parse::<f64>() {
176				// Store it as a float
177				Ok(v) => Ok(Self::Float(v)),
178				// It wasn't parsed as a number
179				_ => Err(()),
180			},
181		}
182	}
183}
184
185macro_rules! try_into_prim {
186	// TODO: switch to one argument per int once https://github.com/rust-lang/rust/issues/29599 is stable
187	($($int: ty => $to_int: ident),*) => {
188		$(
189			impl TryFrom<Number> for $int {
190				type Error = Error;
191				fn try_from(value: Number) -> Result<Self, Self::Error> {
192					match value {
193						Number::Int(v) => match v.$to_int() {
194							Some(v) => Ok(v),
195							None => Err(Error::TryFrom(value.to_sql(), stringify!($int))),
196						},
197						Number::Float(v) => match v.$to_int() {
198							Some(v) => Ok(v),
199							None => Err(Error::TryFrom(value.to_sql(), stringify!($int))),
200						},
201						Number::Decimal(ref v) => match v.$to_int() {
202							Some(v) => Ok(v),
203							None => Err(Error::TryFrom(value.to_sql(), stringify!($int))),
204						},
205					}
206				}
207			}
208		)*
209	};
210}
211
212try_into_prim!(
213	i8 => to_i8, i16 => to_i16, i32 => to_i32, i64 => to_i64, i128 => to_i128,
214	u8 => to_u8, u16 => to_u16, u32 => to_u32, u64 => to_u64, u128 => to_u128,
215	f32 => to_f32, f64 => to_f64
216);
217
218impl TryFrom<Number> for Decimal {
219	type Error = Error;
220	fn try_from(value: Number) -> Result<Self, Self::Error> {
221		match value {
222			Number::Int(v) => match Decimal::from_i64(v) {
223				Some(v) => Ok(v),
224				None => Err(Error::TryFrom(value.to_sql(), "Decimal")),
225			},
226			Number::Float(v) => match Decimal::try_from(v) {
227				Ok(v) => Ok(v),
228				_ => Err(Error::TryFrom(value.to_sql(), "Decimal")),
229			},
230			Number::Decimal(x) => Ok(x),
231		}
232	}
233}
234
235impl Display for Number {
236	fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
237		match self {
238			Number::Int(v) => Display::fmt(v, f),
239			Number::Float(v) => Display::fmt(v, f),
240			Number::Decimal(v) => Display::fmt(v, f),
241		}
242	}
243}
244
245impl ToSql for Number {
246	fn fmt_sql(&self, f: &mut String, sql_fmt: SqlFormat) {
247		match self {
248			Number::Int(v) => v.fmt_sql(f, sql_fmt),
249			Number::Float(v) => {
250				match fmt_non_finite_f64(*v) {
251					// Special case: Infinity, -Infinity or NaN
252					Some(special) => write_sql!(f, sql_fmt, "{}", special),
253					// Regular float: add f to distinguish between int and float
254					None => write_sql!(f, sql_fmt, "{v}f"),
255				}
256			}
257			Number::Decimal(v) => v.fmt_sql(f, sql_fmt),
258		}
259	}
260}
261
262impl Number {
263	// -----------------------------------
264	// Constants
265	// -----------------------------------
266
267	pub const NAN: Number = Number::Float(f64::NAN);
268
269	// -----------------------------------
270	// Simple number detection
271	// -----------------------------------
272
273	pub fn is_int(&self) -> bool {
274		matches!(self, Number::Int(_))
275	}
276
277	pub fn is_float(&self) -> bool {
278		matches!(self, Number::Float(_))
279	}
280
281	pub fn is_truthy(&self) -> bool {
282		match self {
283			Number::Int(v) => v != &0,
284			Number::Float(v) => v != &0.0,
285			Number::Decimal(v) => v != &Decimal::ZERO,
286		}
287	}
288
289	pub fn is_zero(&self) -> bool {
290		match self {
291			Number::Int(v) => v == &0,
292			Number::Float(v) => v == &0.0,
293			Number::Decimal(v) => v == &Decimal::ZERO,
294		}
295	}
296
297	// -----------------------------------
298	// Simple conversion of number
299	// -----------------------------------
300
301	pub fn as_usize(self) -> usize {
302		match self {
303			Number::Int(v) => v as usize,
304			Number::Float(v) => v as usize,
305			Number::Decimal(v) => v.try_into().unwrap_or_default(),
306		}
307	}
308
309	pub fn as_int(self) -> i64 {
310		match self {
311			Number::Int(v) => v,
312			Number::Float(v) => v as i64,
313			Number::Decimal(v) => v.try_into().unwrap_or_default(),
314		}
315	}
316
317	pub fn as_float(self) -> f64 {
318		match self {
319			Number::Int(v) => v as f64,
320			Number::Float(v) => v,
321			Number::Decimal(v) => v.try_into().unwrap_or_default(),
322		}
323	}
324
325	pub fn as_decimal(self) -> Decimal {
326		match self {
327			Number::Int(v) => Decimal::from(v),
328			Number::Float(v) => Decimal::try_from(v).unwrap_or_default(),
329			Number::Decimal(v) => v,
330		}
331	}
332
333	// -----------------------------------
334	// Complex conversion of number
335	// -----------------------------------
336
337	/// Convert to an `i64` only when the value round-trips exactly.
338	///
339	/// Returns `None` for any value that does not represent an exact integer
340	/// within `i64` range — including NaN, infinities, fractional values, and
341	/// out-of-range magnitudes. Lossy `as` casts (which saturate or truncate
342	/// silently) are deliberately avoided so callers can reject the input
343	/// rather than write a wrong value.
344	pub fn as_int_lossless(self) -> Option<i64> {
345		match self {
346			Number::Int(v) => Some(v),
347			Number::Float(v) => {
348				// `i64::MAX as f64` rounds up to 2^63 (the next representable
349				// f64), which is *not* in i64 range. `-(i64::MIN as f64)` is
350				// exactly 2^63 and is the right exclusive upper bound.
351				if !v.is_finite()
352					|| v.fract() != 0.0
353					|| v < i64::MIN as f64
354					|| v >= -(i64::MIN as f64)
355				{
356					return None;
357				}
358				Some(v as i64)
359			}
360			Number::Decimal(v) => {
361				if v.fract().is_zero() {
362					v.try_into().ok()
363				} else {
364					None
365				}
366			}
367		}
368	}
369
370	/// Convert to a `usize` suitable for array indexing.
371	///
372	/// Returns `None` for any value that does not represent an exact
373	/// non-negative integer within `usize` range — including negatives,
374	/// NaN, infinities, fractional values, and out-of-range magnitudes.
375	pub fn as_array_index(self) -> Option<usize> {
376		match self {
377			Number::Int(v) => usize::try_from(v).ok(),
378			Number::Float(v) => {
379				if !v.is_finite() || v < 0.0 || v.fract() != 0.0 {
380					return None;
381				}
382				// `f64 as usize` saturates above `usize::MAX`; round-trip back
383				// through f64 to reject any value that couldn't be represented
384				// exactly.
385				let idx = v as usize;
386				(idx as f64 == v).then_some(idx)
387			}
388			Number::Decimal(v) => {
389				if v.fract().is_zero() {
390					v.to_usize()
391				} else {
392					None
393				}
394			}
395		}
396	}
397
398	pub fn to_int(self) -> i64 {
399		match self {
400			Number::Int(v) => v,
401			Number::Float(v) => v as i64,
402			Number::Decimal(v) => v.to_i64().unwrap_or_default(),
403		}
404	}
405
406	/// The number as an `f64`. Inlined so that per-component loops in other
407	/// crates (the vector functions' norms and distances) compile it into the
408	/// loop whatever link-time optimisation decides.
409	#[inline]
410	pub fn to_float(self) -> f64 {
411		match self {
412			Number::Int(v) => v as f64,
413			Number::Float(v) => v,
414			Number::Decimal(v) => v.try_into().unwrap_or_default(),
415		}
416	}
417
418	pub fn to_decimal(self) -> Decimal {
419		match self {
420			Number::Int(v) => Decimal::from(v),
421			Number::Float(v) => Decimal::from_f64(v).unwrap_or_default(),
422			Number::Decimal(v) => v,
423		}
424	}
425
426	/// Converts this Number to a lexicographically ordered byte buffer.
427	///
428	/// This serializes the Number using DecimalLexEncoder so that byte-wise
429	/// comparison preserves numeric ordering. This is essential for database
430	/// indexes where key bytes must sort the same way as their numeric values.
431	///
432	/// Ordering guarantees:
433	/// - If `a < b` numerically, then `a.as_decimal_buf() < b.as_decimal_buf()` lexicographically.
434	///
435	/// Encoding format:
436	/// - A leading class/marker byte indicates zero, finite negative, finite positive, negative
437	///   infinity, positive infinity, or NaN.
438	/// - Two bytes encode a biased scale for finite values.
439	/// - Packed base-10 digits follow (2 digits per byte), with an in-band terminator ensured by
440	///   the packing scheme; the encoder also appends a trailing 0x00 terminator byte for
441	///   stream-friendly decoding.
442	///
443	/// Notes:
444	/// - There is no extra "type marker" for Int/Float/Decimal variants; all variants are
445	///   normalized through D128 for ordering.
446	/// - Special float values (NaN/±∞) are mapped to fixed encodings at the extremes to preserve a
447	///   total order.
448	///
449	/// Returns an ordered byte buffer or an error if Decimal conversion fails
450	/// for Decimal variant values.
451	pub fn as_decimal_buf(&self) -> Vec<u8> {
452		match self {
453			Self::Int(v) => {
454				// Convert integer to decimal for consistent encoding across all numeric types
455				DecimalLexEncoder::encode(D128::from(*v))
456			}
457			Self::Float(v) => {
458				// Convert float to decimal for lexicographic encoding
459				DecimalLexEncoder::encode(D128::from_f64(*v))
460			}
461			Self::Decimal(v) => {
462				// Direct encoding of decimal values using lexicographic encoder
463				DecimalLexEncoder::encode(DecimalLexEncoder::to_d128(*v))
464			}
465		}
466	}
467
468	/// Reconstructs a Number from a lexicographically ordered byte buffer.
469	///
470	/// This deserializes a buffer produced by `as_decimal_buf()` using
471	/// DecimalLexEncoder, recovering the numeric value. All Number variants are
472	/// normalized through the same encoding, so the original variant (Int/Float/
473	/// Decimal) is not preserved; only the value (and special cases like NaN/±∞)
474	/// matters for ordering and equality in keys.
475	///
476	/// The decoder recognizes:
477	/// - Zero, finite negatives, finite positives (via marker and biased scale)
478	/// - Negative/positive infinity, NaN (fixed encodings)
479	/// - An explicit in-band terminator added by the encoder, which ensures the mantissa decoder
480	///   stops before any following data in the stream.
481	///
482	/// Returns the reconstructed Number or an error if the buffer is empty or
483	/// cannot be decoded.
484	pub fn from_decimal_buf(b: &[u8]) -> Result<Self> {
485		let dec = DecimalLexEncoder::decode(b)?;
486		if dec.is_finite() {
487			match DecimalLexEncoder::to_decimal(dec) {
488				Ok(dec) => Ok(Number::Decimal(dec)),
489				Err(_) => Ok(Number::Float(dec.to_f64())),
490			}
491		} else if dec.is_nan() {
492			Ok(Number::Float(f64::NAN))
493		} else if dec.is_infinite() {
494			if dec.is_negative() {
495				Ok(Number::Float(f64::NEG_INFINITY))
496			} else {
497				Ok(Number::Float(f64::INFINITY))
498			}
499		} else {
500			bail!(Error::Serialization(format!("Invalid decimal value: {dec}")))
501		}
502	}
503
504	pub fn from_decimal_buf_kind(b: &[u8], kind: NumberKind) -> Result<Self> {
505		let dec = DecimalLexEncoder::decode(b)?;
506		match kind {
507			NumberKind::Int => {
508				ensure!(dec.is_finite(), format!("Invalid integer value: {dec}"));
509				Ok(Number::Int(dec.to_string().parse::<i64>()?))
510			}
511			NumberKind::Float => {
512				if dec.is_nan() {
513					Ok(Number::Float(f64::NAN))
514				} else if dec.is_infinite() {
515					if dec.is_negative() {
516						Ok(Number::Float(f64::NEG_INFINITY))
517					} else {
518						Ok(Number::Float(f64::INFINITY))
519					}
520				} else {
521					let dec = DecimalLexEncoder::to_decimal(dec)?;
522					dec.to_f64()
523						.ok_or_else(|| anyhow::Error::msg(format!("Invalid f64 {dec}")))
524						.map(Number::Float)
525				}
526			}
527			NumberKind::Decimal => {
528				ensure!(dec.is_finite(), format!("Invalid integer value: {dec}"));
529				Ok(Number::Decimal(DecimalLexEncoder::to_decimal(dec)?))
530			}
531		}
532	}
533
534	// -----------------------------------
535	//
536	// -----------------------------------
537
538	pub fn abs(self) -> Self {
539		match self {
540			Number::Int(v) => v.abs().into(),
541			Number::Float(v) => v.abs().into(),
542			Number::Decimal(v) => v.abs().into(),
543		}
544	}
545
546	pub fn checked_abs(self) -> Option<Self> {
547		match self {
548			Number::Int(v) => v.checked_abs().map(|x| x.into()),
549			Number::Float(v) => Some(v.abs().into()),
550			Number::Decimal(v) => Some(v.abs().into()),
551		}
552	}
553
554	pub fn acos(self) -> Self {
555		self.to_float().acos().into()
556	}
557
558	pub fn asin(self) -> Self {
559		self.to_float().asin().into()
560	}
561
562	pub fn atan(self) -> Self {
563		self.to_float().atan().into()
564	}
565
566	pub fn acot(self) -> Self {
567		(PI / 2.0 - self.atan().to_float()).into()
568	}
569
570	pub fn ceil(self) -> Self {
571		match self {
572			Number::Int(v) => v.into(),
573			Number::Float(v) => v.ceil().into(),
574			Number::Decimal(v) => v.ceil().into(),
575		}
576	}
577
578	pub fn clamp(self, min: Self, max: Self) -> Self {
579		match (self, min, max) {
580			(Number::Int(n), Number::Int(min), Number::Int(max)) => n.clamp(min, max).into(),
581			(Number::Decimal(n), min, max) => n.clamp(min.to_decimal(), max.to_decimal()).into(),
582			(Number::Float(n), min, max) => n.clamp(min.to_float(), max.to_float()).into(),
583			(Number::Int(n), min, max) => n.to_float().clamp(min.to_float(), max.to_float()).into(),
584		}
585	}
586
587	pub fn cos(self) -> Self {
588		self.to_float().cos().into()
589	}
590
591	pub fn cot(self) -> Self {
592		(1.0 / self.to_float().tan()).into()
593	}
594
595	pub fn deg2rad(self) -> Self {
596		self.to_float().to_radians().into()
597	}
598
599	pub fn floor(self) -> Self {
600		match self {
601			Number::Int(v) => v.into(),
602			Number::Float(v) => v.floor().into(),
603			Number::Decimal(v) => v.floor().into(),
604		}
605	}
606
607	fn lerp_f64(from: f64, to: f64, factor: f64) -> f64 {
608		from + factor * (to - from)
609	}
610
611	fn lerp_decimal(from: Decimal, to: Decimal, factor: Decimal) -> Decimal {
612		from + factor * (to - from)
613	}
614
615	pub fn lerp(self, from: Self, to: Self) -> Self {
616		match (self, from, to) {
617			(Number::Decimal(val), from, to) => {
618				Self::lerp_decimal(from.to_decimal(), to.to_decimal(), val).into()
619			}
620			(val, from, to) => {
621				Self::lerp_f64(from.to_float(), to.to_float(), val.to_float()).into()
622			}
623		}
624	}
625
626	fn repeat_f64(t: f64, m: f64) -> f64 {
627		(t - (t / m).floor() * m).clamp(0.0, m)
628	}
629
630	fn repeat_decimal(t: Decimal, m: Decimal) -> Decimal {
631		(t - (t / m).floor() * m).clamp(Decimal::ZERO, m)
632	}
633
634	pub fn lerp_angle(self, from: Self, to: Self) -> Self {
635		match (self, from, to) {
636			(Number::Decimal(val), from, to) => {
637				let from = from.to_decimal();
638				let to = to.to_decimal();
639				let mut dt = Self::repeat_decimal(to - from, Decimal::from(360));
640				if dt > Decimal::from(180) {
641					dt = Decimal::from(360) - dt;
642				}
643				Self::lerp_decimal(from, from + dt, val).into()
644			}
645			(val, from, to) => {
646				let val = val.to_float();
647				let from = from.to_float();
648				let to = to.to_float();
649				let mut dt = Self::repeat_f64(to - from, 360.0);
650				if dt > 180.0 {
651					dt = 360.0 - dt;
652				}
653				Self::lerp_f64(from, from + dt, val).into()
654			}
655		}
656	}
657
658	pub fn ln(self) -> Self {
659		self.to_float().ln().into()
660	}
661
662	pub fn log(self, base: Self) -> Self {
663		self.to_float().log(base.to_float()).into()
664	}
665
666	pub fn log2(self) -> Self {
667		self.to_float().log2().into()
668	}
669
670	pub fn log10(self) -> Self {
671		self.to_float().log10().into()
672	}
673
674	pub fn rad2deg(self) -> Self {
675		self.to_float().to_degrees().into()
676	}
677
678	pub fn round(self) -> Self {
679		match self {
680			Number::Int(v) => v.into(),
681			Number::Float(v) => v.round().into(),
682			Number::Decimal(v) => v.round().into(),
683		}
684	}
685
686	pub fn fixed(self, precision: usize) -> Number {
687		match self {
688			Number::Int(v) => v.into(),
689			// Truncate via the formatter so subnormals and very large
690			// magnitudes (which would overflow a `10^precision` multiplier)
691			// stay representable; non-finite f64s round-trip too.
692			Number::Float(v) => format!("{v:.precision$}")
693				.parse::<f64>()
694				.expect("formatted f64 always parses back as f64")
695				.into(),
696			Number::Decimal(v) => v.round_dp(precision as u32).into(),
697		}
698	}
699
700	pub fn sign(self) -> Self {
701		match self {
702			Number::Int(n) => n.signum().into(),
703			Number::Float(n) => n.signum().into(),
704			Number::Decimal(n) => n.signum().into(),
705		}
706	}
707
708	pub fn sin(self) -> Self {
709		self.to_float().sin().into()
710	}
711
712	pub fn tan(self) -> Self {
713		self.to_float().tan().into()
714	}
715
716	pub fn sqrt(self) -> Self {
717		match self {
718			Number::Int(v) => (v as f64).sqrt().into(),
719			Number::Float(v) => v.sqrt().into(),
720			Number::Decimal(v) => v.sqrt().unwrap_or_default().into(),
721		}
722	}
723}
724
725impl Eq for Number {}
726
727impl Ord for Number {
728	fn cmp(&self, other: &Self) -> Ordering {
729		fn total_cmp_f64(a: f64, b: f64) -> Ordering {
730			if a == 0.0 && b == 0.0 {
731				// -0.0 = 0.0
732				Ordering::Equal
733			} else {
734				// Handles NaN's
735				a.total_cmp(&b)
736			}
737		}
738
739		// Pick the greater number depending on whether it's positive.
740		macro_rules! greater {
741			($f:ident) => {
742				if $f.is_sign_positive() {
743					Ordering::Greater
744				} else {
745					Ordering::Less
746				}
747			};
748		}
749
750		match (self, other) {
751			(Number::Int(v), Number::Int(w)) => v.cmp(w),
752			(Number::Float(v), Number::Float(w)) => total_cmp_f64(*v, *w),
753			(Number::Decimal(v), Number::Decimal(w)) => v.cmp(w),
754			// ------------------------------
755			(Number::Int(v), Number::Float(w)) => {
756				// If the float is not finite, we don't need to compare it to the integer.
757				if !w.is_finite() {
758					return greater!(w).reverse();
759				}
760				// Cast int to i128 to avoid saturating.
761				let l = *v as i128;
762				// Cast the integer-part of the float to i128 to avoid saturating.
763				let r = *w as i128;
764				// Compare both integer parts.
765				match l.cmp(&r) {
766					// If the integer parts are equal then we need to compare the mantissa.
767					Ordering::Equal => total_cmp_f64(0.0, w.fract()),
768					// If the integer parts are not equal then we already know the correct ordering.
769					ordering => ordering,
770				}
771			}
772			(v @ Number::Float(_), w @ Number::Int(_)) => w.cmp(v).reverse(),
773			// ------------------------------
774			(Number::Int(v), Number::Decimal(w)) => Decimal::from(*v).cmp(w),
775			(Number::Decimal(v), Number::Int(w)) => v.cmp(&Decimal::from(*w)),
776			// ------------------------------
777			(Number::Float(v), Number::Decimal(w)) => {
778				// Compare fractional parts of the float and decimal.
779				macro_rules! compare_fractions {
780					($l:ident, $r:ident) => {
781						match ($l == 0.0, $r == Decimal::ZERO) {
782							// If both numbers are zero, these are equal.
783							(true, true) => {
784								return Ordering::Equal;
785							}
786							// If only the float is zero, check the decimal's sign.
787							(true, false) => {
788								return greater!($r).reverse();
789							}
790							// If only the decimal is zero, check the float's sign.
791							(false, true) => {
792								return greater!($l);
793							}
794							// If neither is zero, continue checking the rest of the digits.
795							(false, false) => {
796								continue;
797							}
798						}
799					};
800				}
801				// If the float is not finite, we don't need to compare it to the decimal
802				if !v.is_finite() {
803					return greater!(v);
804				}
805				// Cast int to i128 to avoid saturating.
806				let l = *v as i128;
807				// Cast the integer-part of the decimal to i128.
808				let Ok(r) = i128::try_from(*w) else {
809					return greater!(w).reverse();
810				};
811				// Compare both integer parts.
812				match l.cmp(&r) {
813					// If the integer parts are equal then we need to compare the fractional parts.
814					Ordering::Equal => {
815						// We can't compare the fractional parts of floats with decimals reliably.
816						// Instead, we need to compare them as integers. To do this, we need to
817						// multiply the fraction with a number large enough to move some digits
818						// to the integer part of the float or decimal. The number should fit in
819						// 52 bits and be able to multiply f64 fractions between -1 and 1 without
820						// losing precision. Since we may need to do this repeatedly it helps if
821						// the number is as big as possible to reduce the number of
822						// iterations needed.
823						//
824						// This number is roughly 2 ^ 53 with the last digits truncated in order
825						// to make sure the fraction converges to 0 every time we multiply it.
826						// This is a magic number I found through my experiments so don't ask me
827						// the logic behind it :) Before changing this number, please make sure
828						// that the relevant tests aren't flaky after changing it.
829						const SAFE_MULTIPLIER: i64 = 9_007_199_254_740_000;
830						// Get the fractional part of the float.
831						let mut l = v.fract();
832						// Get the fractional part of the decimal.
833						let mut r = w.fract();
834						// Move the digits and compare them.
835						// This is very generous. For example, for our tests to pass we only need
836						// 3 iterations. This should be at least 6 to make sure we cover all
837						// possible decimals and floats.
838						for _ in 0..12 {
839							l *= SAFE_MULTIPLIER as f64;
840							r *= Decimal::new(SAFE_MULTIPLIER, 0);
841							// Cast the integer part of the decimal to i64. The fractions are always
842							// less than 1 so we know this will always be less than SAFE_MULTIPLIER.
843							match r.to_i64() {
844								Some(ref right) => match (l as i64).cmp(right) {
845									// If the integer parts are equal, we need to check the
846									// remaining fractional parts.
847									Ordering::Equal => {
848										// Drop the integer parts we already compared.
849										l = l.fract();
850										r = r.fract();
851										// Compare the fractional parts and decide whether to return
852										// or continue checking the next digits.
853										compare_fractions!(l, r);
854									}
855									ordering => {
856										// If the integer parts are not equal then we already know
857										// the correct ordering.
858										return ordering;
859									}
860								},
861								// This is technically unreachable. Reaching this part likely
862								// indicates a bug in `rust-decimal`'s `to_f64`'s
863								// implementation.
864								None => {
865									// We will assume the decimal is bigger or smaller depending on
866									// its sign.
867									return greater!(w).reverse();
868								}
869							}
870						}
871						// After our iterations, if we still haven't exhausted both fractions we
872						// will just treat them as equal. It should be impossible to reach
873						// this point after at least 6 iterations. We could use an infinite
874						// loop instead but this way we make sure the loop always exits.
875						Ordering::Equal
876					}
877					// If the integer parts are not equal then we already know the correct ordering.
878					ordering => ordering,
879				}
880			}
881			(v @ Number::Decimal(..), w @ Number::Float(..)) => w.cmp(v).reverse(),
882		}
883	}
884}
885
886impl hash::Hash for Number {
887	/// # This hash does not satisfy the `Hash`/`Eq` contract
888	///
889	/// It hashes the decimal buffer encoding, so numerically-equal values with an
890	/// identical decimal expansion agree across variants — `Int(1)`, `Float(1.0)`
891	/// and `Decimal(1)` share a hash. But [`Number`]'s equality is *approximate*
892	/// between `Float` and `Decimal`: it agrees to roughly sixteen significant
893	/// digits and then calls it equal, so `Float(0.1) == Decimal("0.1")` while the
894	/// buffers differ, `D128::from_f64(0.1)` being
895	/// `0.1000000000000000055511151231257827`. (Going the other way,
896	/// `Float(0.11111) != Decimal("0.11111")` — the relation is not even
897	/// transitive across the boundary.)
898	///
899	/// So `a == b` does **not** imply `hash(a) == hash(b)`, and an approximate,
900	/// non-transitive equality admits no canonical form that would fix it. Any
901	/// `HashMap`/`HashSet` keyed on a [`Number`] — or on any value that can hold
902	/// one — will therefore miss entries it contains. Key such structures on `Ord`
903	/// instead, or treat a miss as inconclusive; see
904	/// [`Value::hash_agrees_with_eq`](crate::val::Value::hash_agrees_with_eq) for
905	/// deciding when a miss can still be trusted.
906	fn hash<H: hash::Hasher>(&self, state: &mut H) {
907		self.as_decimal_buf().hash(state);
908	}
909}
910
911impl PartialEq for Number {
912	fn eq(&self, other: &Self) -> bool {
913		fn total_eq_f64(a: f64, b: f64) -> bool {
914			a.to_bits().eq(&b.to_bits()) || (a == 0.0 && b == 0.0)
915		}
916
917		match (self, other) {
918			(Number::Int(v), Number::Int(w)) => v.eq(w),
919			(Number::Float(v), Number::Float(w)) => total_eq_f64(*v, *w),
920			(Number::Decimal(v), Number::Decimal(w)) => v.eq(w),
921			// ------------------------------
922			(v @ Number::Int(_), w @ Number::Float(_)) => v.cmp(w) == Ordering::Equal,
923			(v @ Number::Float(_), w @ Number::Int(_)) => v.cmp(w) == Ordering::Equal,
924			// ------------------------------
925			(Number::Int(v), Number::Decimal(w)) => Decimal::from(*v).eq(w),
926			(Number::Decimal(v), Number::Int(w)) => v.eq(&Decimal::from(*w)),
927			// ------------------------------
928			(v @ Number::Float(_), w @ Number::Decimal(_)) => v.cmp(w) == Ordering::Equal,
929			(v @ Number::Decimal(_), w @ Number::Float(_)) => v.cmp(w) == Ordering::Equal,
930		}
931	}
932}
933
934impl PartialOrd for Number {
935	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
936		Some(self.cmp(other))
937	}
938}
939
940macro_rules! impl_simple_try_op {
941	($trt:ident, $fn:ident, $unchecked:ident, $checked:ident) => {
942		impl $trt for Number {
943			type Output = Self;
944			fn $fn(self, other: Self) -> Result<Self> {
945				Ok(match (self, other) {
946					(Number::Int(v), Number::Int(w)) => Number::Int(
947						v.$checked(w).ok_or_else(|| Error::$trt(v.to_string(), w.to_string()))?,
948					),
949					(Number::Float(v), Number::Float(w)) => Number::Float(v.$unchecked(w)),
950					(Number::Decimal(v), Number::Decimal(w)) => Number::Decimal(
951						v.$checked(w).ok_or_else(|| Error::$trt(v.to_string(), w.to_string()))?,
952					),
953					(Number::Int(v), Number::Float(w)) => Number::Float((v as f64).$unchecked(w)),
954					(Number::Float(v), Number::Int(w)) => Number::Float(v.$unchecked(w as f64)),
955					(v, w) => Number::Decimal(
956						v.to_decimal()
957							.$checked(w.to_decimal())
958							.ok_or_else(|| Error::$trt(v.to_sql(), w.to_sql()))?,
959					),
960				})
961			}
962		}
963	};
964}
965
966impl_simple_try_op!(TryAdd, try_add, add, checked_add);
967impl_simple_try_op!(TrySub, try_sub, sub, checked_sub);
968impl_simple_try_op!(TryMul, try_mul, mul, checked_mul);
969impl_simple_try_op!(TryDiv, try_div, div, checked_div);
970impl_simple_try_op!(TryRem, try_rem, rem, checked_rem);
971
972impl TryPow for Number {
973	type Output = Self;
974	fn try_pow(self, power: Self) -> Result<Self> {
975		Ok(match (self, power) {
976			(Self::Int(v), Self::Int(p)) => Self::Int(match v {
977				0 => match p.cmp(&0) {
978					// 0^(-x)
979					Ordering::Less => bail!(Error::TryPow(v.to_string(), p.to_string())),
980					// 0^0
981					Ordering::Equal => 1,
982					// 0^x
983					Ordering::Greater => 0,
984				},
985				// 1^p
986				1 => 1,
987				-1 => {
988					if p % 2 == 0 {
989						// (-1)^even
990						1
991					} else {
992						// (-1)^odd
993						-1
994					}
995				}
996				// try_into may cause an error, which would be wrong for the above cases.
997				_ => p
998					.try_into()
999					.ok()
1000					.and_then(|p| v.checked_pow(p))
1001					.ok_or_else(|| Error::TryPow(v.to_string(), p.to_string()))?,
1002			}),
1003			(Self::Decimal(v), Self::Int(p)) => Self::Decimal(
1004				v.checked_powi(p).ok_or_else(|| Error::TryPow(v.to_string(), p.to_string()))?,
1005			),
1006			(Self::Decimal(v), Self::Float(p)) => Self::Decimal(
1007				v.checked_powf(p).ok_or_else(|| Error::TryPow(v.to_string(), p.to_string()))?,
1008			),
1009			(Self::Decimal(v), Self::Decimal(p)) => Self::Decimal(
1010				v.checked_powd(p).ok_or_else(|| Error::TryPow(v.to_string(), p.to_string()))?,
1011			),
1012			(v, p) => v.as_float().powf(p.as_float()).into(),
1013		})
1014	}
1015}
1016
1017impl TryNeg for Number {
1018	type Output = Self;
1019
1020	fn try_neg(self) -> Result<Self::Output> {
1021		Ok(match self {
1022			Self::Int(n) => {
1023				Number::Int(n.checked_neg().ok_or_else(|| Error::TryNeg(n.to_string()))?)
1024			}
1025			Self::Float(n) => Number::Float(-n),
1026			Self::Decimal(n) => Number::Decimal(-n),
1027		})
1028	}
1029}
1030
1031impl TryFloatDiv for Number {
1032	type Output = Self;
1033	fn try_float_div(self, other: Self) -> Result<Self> {
1034		Ok(match (self, other) {
1035			(Number::Int(v), Number::Int(w)) => {
1036				let quotient = (v as f64).div(w as f64);
1037				if quotient.fract() != 0.0 {
1038					return Ok(Number::Float(quotient));
1039				}
1040				Number::Int(
1041					v.checked_div(w).ok_or_else(|| Error::TryDiv(v.to_string(), w.to_string()))?,
1042				)
1043			}
1044			(v, w) => v.try_div(w)?,
1045		})
1046	}
1047}
1048
1049impl ops::Add for Number {
1050	type Output = Self;
1051	fn add(self, other: Self) -> Self {
1052		match (self, other) {
1053			(Number::Int(v), Number::Int(w)) => Number::Int(v + w),
1054			(Number::Float(v), Number::Float(w)) => Number::Float(v + w),
1055			(Number::Decimal(v), Number::Decimal(w)) => Number::Decimal(v + w),
1056			(Number::Int(v), Number::Float(w)) => Number::Float(v as f64 + w),
1057			(Number::Float(v), Number::Int(w)) => Number::Float(v + w as f64),
1058			(v, w) => Number::from(v.as_decimal() + w.as_decimal()),
1059		}
1060	}
1061}
1062
1063impl<'b> ops::Add<&'b Number> for &Number {
1064	type Output = Number;
1065	fn add(self, other: &'b Number) -> Number {
1066		match (self, other) {
1067			(Number::Int(v), Number::Int(w)) => Number::Int(v + w),
1068			(Number::Float(v), Number::Float(w)) => Number::Float(v + w),
1069			(Number::Decimal(v), Number::Decimal(w)) => Number::Decimal(v + w),
1070			(Number::Int(v), Number::Float(w)) => Number::Float(*v as f64 + w),
1071			(Number::Float(v), Number::Int(w)) => Number::Float(v + *w as f64),
1072			(v, w) => Number::from(v.to_decimal() + w.to_decimal()),
1073		}
1074	}
1075}
1076
1077impl ops::Sub for Number {
1078	type Output = Self;
1079	fn sub(self, other: Self) -> Self {
1080		match (self, other) {
1081			(Number::Int(v), Number::Int(w)) => Number::Int(v - w),
1082			(Number::Float(v), Number::Float(w)) => Number::Float(v - w),
1083			(Number::Decimal(v), Number::Decimal(w)) => Number::Decimal(v - w),
1084			(Number::Int(v), Number::Float(w)) => Number::Float(v as f64 - w),
1085			(Number::Float(v), Number::Int(w)) => Number::Float(v - w as f64),
1086			(v, w) => Number::from(v.as_decimal() - w.as_decimal()),
1087		}
1088	}
1089}
1090
1091impl<'b> ops::Sub<&'b Number> for &Number {
1092	type Output = Number;
1093	fn sub(self, other: &'b Number) -> Number {
1094		match (self, other) {
1095			(Number::Int(v), Number::Int(w)) => Number::Int(v - w),
1096			(Number::Float(v), Number::Float(w)) => Number::Float(v - w),
1097			(Number::Decimal(v), Number::Decimal(w)) => Number::Decimal(v - w),
1098			(Number::Int(v), Number::Float(w)) => Number::Float(*v as f64 - w),
1099			(Number::Float(v), Number::Int(w)) => Number::Float(v - *w as f64),
1100			(v, w) => Number::from(v.to_decimal() - w.to_decimal()),
1101		}
1102	}
1103}
1104
1105impl ops::Mul for Number {
1106	type Output = Self;
1107	fn mul(self, other: Self) -> Self {
1108		match (self, other) {
1109			(Number::Int(v), Number::Int(w)) => Number::Int(v * w),
1110			(Number::Float(v), Number::Float(w)) => Number::Float(v * w),
1111			(Number::Decimal(v), Number::Decimal(w)) => Number::Decimal(v * w),
1112			(Number::Int(v), Number::Float(w)) => Number::Float(v as f64 * w),
1113			(Number::Float(v), Number::Int(w)) => Number::Float(v * w as f64),
1114			(v, w) => Number::from(v.as_decimal() * w.as_decimal()),
1115		}
1116	}
1117}
1118
1119impl<'b> ops::Mul<&'b Number> for &Number {
1120	type Output = Number;
1121	fn mul(self, other: &'b Number) -> Number {
1122		match (self, other) {
1123			(Number::Int(v), Number::Int(w)) => Number::Int(v * w),
1124			(Number::Float(v), Number::Float(w)) => Number::Float(v * w),
1125			(Number::Decimal(v), Number::Decimal(w)) => Number::Decimal(v * w),
1126			(Number::Int(v), Number::Float(w)) => Number::Float(*v as f64 * w),
1127			(Number::Float(v), Number::Int(w)) => Number::Float(v * *w as f64),
1128			(v, w) => Number::from(v.to_decimal() * w.to_decimal()),
1129		}
1130	}
1131}
1132
1133impl ops::Div for Number {
1134	type Output = Self;
1135	fn div(self, other: Self) -> Self {
1136		match (self, other) {
1137			(Number::Int(v), Number::Int(w)) => Number::Int(v / w),
1138			(Number::Float(v), Number::Float(w)) => Number::Float(v / w),
1139			(Number::Decimal(v), Number::Decimal(w)) => Number::Decimal(v / w),
1140			(Number::Int(v), Number::Float(w)) => Number::Float(v as f64 / w),
1141			(Number::Float(v), Number::Int(w)) => Number::Float(v / w as f64),
1142			(v, w) => Number::from(v.as_decimal() / w.as_decimal()),
1143		}
1144	}
1145}
1146
1147impl<'b> ops::Div<&'b Number> for &Number {
1148	type Output = Number;
1149	fn div(self, other: &'b Number) -> Number {
1150		match (self, other) {
1151			(Number::Int(v), Number::Int(w)) => Number::Int(v / w),
1152			(Number::Float(v), Number::Float(w)) => Number::Float(v / w),
1153			(Number::Decimal(v), Number::Decimal(w)) => Number::Decimal(v / w),
1154			(Number::Int(v), Number::Float(w)) => Number::Float(*v as f64 / w),
1155			(Number::Float(v), Number::Int(w)) => Number::Float(v / *w as f64),
1156			(v, w) => Number::from(v.to_decimal() / w.to_decimal()),
1157		}
1158	}
1159}
1160
1161impl Neg for Number {
1162	type Output = Self;
1163
1164	fn neg(self) -> Self::Output {
1165		match self {
1166			Self::Int(n) => Number::Int(-n),
1167			Self::Float(n) => Number::Float(-n),
1168			Self::Decimal(n) => Number::Decimal(-n),
1169		}
1170	}
1171}
1172
1173// ------------------------------
1174
1175impl Sum<Self> for Number {
1176	fn sum<I>(iter: I) -> Number
1177	where
1178		I: Iterator<Item = Self>,
1179	{
1180		iter.fold(Number::Int(0), |a, b| a + b)
1181	}
1182}
1183
1184impl<'a> Sum<&'a Self> for Number {
1185	fn sum<I>(iter: I) -> Number
1186	where
1187		I: Iterator<Item = &'a Self>,
1188	{
1189		iter.fold(Number::Int(0), |a, b| &a + b)
1190	}
1191}
1192
1193impl Product<Self> for Number {
1194	fn product<I>(iter: I) -> Number
1195	where
1196		I: Iterator<Item = Self>,
1197	{
1198		iter.fold(Number::Int(1), |a, b| a * b)
1199	}
1200}
1201
1202impl<'a> Product<&'a Self> for Number {
1203	fn product<I>(iter: I) -> Number
1204	where
1205		I: Iterator<Item = &'a Self>,
1206	{
1207		iter.fold(Number::Int(1), |a, b| &a * b)
1208	}
1209}
1210
1211pub struct Sorted<T>(pub T);
1212
1213pub trait Sort {
1214	fn sorted(&mut self) -> Sorted<&Self>
1215	where
1216		Self: Sized;
1217}
1218
1219impl Sort for Vec<Number> {
1220	fn sorted(&mut self) -> Sorted<&Vec<Number>> {
1221		self.sort();
1222		Sorted(self)
1223	}
1224}
1225
1226impl ToFloat for Number {
1227	#[inline]
1228	fn to_float(&self) -> f64 {
1229		Number::to_float(*self)
1230	}
1231}
1232
1233impl Encode<()> for Number {
1234	fn encode<W: std::io::Write>(
1235		&self,
1236		w: &mut storekey::Writer<W>,
1237	) -> std::result::Result<(), storekey::EncodeError> {
1238		let slice = self.as_decimal_buf();
1239		w.write_slice(&slice)?;
1240		let kind = match self {
1241			Number::Int(_) => NumberKind::Int,
1242			Number::Float(_) => NumberKind::Float,
1243			Number::Decimal(_) => NumberKind::Decimal,
1244		};
1245		Encode::<()>::encode(&kind, w)?;
1246		Ok(())
1247	}
1248}
1249
1250impl<'de> BorrowDecode<'de, ()> for Number {
1251	fn borrow_decode(
1252		r: &mut storekey::BorrowReader<'de>,
1253	) -> std::result::Result<Self, storekey::DecodeError> {
1254		let slice = r.read_cow()?;
1255		let kind: NumberKind = BorrowDecode::<'de, ()>::borrow_decode(r)?;
1256		Number::from_decimal_buf_kind(slice.as_ref(), kind)
1257			.map_err(|_| storekey::DecodeError::InvalidFormat)
1258	}
1259}
1260
1261impl Encode<IndexFormat> for Number {
1262	fn encode<W: std::io::Write>(
1263		&self,
1264		w: &mut storekey::Writer<W>,
1265	) -> std::result::Result<(), storekey::EncodeError> {
1266		let slice = self.as_decimal_buf();
1267		w.write_slice(&slice)
1268	}
1269}
1270
1271impl<'de> BorrowDecode<'de, IndexFormat> for Number {
1272	fn borrow_decode(
1273		r: &mut storekey::BorrowReader<'de>,
1274	) -> std::result::Result<Self, storekey::DecodeError> {
1275		let slice = r.read_cow()?;
1276		Number::from_decimal_buf(slice.as_ref()).map_err(|_| storekey::DecodeError::InvalidFormat)
1277	}
1278}
1279
1280/// Conversion to `f64`. The implementations are marked `#[inline]` so that the
1281/// per-component loops of the vector functions, in other crates, compile them
1282/// into the loop whatever link-time optimisation decides.
1283pub trait ToFloat {
1284	fn to_float(&self) -> f64;
1285}
1286
1287impl ToFloat for f64 {
1288	#[inline]
1289	fn to_float(&self) -> f64 {
1290		*self
1291	}
1292}
1293
1294impl ToFloat for f32 {
1295	#[inline]
1296	fn to_float(&self) -> f64 {
1297		*self as f64
1298	}
1299}
1300
1301impl ToFloat for half::f16 {
1302	#[inline]
1303	fn to_float(&self) -> f64 {
1304		f64::from(*self)
1305	}
1306}
1307
1308impl ToFloat for i64 {
1309	#[inline]
1310	fn to_float(&self) -> f64 {
1311		*self as f64
1312	}
1313}
1314
1315impl ToFloat for i32 {
1316	#[inline]
1317	fn to_float(&self) -> f64 {
1318		*self as f64
1319	}
1320}
1321
1322impl ToFloat for i16 {
1323	#[inline]
1324	fn to_float(&self) -> f64 {
1325		*self as f64
1326	}
1327}
1328
1329impl ToFloat for i8 {
1330	#[inline]
1331	fn to_float(&self) -> f64 {
1332		*self as f64
1333	}
1334}
1335
1336impl ToFloat for u8 {
1337	#[inline]
1338	fn to_float(&self) -> f64 {
1339		*self as f64
1340	}
1341}
1342
1343#[cfg(test)]
1344mod tests {
1345	use std::cmp::Ordering;
1346
1347	use ahash::HashSet;
1348	use common::decimal::DecimalExt;
1349	use rand::Rng;
1350	use rand::seq::SliceRandom;
1351	use rust_decimal::Decimal;
1352	use rust_decimal::prelude::ToPrimitive;
1353
1354	use super::*;
1355
1356	#[test]
1357	fn test_decimal_ext_from_str_normalized() {
1358		let decimal = Decimal::from_str_normalized("0.0").unwrap();
1359		assert_eq!(decimal.to_string(), "0");
1360		assert_eq!(decimal.to_i64(), Some(0));
1361		assert_eq!(decimal.to_f64(), Some(0.0));
1362
1363		let decimal = Decimal::from_str_normalized("123.456").unwrap();
1364		assert_eq!(decimal.to_string(), "123.456");
1365		assert_eq!(decimal.to_i64(), Some(123));
1366		assert_eq!(decimal.to_f64(), Some(123.456));
1367
1368		let decimal =
1369			Decimal::from_str_normalized("13.5719384719384719385639856394139476937756394756")
1370				.unwrap();
1371		assert_eq!(decimal.to_string(), "13.571938471938471938563985639");
1372		assert_eq!(decimal.to_i64(), Some(13));
1373		assert_eq!(decimal.to_f64(), Some(13.571_938_471_938_472));
1374	}
1375
1376	#[test]
1377	fn test_try_float_div() {
1378		let (sum_one, count_one) = (Number::Int(5), Number::Int(2));
1379		assert_eq!(sum_one.try_float_div(count_one).unwrap(), Number::Float(2.5));
1380		// i64::MIN
1381
1382		let (sum_two, count_two) = (Number::Int(10), Number::Int(5));
1383		assert_eq!(sum_two.try_float_div(count_two).unwrap(), Number::Int(2));
1384
1385		let (sum_three, count_three) = (Number::Float(6.3), Number::Int(3));
1386		assert_eq!(sum_three.try_float_div(count_three).unwrap(), Number::Float(2.1));
1387	}
1388
1389	#[test]
1390	fn ord_test() {
1391		let a = Number::Float(-f64::NAN);
1392		let b = Number::Float(-f64::INFINITY);
1393		let c = Number::Float(1f64);
1394		let d = Number::Decimal(
1395			Decimal::from_str_normalized("1.0000000000000000000000000002").unwrap(),
1396		);
1397		let e = Number::Decimal(Decimal::from_str_normalized("1.1").unwrap());
1398		let f = Number::Float(1.1f64);
1399		let g = Number::Float(1.5f64);
1400		let h = Number::Decimal(Decimal::from_str_normalized("1.5").unwrap());
1401		let i = Number::Float(f64::INFINITY);
1402		let j = Number::Float(f64::NAN);
1403		let original = vec![a, b, c, d, e, f, g, h, i, j];
1404		let mut copy = original.clone();
1405		let mut rng = rand::rng();
1406		copy.shuffle(&mut rng);
1407		copy.sort();
1408		assert_eq!(original, copy);
1409	}
1410
1411	#[test]
1412	fn ord_fuzz() {
1413		fn random_number() -> Number {
1414			let mut rng = rand::rng();
1415			match rng.random_range(0..3) {
1416				0 => Number::Int(rng.random()),
1417				1 => Number::Float(f64::from_bits(rng.random())),
1418				_ => Number::Decimal(Number::Float(f64::from_bits(rng.random())).as_decimal()),
1419			}
1420		}
1421
1422		fn random_permutation(number: Number) -> Number {
1423			let mut rng = rand::rng();
1424			let value = match rng.random_range(0..4) {
1425				0 => number + Number::from(rng.random::<f64>()),
1426				1 if !matches!(number, Number::Int(i64::MIN)) => number * Number::from(-1),
1427				2 => Number::Float(number.as_float().next_down()),
1428				_ => number,
1429			};
1430			match rng.random_range(0..3) {
1431				0 => Number::Int(value.as_int()),
1432				1 => Number::Float(value.as_float()),
1433				_ => Number::Decimal(value.as_decimal()),
1434			}
1435		}
1436
1437		fn assert_partial_ord(x: Number, y: Number) {
1438			// PartialOrd requirements
1439			assert_eq!(x == y, x.partial_cmp(&y) == Some(Ordering::Equal), "{x:?} {y:?}");
1440
1441			// Ord consistent with PartialOrd
1442			assert_eq!(x.partial_cmp(&y), Some(x.cmp(&y)), "{x:?} {y:?}");
1443		}
1444
1445		fn assert_consistent(a: Number, b: Number, c: Number) {
1446			assert_partial_ord(a, b);
1447			assert_partial_ord(b, c);
1448			assert_partial_ord(c, a);
1449
1450			// Transitive property (without the fix, these can fail)
1451			if a == b && b == c {
1452				assert_eq!(a, c, "{a:?} {b:?} {c:?}");
1453			}
1454			if a != b && b == c {
1455				assert_ne!(a, c, "{a:?} {b:?} {c:?}");
1456			}
1457			if a < b && b < c {
1458				assert!(a < c, "{a:?} {b:?} {c:?}");
1459			}
1460			if a > b && b > c {
1461				assert!(a > c, "{a:?} {b:?} {c:?}");
1462			}
1463
1464			// Duality
1465			assert_eq!(a == b, b == a, "{a:?} {b:?}");
1466			assert_eq!(a < b, b > a, "{a:?} {b:?}");
1467		}
1468
1469		for _ in 0..100000 {
1470			let base = random_number();
1471			let a = random_permutation(base);
1472			let b = random_permutation(a);
1473			let c = random_permutation(b);
1474			assert_consistent(a, b, c);
1475		}
1476	}
1477
1478	#[test]
1479	fn serialised_ord_test() {
1480		let ordering = [
1481			Number::from(f64::NEG_INFINITY),
1482			Number::from(f64::MIN),
1483			Number::Int(i64::MIN),
1484			Number::from(-1000),
1485			Number::from(-100),
1486			Number::from(-10),
1487			Number::from(-1.5),
1488			Number::from(-1),
1489			Number::from(0),
1490			Number::from(1),
1491			Number::from(1.5),
1492			Number::from(2),
1493			Number::from(10),
1494			Number::from(100),
1495			Number::from(1000),
1496			Number::from(i64::MAX),
1497			Number::from(f64::MAX),
1498			Number::from(f64::INFINITY),
1499			Number::from(f64::NAN),
1500		];
1501		for window in ordering.windows(2) {
1502			let n1 = &window[0];
1503			let n2 = &window[1];
1504			assert!(n1 < n2, "{n1:?} < {n2:?} (before serialization)");
1505			let b1 = n1.as_decimal_buf();
1506			let b2 = n2.as_decimal_buf();
1507			assert!(b1 < b2, "{n1:?} < {n2:?} (after serialization) - {b1:?} < {b2:?}");
1508			let r1 = Number::from_decimal_buf(&b1).unwrap();
1509			let r2 = Number::from_decimal_buf(&b2).unwrap();
1510			assert!(r1.eq(n1), "{r1:?} = {n1:?} (after deserialization)");
1511			assert!(r2.eq(n2), "{r2:?} = {n2:?} (after deserialization)");
1512		}
1513	}
1514
1515	#[test]
1516	fn serialised_test() {
1517		let check = |numbers: &[Number]| {
1518			let mut buffers = HashSet::default();
1519			for n1 in numbers {
1520				let b = n1.as_decimal_buf();
1521				let n2 = Number::from_decimal_buf(&b).unwrap();
1522				buffers.insert(b);
1523				assert!(n1.eq(&n2), "{n1:?} = {n2:?} (after deserialization)");
1524			}
1525			assert_eq!(buffers.len(), 1, "{numbers:?}");
1526		};
1527		check(&[Number::Int(0), Number::Float(0.0), Number::Decimal(Decimal::ZERO)]);
1528		check(&[Number::Int(1), Number::Float(1.0), Number::Decimal(Decimal::ONE)]);
1529		check(&[Number::Int(-1), Number::Float(-1.0), Number::Decimal(Decimal::NEGATIVE_ONE)]);
1530		check(&[Number::Float(1.5), Number::Decimal(Decimal::from_str_normalized("1.5").unwrap())]);
1531	}
1532
1533	#[test]
1534	fn as_int_lossless_accepts_valid() {
1535		assert_eq!(Number::Int(0).as_int_lossless(), Some(0));
1536		assert_eq!(Number::Int(i64::MIN).as_int_lossless(), Some(i64::MIN));
1537		assert_eq!(Number::Int(i64::MAX).as_int_lossless(), Some(i64::MAX));
1538		assert_eq!(Number::Float(0.0).as_int_lossless(), Some(0));
1539		assert_eq!(Number::Float(-0.0).as_int_lossless(), Some(0));
1540		assert_eq!(Number::Float(7.0).as_int_lossless(), Some(7));
1541		// `i64::MIN` is exactly representable as `f64` and is the inclusive lower bound.
1542		assert_eq!(Number::Float(i64::MIN as f64).as_int_lossless(), Some(i64::MIN));
1543		assert_eq!(Number::Decimal(Decimal::ZERO).as_int_lossless(), Some(0));
1544		assert_eq!(Number::Decimal(Decimal::ONE).as_int_lossless(), Some(1));
1545		assert_eq!(Number::Decimal(Decimal::NEGATIVE_ONE).as_int_lossless(), Some(-1));
1546	}
1547
1548	#[test]
1549	fn as_int_lossless_rejects_invalid() {
1550		assert_eq!(Number::Float(1.5).as_int_lossless(), None);
1551		assert_eq!(Number::Float(-1.5).as_int_lossless(), None);
1552		assert_eq!(Number::Float(f64::NAN).as_int_lossless(), None);
1553		assert_eq!(Number::Float(f64::INFINITY).as_int_lossless(), None);
1554		assert_eq!(Number::Float(f64::NEG_INFINITY).as_int_lossless(), None);
1555		// `i64::MAX as f64` rounds up to 2^63, which is *not* in `i64` range —
1556		// the exclusive upper bound is `-(i64::MIN as f64)`.
1557		assert_eq!(Number::Float(i64::MAX as f64).as_int_lossless(), None);
1558		assert_eq!(Number::Float(1e30).as_int_lossless(), None);
1559		assert_eq!(Number::Float(-1e30).as_int_lossless(), None);
1560		assert_eq!(
1561			Number::Decimal(Decimal::from_str_normalized("1.5").unwrap()).as_int_lossless(),
1562			None,
1563		);
1564	}
1565
1566	#[test]
1567	fn as_array_index_accepts_valid() {
1568		assert_eq!(Number::Int(0).as_array_index(), Some(0));
1569		assert_eq!(Number::Int(7).as_array_index(), Some(7));
1570		assert_eq!(Number::Float(0.0).as_array_index(), Some(0));
1571		assert_eq!(Number::Float(-0.0).as_array_index(), Some(0));
1572		assert_eq!(Number::Float(3.0).as_array_index(), Some(3));
1573		assert_eq!(Number::Decimal(Decimal::ZERO).as_array_index(), Some(0));
1574		assert_eq!(Number::Decimal(Decimal::ONE).as_array_index(), Some(1));
1575	}
1576
1577	#[test]
1578	fn as_array_index_rejects_invalid() {
1579		assert_eq!(Number::Int(-1).as_array_index(), None);
1580		assert_eq!(Number::Int(i64::MIN).as_array_index(), None);
1581		assert_eq!(Number::Float(-1.0).as_array_index(), None);
1582		assert_eq!(Number::Float(1.5).as_array_index(), None);
1583		assert_eq!(Number::Float(f64::NAN).as_array_index(), None);
1584		assert_eq!(Number::Float(f64::INFINITY).as_array_index(), None);
1585		assert_eq!(Number::Float(f64::NEG_INFINITY).as_array_index(), None);
1586		// 1e30 is far beyond usize::MAX and not exactly representable as usize.
1587		assert_eq!(Number::Float(1e30).as_array_index(), None);
1588		assert_eq!(Number::Decimal(Decimal::NEGATIVE_ONE).as_array_index(), None);
1589		assert_eq!(
1590			Number::Decimal(Decimal::from_str_normalized("1.5").unwrap()).as_array_index(),
1591			None,
1592		);
1593	}
1594
1595	#[test]
1596	fn fixed_int_is_unchanged_regardless_of_precision() {
1597		assert_eq!(Number::Int(101).fixed(0), Number::Int(101));
1598		assert_eq!(Number::Int(101).fixed(2), Number::Int(101));
1599		assert_eq!(Number::Int(101).fixed(319), Number::Int(101));
1600		assert_eq!(Number::Int(-7).fixed(5), Number::Int(-7));
1601	}
1602
1603	#[test]
1604	fn fixed_float_rounds_to_requested_precision() {
1605		assert_eq!(Number::Float(101.5).fixed(2), Number::Float(101.5));
1606		assert_eq!(Number::Float(101.1111111).fixed(2), Number::Float(101.11));
1607		// Subnormal at precision past f64's significant-digit range: the
1608		// trailing digits get truncated, producing a smaller-but-finite
1609		// neighbour rather than 0, inf, or NaN.
1610		assert_eq!(
1611			Number::Float(2.2250738585072014e-308).fixed(319),
1612			Number::Float(2.22507385851e-308),
1613		);
1614	}
1615
1616	#[test]
1617	fn fixed_float_preserves_non_finite() {
1618		// The Float arm relies on `format!`/`parse` round-tripping every
1619		// f64 — including NaN and ±inf. Pin that invariant here so a future
1620		// change to the formatter cannot silently break the `expect` in
1621		// `Number::fixed`.
1622		let Number::Float(nan) = Number::Float(f64::NAN).fixed(2) else {
1623			panic!("expected Number::Float(NaN)");
1624		};
1625		assert!(nan.is_nan());
1626		assert_eq!(Number::Float(f64::INFINITY).fixed(2), Number::Float(f64::INFINITY));
1627		assert_eq!(Number::Float(f64::NEG_INFINITY).fixed(2), Number::Float(f64::NEG_INFINITY));
1628	}
1629
1630	#[test]
1631	fn fixed_decimal_uses_round_dp() {
1632		let d = Decimal::from_str_normalized("1.2345").unwrap();
1633		assert_eq!(
1634			Number::Decimal(d).fixed(2),
1635			Number::Decimal(Decimal::from_str_normalized("1.23").unwrap()),
1636		);
1637	}
1638}