1use 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 }
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
76from_prim_ints!(i8, i16, i32, i64, isize, u8, u16, u32);
80
81impl 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 Self::from(i as u64)
97 }
98}
99
100impl 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 match s.parse::<i64>() {
172 Ok(v) => Ok(Self::Int(v)),
174 _ => match s.parse::<f64>() {
176 Ok(v) => Ok(Self::Float(v)),
178 _ => Err(()),
180 },
181 }
182 }
183}
184
185macro_rules! try_into_prim {
186 ($($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 Some(special) => write_sql!(f, sql_fmt, "{}", special),
253 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 pub const NAN: Number = Number::Float(f64::NAN);
268
269 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 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 pub fn as_int_lossless(self) -> Option<i64> {
345 match self {
346 Number::Int(v) => Some(v),
347 Number::Float(v) => {
348 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 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 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 #[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 pub fn as_decimal_buf(&self) -> Vec<u8> {
452 match self {
453 Self::Int(v) => {
454 DecimalLexEncoder::encode(D128::from(*v))
456 }
457 Self::Float(v) => {
458 DecimalLexEncoder::encode(D128::from_f64(*v))
460 }
461 Self::Decimal(v) => {
462 DecimalLexEncoder::encode(DecimalLexEncoder::to_d128(*v))
464 }
465 }
466 }
467
468 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 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 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 Ordering::Equal
733 } else {
734 a.total_cmp(&b)
736 }
737 }
738
739 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 (Number::Int(v), Number::Float(w)) => {
756 if !w.is_finite() {
758 return greater!(w).reverse();
759 }
760 let l = *v as i128;
762 let r = *w as i128;
764 match l.cmp(&r) {
766 Ordering::Equal => total_cmp_f64(0.0, w.fract()),
768 ordering => ordering,
770 }
771 }
772 (v @ Number::Float(_), w @ Number::Int(_)) => w.cmp(v).reverse(),
773 (Number::Int(v), Number::Decimal(w)) => Decimal::from(*v).cmp(w),
775 (Number::Decimal(v), Number::Int(w)) => v.cmp(&Decimal::from(*w)),
776 (Number::Float(v), Number::Decimal(w)) => {
778 macro_rules! compare_fractions {
780 ($l:ident, $r:ident) => {
781 match ($l == 0.0, $r == Decimal::ZERO) {
782 (true, true) => {
784 return Ordering::Equal;
785 }
786 (true, false) => {
788 return greater!($r).reverse();
789 }
790 (false, true) => {
792 return greater!($l);
793 }
794 (false, false) => {
796 continue;
797 }
798 }
799 };
800 }
801 if !v.is_finite() {
803 return greater!(v);
804 }
805 let l = *v as i128;
807 let Ok(r) = i128::try_from(*w) else {
809 return greater!(w).reverse();
810 };
811 match l.cmp(&r) {
813 Ordering::Equal => {
815 const SAFE_MULTIPLIER: i64 = 9_007_199_254_740_000;
830 let mut l = v.fract();
832 let mut r = w.fract();
834 for _ in 0..12 {
839 l *= SAFE_MULTIPLIER as f64;
840 r *= Decimal::new(SAFE_MULTIPLIER, 0);
841 match r.to_i64() {
844 Some(ref right) => match (l as i64).cmp(right) {
845 Ordering::Equal => {
848 l = l.fract();
850 r = r.fract();
851 compare_fractions!(l, r);
854 }
855 ordering => {
856 return ordering;
859 }
860 },
861 None => {
865 return greater!(w).reverse();
868 }
869 }
870 }
871 Ordering::Equal
876 }
877 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 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 (v @ Number::Int(_), w @ Number::Float(_)) => v.cmp(w) == Ordering::Equal,
923 (v @ Number::Float(_), w @ Number::Int(_)) => v.cmp(w) == Ordering::Equal,
924 (Number::Int(v), Number::Decimal(w)) => Decimal::from(*v).eq(w),
926 (Number::Decimal(v), Number::Int(w)) => v.eq(&Decimal::from(*w)),
927 (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 Ordering::Less => bail!(Error::TryPow(v.to_string(), p.to_string())),
980 Ordering::Equal => 1,
982 Ordering::Greater => 0,
984 },
985 1 => 1,
987 -1 => {
988 if p % 2 == 0 {
989 1
991 } else {
992 -1
994 }
995 }
996 _ => 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
1173impl 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
1280pub 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 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 assert_eq!(x == y, x.partial_cmp(&y) == Some(Ordering::Equal), "{x:?} {y:?}");
1440
1441 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 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 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 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 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 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 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 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}