surrealdb-core 3.2.0

A scalable, distributed, collaborative, document-graph database, for the realtime web
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
//! Numeric value type used throughout SurrealDB.
//!
//! This module defines Number, a discriminated union over Int (i64), Float (f64),
//! and Decimal (rust_decimal::Decimal), and implements arithmetic, comparison,
//! and conversions. For storage in index keys, Numbers are serialized with a
//! canonical, lexicographic encoding (via expr::decimal::DecimalLexEncoder)
//! so that byte-wise ordering matches numeric ordering and numerically-equal
//! values across variants normalize to identical bytes.
//!
//! Key points:
//! - Ordering: PartialOrd/Ord behavior aims to reflect mathematical ordering across variants; for
//!   index keys we rely on DecimalLexEncoder to preserve ordering at the byte level.
//! - Normalization in keys: 0 (Int), 0.0 (Float) and 0dec (Decimal) encode to the same byte
//!   sequence for keys, so UNIQUE indexes treat them as equal.
//! - Special float values: NaN, +∞ and −∞ are given fixed encodings that fit in the total ordering
//!   used by keys (see DecimalLexEncoder docs).
//! - Stream-friendly: the numeric encoding contains an in-band terminator and appends a 0x00 byte,
//!   allowing concatenation in composite keys without ambiguity during decoding.

use std::cmp::Ordering;
use std::f64::consts::PI;
use std::fmt::{self, Debug, Display, Formatter};
use std::hash;
use std::iter::{Product, Sum};
use std::ops::{self, Add, Div, Mul, Neg, Rem, Sub};
use std::str::FromStr;

use anyhow::{Result, bail, ensure};
use fastnum::D128;
use revision::revisioned;
use rust_decimal::Decimal;
use rust_decimal::prelude::*;
use storekey::{BorrowDecode, Encode};
use surrealdb_types::{SqlFormat, ToSql, fmt_non_finite_f64, write_sql};

use super::IndexFormat;
use crate::err::Error;
use crate::expr::decimal::DecimalLexEncoder;
use crate::fnc::util::math::ToFloat;
use crate::val::{TryAdd, TryDiv, TryFloatDiv, TryMul, TryNeg, TryPow, TryRem, TrySub};

#[derive(Copy, Clone, Encode, BorrowDecode)]
pub(crate) enum NumberKind {
	Int,
	Float,
	Decimal,
}

#[revisioned(revision = 1)]
#[derive(Clone, Copy, Debug)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub(crate) enum Number {
	Int(i64),
	Float(f64),
	Decimal(Decimal),
	// Add new variants here
}

impl Default for Number {
	fn default() -> Self {
		Self::Int(0)
	}
}

macro_rules! from_prim_ints {
	($($int: ty),*) => {
		$(
			impl From<$int> for Number {
				fn from(i: $int) -> Self {
					Self::Int(i as i64)
				}
			}
		)*
	};
}

// Only integer types that always fit losslessly into an i64 are converted
// infallibly here. Wider types are handled below so they store the value
// correctly (as a Decimal when it exceeds i64) instead of truncating.
from_prim_ints!(i8, i16, i32, i64, isize, u8, u16, u32);

// `u64`/`usize` can exceed i64::MAX but always fit within Decimal's 96-bit
// mantissa, so the conversion is lossless and infallible: store as an Int when
// it fits, otherwise as a Decimal.
impl From<u64> for Number {
	fn from(i: u64) -> Self {
		match i64::try_from(i) {
			Ok(v) => Self::Int(v),
			Err(_) => Self::Decimal(Decimal::from(i)),
		}
	}
}

impl From<usize> for Number {
	fn from(i: usize) -> Self {
		// usize is at most 64 bits wide on every supported target.
		Self::from(i as u64)
	}
}

// `i128`/`u128` can exceed Decimal's range (2^96), so the conversion is
// fallible: store as an Int when it fits in i64, otherwise as a Decimal, and
// error rather than silently truncate when the value is too large for either.
impl TryFrom<i128> for Number {
	type Error = Error;
	fn try_from(i: i128) -> Result<Self, Self::Error> {
		if let Ok(v) = i64::try_from(i) {
			Ok(Self::Int(v))
		} else if let Some(v) = Decimal::from_i128(i) {
			Ok(Self::Decimal(v))
		} else {
			Err(Error::TryFrom(i.to_string(), "Number"))
		}
	}
}

impl TryFrom<u128> for Number {
	type Error = Error;
	fn try_from(i: u128) -> Result<Self, Self::Error> {
		if let Ok(v) = i64::try_from(i) {
			Ok(Self::Int(v))
		} else if let Some(v) = Decimal::from_u128(i) {
			Ok(Self::Decimal(v))
		} else {
			Err(Error::TryFrom(i.to_string(), "Number"))
		}
	}
}

impl From<f32> for Number {
	fn from(f: f32) -> Self {
		Self::Float(f as f64)
	}
}

impl From<f64> for Number {
	fn from(f: f64) -> Self {
		Self::Float(f)
	}
}

impl From<Decimal> for Number {
	fn from(v: Decimal) -> Self {
		Self::Decimal(v)
	}
}

impl From<surrealdb_types::Number> for Number {
	fn from(v: surrealdb_types::Number) -> Self {
		match v {
			surrealdb_types::Number::Int(i) => Self::Int(i),
			surrealdb_types::Number::Float(f) => Self::Float(f),
			surrealdb_types::Number::Decimal(d) => Self::Decimal(d),
		}
	}
}

impl From<Number> for surrealdb_types::Number {
	fn from(v: Number) -> Self {
		match v {
			Number::Int(i) => Self::Int(i),
			Number::Float(f) => Self::Float(f),
			Number::Decimal(d) => Self::Decimal(d),
		}
	}
}

impl FromStr for Number {
	type Err = ();
	fn from_str(s: &str) -> Result<Self, Self::Err> {
		// Attempt to parse as i64
		match s.parse::<i64>() {
			// Store it as an i64
			Ok(v) => Ok(Self::Int(v)),
			// It wasn't parsed as a i64 so parse as a float
			_ => match s.parse::<f64>() {
				// Store it as a float
				Ok(v) => Ok(Self::Float(v)),
				// It wasn't parsed as a number
				_ => Err(()),
			},
		}
	}
}

macro_rules! try_into_prim {
	// TODO: switch to one argument per int once https://github.com/rust-lang/rust/issues/29599 is stable
	($($int: ty => $to_int: ident),*) => {
		$(
			impl TryFrom<Number> for $int {
				type Error = Error;
				fn try_from(value: Number) -> Result<Self, Self::Error> {
					match value {
						Number::Int(v) => match v.$to_int() {
							Some(v) => Ok(v),
							None => Err(Error::TryFrom(value.to_sql(), stringify!($int))),
						},
						Number::Float(v) => match v.$to_int() {
							Some(v) => Ok(v),
							None => Err(Error::TryFrom(value.to_sql(), stringify!($int))),
						},
						Number::Decimal(ref v) => match v.$to_int() {
							Some(v) => Ok(v),
							None => Err(Error::TryFrom(value.to_sql(), stringify!($int))),
						},
					}
				}
			}
		)*
	};
}

try_into_prim!(
	i8 => to_i8, i16 => to_i16, i32 => to_i32, i64 => to_i64, i128 => to_i128,
	u8 => to_u8, u16 => to_u16, u32 => to_u32, u64 => to_u64, u128 => to_u128,
	f32 => to_f32, f64 => to_f64
);

impl TryFrom<Number> for Decimal {
	type Error = Error;
	fn try_from(value: Number) -> Result<Self, Self::Error> {
		match value {
			Number::Int(v) => match Decimal::from_i64(v) {
				Some(v) => Ok(v),
				None => Err(Error::TryFrom(value.to_sql(), "Decimal")),
			},
			Number::Float(v) => match Decimal::try_from(v) {
				Ok(v) => Ok(v),
				_ => Err(Error::TryFrom(value.to_sql(), "Decimal")),
			},
			Number::Decimal(x) => Ok(x),
		}
	}
}

impl Display for Number {
	fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
		match self {
			Number::Int(v) => Display::fmt(v, f),
			Number::Float(v) => Display::fmt(v, f),
			Number::Decimal(v) => Display::fmt(v, f),
		}
	}
}

impl ToSql for Number {
	fn fmt_sql(&self, f: &mut String, sql_fmt: SqlFormat) {
		match self {
			Number::Int(v) => v.fmt_sql(f, sql_fmt),
			Number::Float(v) => {
				match fmt_non_finite_f64(*v) {
					// Special case: Infinity, -Infinity or NaN
					Some(special) => write_sql!(f, sql_fmt, "{}", special),
					// Regular float: add f to distinguish between int and float
					None => write_sql!(f, sql_fmt, "{v}f"),
				}
			}
			Number::Decimal(v) => v.fmt_sql(f, sql_fmt),
		}
	}
}

impl Number {
	// -----------------------------------
	// Constants
	// -----------------------------------

	pub const NAN: Number = Number::Float(f64::NAN);

	// -----------------------------------
	// Simple number detection
	// -----------------------------------

	pub fn is_nan(&self) -> bool {
		matches!(self, Number::Float(v) if v.is_nan())
	}

	pub fn is_int(&self) -> bool {
		matches!(self, Number::Int(_))
	}

	pub fn is_float(&self) -> bool {
		matches!(self, Number::Float(_))
	}

	pub fn is_truthy(&self) -> bool {
		match self {
			Number::Int(v) => v != &0,
			Number::Float(v) => v != &0.0,
			Number::Decimal(v) => v != &Decimal::ZERO,
		}
	}

	pub fn is_zero(&self) -> bool {
		match self {
			Number::Int(v) => v == &0,
			Number::Float(v) => v == &0.0,
			Number::Decimal(v) => v == &Decimal::ZERO,
		}
	}

	// -----------------------------------
	// Simple conversion of number
	// -----------------------------------

	pub fn as_usize(self) -> usize {
		match self {
			Number::Int(v) => v as usize,
			Number::Float(v) => v as usize,
			Number::Decimal(v) => v.try_into().unwrap_or_default(),
		}
	}

	pub fn as_int(self) -> i64 {
		match self {
			Number::Int(v) => v,
			Number::Float(v) => v as i64,
			Number::Decimal(v) => v.try_into().unwrap_or_default(),
		}
	}

	pub fn as_float(self) -> f64 {
		match self {
			Number::Int(v) => v as f64,
			Number::Float(v) => v,
			Number::Decimal(v) => v.try_into().unwrap_or_default(),
		}
	}

	pub fn as_decimal(self) -> Decimal {
		match self {
			Number::Int(v) => Decimal::from(v),
			Number::Float(v) => Decimal::try_from(v).unwrap_or_default(),
			Number::Decimal(v) => v,
		}
	}

	// -----------------------------------
	// Complex conversion of number
	// -----------------------------------

	/// Convert to an `i64` only when the value round-trips exactly.
	///
	/// Returns `None` for any value that does not represent an exact integer
	/// within `i64` range — including NaN, infinities, fractional values, and
	/// out-of-range magnitudes. Lossy `as` casts (which saturate or truncate
	/// silently) are deliberately avoided so callers can reject the input
	/// rather than write a wrong value.
	pub fn as_int_lossless(self) -> Option<i64> {
		match self {
			Number::Int(v) => Some(v),
			Number::Float(v) => {
				// `i64::MAX as f64` rounds up to 2^63 (the next representable
				// f64), which is *not* in i64 range. `-(i64::MIN as f64)` is
				// exactly 2^63 and is the right exclusive upper bound.
				if !v.is_finite()
					|| v.fract() != 0.0
					|| v < i64::MIN as f64
					|| v >= -(i64::MIN as f64)
				{
					return None;
				}
				Some(v as i64)
			}
			Number::Decimal(v) => {
				if v.fract().is_zero() {
					v.try_into().ok()
				} else {
					None
				}
			}
		}
	}

	/// Convert to a `usize` suitable for array indexing.
	///
	/// Returns `None` for any value that does not represent an exact
	/// non-negative integer within `usize` range — including negatives,
	/// NaN, infinities, fractional values, and out-of-range magnitudes.
	pub fn as_array_index(self) -> Option<usize> {
		match self {
			Number::Int(v) => usize::try_from(v).ok(),
			Number::Float(v) => {
				if !v.is_finite() || v < 0.0 || v.fract() != 0.0 {
					return None;
				}
				// `f64 as usize` saturates above `usize::MAX`; round-trip back
				// through f64 to reject any value that couldn't be represented
				// exactly.
				let idx = v as usize;
				(idx as f64 == v).then_some(idx)
			}
			Number::Decimal(v) => {
				if v.fract().is_zero() {
					v.to_usize()
				} else {
					None
				}
			}
		}
	}

	pub fn to_int(self) -> i64 {
		match self {
			Number::Int(v) => v,
			Number::Float(v) => v as i64,
			Number::Decimal(v) => v.to_i64().unwrap_or_default(),
		}
	}

	pub fn to_float(self) -> f64 {
		match self {
			Number::Int(v) => v as f64,
			Number::Float(v) => v,
			Number::Decimal(v) => v.try_into().unwrap_or_default(),
		}
	}

	pub fn to_decimal(self) -> Decimal {
		match self {
			Number::Int(v) => Decimal::from(v),
			Number::Float(v) => Decimal::from_f64(v).unwrap_or_default(),
			Number::Decimal(v) => v,
		}
	}

	/// Converts this Number to a lexicographically ordered byte buffer.
	///
	/// This serializes the Number using DecimalLexEncoder so that byte-wise
	/// comparison preserves numeric ordering. This is essential for database
	/// indexes where key bytes must sort the same way as their numeric values.
	///
	/// Ordering guarantees:
	/// - If `a < b` numerically, then `a.as_decimal_buf() < b.as_decimal_buf()` lexicographically.
	///
	/// Encoding format:
	/// - A leading class/marker byte indicates zero, finite negative, finite positive, negative
	///   infinity, positive infinity, or NaN.
	/// - Two bytes encode a biased scale for finite values.
	/// - Packed base-10 digits follow (2 digits per byte), with an in-band terminator ensured by
	///   the packing scheme; the encoder also appends a trailing 0x00 terminator byte for
	///   stream-friendly decoding.
	///
	/// Notes:
	/// - There is no extra "type marker" for Int/Float/Decimal variants; all variants are
	///   normalized through D128 for ordering.
	/// - Special float values (NaN/±∞) are mapped to fixed encodings at the extremes to preserve a
	///   total order.
	///
	/// Returns an ordered byte buffer or an error if Decimal conversion fails
	/// for Decimal variant values.
	pub(crate) fn as_decimal_buf(&self) -> Vec<u8> {
		match self {
			Self::Int(v) => {
				// Convert integer to decimal for consistent encoding across all numeric types
				DecimalLexEncoder::encode(D128::from(*v))
			}
			Self::Float(v) => {
				// Convert float to decimal for lexicographic encoding
				DecimalLexEncoder::encode(D128::from_f64(*v))
			}
			Self::Decimal(v) => {
				// Direct encoding of decimal values using lexicographic encoder
				DecimalLexEncoder::encode(DecimalLexEncoder::to_d128(*v))
			}
		}
	}

	/// Reconstructs a Number from a lexicographically ordered byte buffer.
	///
	/// This deserializes a buffer produced by `as_decimal_buf()` using
	/// DecimalLexEncoder, recovering the numeric value. All Number variants are
	/// normalized through the same encoding, so the original variant (Int/Float/
	/// Decimal) is not preserved; only the value (and special cases like NaN/±∞)
	/// matters for ordering and equality in keys.
	///
	/// The decoder recognizes:
	/// - Zero, finite negatives, finite positives (via marker and biased scale)
	/// - Negative/positive infinity, NaN (fixed encodings)
	/// - An explicit in-band terminator added by the encoder, which ensures the mantissa decoder
	///   stops before any following data in the stream.
	///
	/// Returns the reconstructed Number or an error if the buffer is empty or
	/// cannot be decoded.
	pub(crate) fn from_decimal_buf(b: &[u8]) -> Result<Self> {
		let dec = DecimalLexEncoder::decode(b)?;
		if dec.is_finite() {
			match DecimalLexEncoder::to_decimal(dec) {
				Ok(dec) => Ok(Number::Decimal(dec)),
				Err(_) => Ok(Number::Float(dec.to_f64())),
			}
		} else if dec.is_nan() {
			Ok(Number::Float(f64::NAN))
		} else if dec.is_infinite() {
			if dec.is_negative() {
				Ok(Number::Float(f64::NEG_INFINITY))
			} else {
				Ok(Number::Float(f64::INFINITY))
			}
		} else {
			bail!(Error::Serialization(format!("Invalid decimal value: {dec}")))
		}
	}

	pub(crate) fn from_decimal_buf_kind(b: &[u8], kind: NumberKind) -> Result<Self> {
		let dec = DecimalLexEncoder::decode(b)?;
		match kind {
			NumberKind::Int => {
				ensure!(dec.is_finite(), format!("Invalid integer value: {dec}"));
				Ok(Number::Int(dec.to_string().parse::<i64>()?))
			}
			NumberKind::Float => {
				if dec.is_nan() {
					Ok(Number::Float(f64::NAN))
				} else if dec.is_infinite() {
					if dec.is_negative() {
						Ok(Number::Float(f64::NEG_INFINITY))
					} else {
						Ok(Number::Float(f64::INFINITY))
					}
				} else {
					let dec = DecimalLexEncoder::to_decimal(dec)?;
					dec.to_f64()
						.ok_or_else(|| anyhow::Error::msg(format!("Invalid f64 {dec}")))
						.map(Number::Float)
				}
			}
			NumberKind::Decimal => {
				ensure!(dec.is_finite(), format!("Invalid integer value: {dec}"));
				Ok(Number::Decimal(DecimalLexEncoder::to_decimal(dec)?))
			}
		}
	}

	// -----------------------------------
	//
	// -----------------------------------

	pub fn abs(self) -> Self {
		match self {
			Number::Int(v) => v.abs().into(),
			Number::Float(v) => v.abs().into(),
			Number::Decimal(v) => v.abs().into(),
		}
	}

	pub fn checked_abs(self) -> Option<Self> {
		match self {
			Number::Int(v) => v.checked_abs().map(|x| x.into()),
			Number::Float(v) => Some(v.abs().into()),
			Number::Decimal(v) => Some(v.abs().into()),
		}
	}

	pub fn acos(self) -> Self {
		self.to_float().acos().into()
	}

	pub fn asin(self) -> Self {
		self.to_float().asin().into()
	}

	pub fn atan(self) -> Self {
		self.to_float().atan().into()
	}

	pub fn acot(self) -> Self {
		(PI / 2.0 - self.atan().to_float()).into()
	}

	pub fn ceil(self) -> Self {
		match self {
			Number::Int(v) => v.into(),
			Number::Float(v) => v.ceil().into(),
			Number::Decimal(v) => v.ceil().into(),
		}
	}

	pub fn clamp(self, min: Self, max: Self) -> Self {
		match (self, min, max) {
			(Number::Int(n), Number::Int(min), Number::Int(max)) => n.clamp(min, max).into(),
			(Number::Decimal(n), min, max) => n.clamp(min.to_decimal(), max.to_decimal()).into(),
			(Number::Float(n), min, max) => n.clamp(min.to_float(), max.to_float()).into(),
			(Number::Int(n), min, max) => n.to_float().clamp(min.to_float(), max.to_float()).into(),
		}
	}

	pub fn cos(self) -> Self {
		self.to_float().cos().into()
	}

	pub fn cot(self) -> Self {
		(1.0 / self.to_float().tan()).into()
	}

	pub fn deg2rad(self) -> Self {
		self.to_float().to_radians().into()
	}

	pub fn floor(self) -> Self {
		match self {
			Number::Int(v) => v.into(),
			Number::Float(v) => v.floor().into(),
			Number::Decimal(v) => v.floor().into(),
		}
	}

	fn lerp_f64(from: f64, to: f64, factor: f64) -> f64 {
		from + factor * (to - from)
	}

	fn lerp_decimal(from: Decimal, to: Decimal, factor: Decimal) -> Decimal {
		from + factor * (to - from)
	}

	pub fn lerp(self, from: Self, to: Self) -> Self {
		match (self, from, to) {
			(Number::Decimal(val), from, to) => {
				Self::lerp_decimal(from.to_decimal(), to.to_decimal(), val).into()
			}
			(val, from, to) => {
				Self::lerp_f64(from.to_float(), to.to_float(), val.to_float()).into()
			}
		}
	}

	fn repeat_f64(t: f64, m: f64) -> f64 {
		(t - (t / m).floor() * m).clamp(0.0, m)
	}

	fn repeat_decimal(t: Decimal, m: Decimal) -> Decimal {
		(t - (t / m).floor() * m).clamp(Decimal::ZERO, m)
	}

	pub fn lerp_angle(self, from: Self, to: Self) -> Self {
		match (self, from, to) {
			(Number::Decimal(val), from, to) => {
				let from = from.to_decimal();
				let to = to.to_decimal();
				let mut dt = Self::repeat_decimal(to - from, Decimal::from(360));
				if dt > Decimal::from(180) {
					dt = Decimal::from(360) - dt;
				}
				Self::lerp_decimal(from, from + dt, val).into()
			}
			(val, from, to) => {
				let val = val.to_float();
				let from = from.to_float();
				let to = to.to_float();
				let mut dt = Self::repeat_f64(to - from, 360.0);
				if dt > 180.0 {
					dt = 360.0 - dt;
				}
				Self::lerp_f64(from, from + dt, val).into()
			}
		}
	}

	pub fn ln(self) -> Self {
		self.to_float().ln().into()
	}

	pub fn log(self, base: Self) -> Self {
		self.to_float().log(base.to_float()).into()
	}

	pub fn log2(self) -> Self {
		self.to_float().log2().into()
	}

	pub fn log10(self) -> Self {
		self.to_float().log10().into()
	}

	pub fn rad2deg(self) -> Self {
		self.to_float().to_degrees().into()
	}

	pub fn round(self) -> Self {
		match self {
			Number::Int(v) => v.into(),
			Number::Float(v) => v.round().into(),
			Number::Decimal(v) => v.round().into(),
		}
	}

	pub fn fixed(self, precision: usize) -> Number {
		match self {
			Number::Int(v) => v.into(),
			// Truncate via the formatter so subnormals and very large
			// magnitudes (which would overflow a `10^precision` multiplier)
			// stay representable; non-finite f64s round-trip too.
			Number::Float(v) => format!("{v:.precision$}")
				.parse::<f64>()
				.expect("formatted f64 always parses back as f64")
				.into(),
			Number::Decimal(v) => v.round_dp(precision as u32).into(),
		}
	}

	pub fn sign(self) -> Self {
		match self {
			Number::Int(n) => n.signum().into(),
			Number::Float(n) => n.signum().into(),
			Number::Decimal(n) => n.signum().into(),
		}
	}

	pub fn sin(self) -> Self {
		self.to_float().sin().into()
	}

	pub fn tan(self) -> Self {
		self.to_float().tan().into()
	}

	pub fn sqrt(self) -> Self {
		match self {
			Number::Int(v) => (v as f64).sqrt().into(),
			Number::Float(v) => v.sqrt().into(),
			Number::Decimal(v) => v.sqrt().unwrap_or_default().into(),
		}
	}
}

impl Eq for Number {}

impl Ord for Number {
	fn cmp(&self, other: &Self) -> Ordering {
		fn total_cmp_f64(a: f64, b: f64) -> Ordering {
			if a == 0.0 && b == 0.0 {
				// -0.0 = 0.0
				Ordering::Equal
			} else {
				// Handles NaN's
				a.total_cmp(&b)
			}
		}

		// Pick the greater number depending on whether it's positive.
		macro_rules! greater {
			($f:ident) => {
				if $f.is_sign_positive() {
					Ordering::Greater
				} else {
					Ordering::Less
				}
			};
		}

		match (self, other) {
			(Number::Int(v), Number::Int(w)) => v.cmp(w),
			(Number::Float(v), Number::Float(w)) => total_cmp_f64(*v, *w),
			(Number::Decimal(v), Number::Decimal(w)) => v.cmp(w),
			// ------------------------------
			(Number::Int(v), Number::Float(w)) => {
				// If the float is not finite, we don't need to compare it to the integer.
				if !w.is_finite() {
					return greater!(w).reverse();
				}
				// Cast int to i128 to avoid saturating.
				let l = *v as i128;
				// Cast the integer-part of the float to i128 to avoid saturating.
				let r = *w as i128;
				// Compare both integer parts.
				match l.cmp(&r) {
					// If the integer parts are equal then we need to compare the mantissa.
					Ordering::Equal => total_cmp_f64(0.0, w.fract()),
					// If the integer parts are not equal then we already know the correct ordering.
					ordering => ordering,
				}
			}
			(v @ Number::Float(_), w @ Number::Int(_)) => w.cmp(v).reverse(),
			// ------------------------------
			(Number::Int(v), Number::Decimal(w)) => Decimal::from(*v).cmp(w),
			(Number::Decimal(v), Number::Int(w)) => v.cmp(&Decimal::from(*w)),
			// ------------------------------
			(Number::Float(v), Number::Decimal(w)) => {
				// Compare fractional parts of the float and decimal.
				macro_rules! compare_fractions {
					($l:ident, $r:ident) => {
						match ($l == 0.0, $r == Decimal::ZERO) {
							// If both numbers are zero, these are equal.
							(true, true) => {
								return Ordering::Equal;
							}
							// If only the float is zero, check the decimal's sign.
							(true, false) => {
								return greater!($r).reverse();
							}
							// If only the decimal is zero, check the float's sign.
							(false, true) => {
								return greater!($l);
							}
							// If neither is zero, continue checking the rest of the digits.
							(false, false) => {
								continue;
							}
						}
					};
				}
				// If the float is not finite, we don't need to compare it to the decimal
				if !v.is_finite() {
					return greater!(v);
				}
				// Cast int to i128 to avoid saturating.
				let l = *v as i128;
				// Cast the integer-part of the decimal to i128.
				let Ok(r) = i128::try_from(*w) else {
					return greater!(w).reverse();
				};
				// Compare both integer parts.
				match l.cmp(&r) {
					// If the integer parts are equal then we need to compare the fractional parts.
					Ordering::Equal => {
						// We can't compare the fractional parts of floats with decimals reliably.
						// Instead, we need to compare them as integers. To do this, we need to
						// multiply the fraction with a number large enough to move some digits
						// to the integer part of the float or decimal. The number should fit in
						// 52 bits and be able to multiply f64 fractions between -1 and 1 without
						// losing precision. Since we may need to do this repeatedly it helps if
						// the number is as big as possible to reduce the number of
						// iterations needed.
						//
						// This number is roughly 2 ^ 53 with the last digits truncated in order
						// to make sure the fraction converges to 0 every time we multiply it.
						// This is a magic number I found through my experiments so don't ask me
						// the logic behind it :) Before changing this number, please make sure
						// that the relevant tests aren't flaky after changing it.
						const SAFE_MULTIPLIER: i64 = 9_007_199_254_740_000;
						// Get the fractional part of the float.
						let mut l = v.fract();
						// Get the fractional part of the decimal.
						let mut r = w.fract();
						// Move the digits and compare them.
						// This is very generous. For example, for our tests to pass we only need
						// 3 iterations. This should be at least 6 to make sure we cover all
						// possible decimals and floats.
						for _ in 0..12 {
							l *= SAFE_MULTIPLIER as f64;
							r *= Decimal::new(SAFE_MULTIPLIER, 0);
							// Cast the integer part of the decimal to i64. The fractions are always
							// less than 1 so we know this will always be less than SAFE_MULTIPLIER.
							match r.to_i64() {
								Some(ref right) => match (l as i64).cmp(right) {
									// If the integer parts are equal, we need to check the
									// remaining fractional parts.
									Ordering::Equal => {
										// Drop the integer parts we already compared.
										l = l.fract();
										r = r.fract();
										// Compare the fractional parts and decide whether to return
										// or continue checking the next digits.
										compare_fractions!(l, r);
									}
									ordering => {
										// If the integer parts are not equal then we already know
										// the correct ordering.
										return ordering;
									}
								},
								// This is technically unreachable. Reaching this part likely
								// indicates a bug in `rust-decimal`'s `to_f64`'s
								// implementation.
								None => {
									// We will assume the decimal is bigger or smaller depending on
									// its sign.
									return greater!(w).reverse();
								}
							}
						}
						// After our iterations, if we still haven't exhausted both fractions we
						// will just treat them as equal. It should be impossible to reach
						// this point after at least 6 iterations. We could use an infinite
						// loop instead but this way we make sure the loop always exits.
						Ordering::Equal
					}
					// If the integer parts are not equal then we already know the correct ordering.
					ordering => ordering,
				}
			}
			(v @ Number::Decimal(..), w @ Number::Float(..)) => w.cmp(v).reverse(),
		}
	}
}

impl hash::Hash for Number {
	fn hash<H: hash::Hasher>(&self, state: &mut H) {
		// Use decimal buffer encoding to ensure numerically-equal values
		// across variants (Int/Float/Decimal) produce identical hashes.
		// This maintains the Hash/Eq contract: if a == b, then hash(a) == hash(b).
		self.as_decimal_buf().hash(state);
	}
}

impl PartialEq for Number {
	fn eq(&self, other: &Self) -> bool {
		fn total_eq_f64(a: f64, b: f64) -> bool {
			a.to_bits().eq(&b.to_bits()) || (a == 0.0 && b == 0.0)
		}

		match (self, other) {
			(Number::Int(v), Number::Int(w)) => v.eq(w),
			(Number::Float(v), Number::Float(w)) => total_eq_f64(*v, *w),
			(Number::Decimal(v), Number::Decimal(w)) => v.eq(w),
			// ------------------------------
			(v @ Number::Int(_), w @ Number::Float(_)) => v.cmp(w) == Ordering::Equal,
			(v @ Number::Float(_), w @ Number::Int(_)) => v.cmp(w) == Ordering::Equal,
			// ------------------------------
			(Number::Int(v), Number::Decimal(w)) => Decimal::from(*v).eq(w),
			(Number::Decimal(v), Number::Int(w)) => v.eq(&Decimal::from(*w)),
			// ------------------------------
			(v @ Number::Float(_), w @ Number::Decimal(_)) => v.cmp(w) == Ordering::Equal,
			(v @ Number::Decimal(_), w @ Number::Float(_)) => v.cmp(w) == Ordering::Equal,
		}
	}
}

impl PartialOrd for Number {
	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
		Some(self.cmp(other))
	}
}

macro_rules! impl_simple_try_op {
	($trt:ident, $fn:ident, $unchecked:ident, $checked:ident) => {
		impl $trt for Number {
			type Output = Self;
			fn $fn(self, other: Self) -> Result<Self> {
				Ok(match (self, other) {
					(Number::Int(v), Number::Int(w)) => Number::Int(
						v.$checked(w).ok_or_else(|| Error::$trt(v.to_string(), w.to_string()))?,
					),
					(Number::Float(v), Number::Float(w)) => Number::Float(v.$unchecked(w)),
					(Number::Decimal(v), Number::Decimal(w)) => Number::Decimal(
						v.$checked(w).ok_or_else(|| Error::$trt(v.to_string(), w.to_string()))?,
					),
					(Number::Int(v), Number::Float(w)) => Number::Float((v as f64).$unchecked(w)),
					(Number::Float(v), Number::Int(w)) => Number::Float(v.$unchecked(w as f64)),
					(v, w) => Number::Decimal(
						v.to_decimal()
							.$checked(w.to_decimal())
							.ok_or_else(|| Error::$trt(v.to_sql(), w.to_sql()))?,
					),
				})
			}
		}
	};
}

impl_simple_try_op!(TryAdd, try_add, add, checked_add);
impl_simple_try_op!(TrySub, try_sub, sub, checked_sub);
impl_simple_try_op!(TryMul, try_mul, mul, checked_mul);
impl_simple_try_op!(TryDiv, try_div, div, checked_div);
impl_simple_try_op!(TryRem, try_rem, rem, checked_rem);

impl TryPow for Number {
	type Output = Self;
	fn try_pow(self, power: Self) -> Result<Self> {
		Ok(match (self, power) {
			(Self::Int(v), Self::Int(p)) => Self::Int(match v {
				0 => match p.cmp(&0) {
					// 0^(-x)
					Ordering::Less => bail!(Error::TryPow(v.to_string(), p.to_string())),
					// 0^0
					Ordering::Equal => 1,
					// 0^x
					Ordering::Greater => 0,
				},
				// 1^p
				1 => 1,
				-1 => {
					if p % 2 == 0 {
						// (-1)^even
						1
					} else {
						// (-1)^odd
						-1
					}
				}
				// try_into may cause an error, which would be wrong for the above cases.
				_ => p
					.try_into()
					.ok()
					.and_then(|p| v.checked_pow(p))
					.ok_or_else(|| Error::TryPow(v.to_string(), p.to_string()))?,
			}),
			(Self::Decimal(v), Self::Int(p)) => Self::Decimal(
				v.checked_powi(p).ok_or_else(|| Error::TryPow(v.to_string(), p.to_string()))?,
			),
			(Self::Decimal(v), Self::Float(p)) => Self::Decimal(
				v.checked_powf(p).ok_or_else(|| Error::TryPow(v.to_string(), p.to_string()))?,
			),
			(Self::Decimal(v), Self::Decimal(p)) => Self::Decimal(
				v.checked_powd(p).ok_or_else(|| Error::TryPow(v.to_string(), p.to_string()))?,
			),
			(v, p) => v.as_float().powf(p.as_float()).into(),
		})
	}
}

impl TryNeg for Number {
	type Output = Self;

	fn try_neg(self) -> Result<Self::Output> {
		Ok(match self {
			Self::Int(n) => {
				Number::Int(n.checked_neg().ok_or_else(|| Error::TryNeg(n.to_string()))?)
			}
			Self::Float(n) => Number::Float(-n),
			Self::Decimal(n) => Number::Decimal(-n),
		})
	}
}

impl TryFloatDiv for Number {
	type Output = Self;
	fn try_float_div(self, other: Self) -> Result<Self> {
		Ok(match (self, other) {
			(Number::Int(v), Number::Int(w)) => {
				let quotient = (v as f64).div(w as f64);
				if quotient.fract() != 0.0 {
					return Ok(Number::Float(quotient));
				}
				Number::Int(
					v.checked_div(w).ok_or_else(|| Error::TryDiv(v.to_string(), w.to_string()))?,
				)
			}
			(v, w) => v.try_div(w)?,
		})
	}
}

impl ops::Add for Number {
	type Output = Self;
	fn add(self, other: Self) -> Self {
		match (self, other) {
			(Number::Int(v), Number::Int(w)) => Number::Int(v + w),
			(Number::Float(v), Number::Float(w)) => Number::Float(v + w),
			(Number::Decimal(v), Number::Decimal(w)) => Number::Decimal(v + w),
			(Number::Int(v), Number::Float(w)) => Number::Float(v as f64 + w),
			(Number::Float(v), Number::Int(w)) => Number::Float(v + w as f64),
			(v, w) => Number::from(v.as_decimal() + w.as_decimal()),
		}
	}
}

impl<'b> ops::Add<&'b Number> for &Number {
	type Output = Number;
	fn add(self, other: &'b Number) -> Number {
		match (self, other) {
			(Number::Int(v), Number::Int(w)) => Number::Int(v + w),
			(Number::Float(v), Number::Float(w)) => Number::Float(v + w),
			(Number::Decimal(v), Number::Decimal(w)) => Number::Decimal(v + w),
			(Number::Int(v), Number::Float(w)) => Number::Float(*v as f64 + w),
			(Number::Float(v), Number::Int(w)) => Number::Float(v + *w as f64),
			(v, w) => Number::from(v.to_decimal() + w.to_decimal()),
		}
	}
}

impl ops::Sub for Number {
	type Output = Self;
	fn sub(self, other: Self) -> Self {
		match (self, other) {
			(Number::Int(v), Number::Int(w)) => Number::Int(v - w),
			(Number::Float(v), Number::Float(w)) => Number::Float(v - w),
			(Number::Decimal(v), Number::Decimal(w)) => Number::Decimal(v - w),
			(Number::Int(v), Number::Float(w)) => Number::Float(v as f64 - w),
			(Number::Float(v), Number::Int(w)) => Number::Float(v - w as f64),
			(v, w) => Number::from(v.as_decimal() - w.as_decimal()),
		}
	}
}

impl<'b> ops::Sub<&'b Number> for &Number {
	type Output = Number;
	fn sub(self, other: &'b Number) -> Number {
		match (self, other) {
			(Number::Int(v), Number::Int(w)) => Number::Int(v - w),
			(Number::Float(v), Number::Float(w)) => Number::Float(v - w),
			(Number::Decimal(v), Number::Decimal(w)) => Number::Decimal(v - w),
			(Number::Int(v), Number::Float(w)) => Number::Float(*v as f64 - w),
			(Number::Float(v), Number::Int(w)) => Number::Float(v - *w as f64),
			(v, w) => Number::from(v.to_decimal() - w.to_decimal()),
		}
	}
}

impl ops::Mul for Number {
	type Output = Self;
	fn mul(self, other: Self) -> Self {
		match (self, other) {
			(Number::Int(v), Number::Int(w)) => Number::Int(v * w),
			(Number::Float(v), Number::Float(w)) => Number::Float(v * w),
			(Number::Decimal(v), Number::Decimal(w)) => Number::Decimal(v * w),
			(Number::Int(v), Number::Float(w)) => Number::Float(v as f64 * w),
			(Number::Float(v), Number::Int(w)) => Number::Float(v * w as f64),
			(v, w) => Number::from(v.as_decimal() * w.as_decimal()),
		}
	}
}

impl<'b> ops::Mul<&'b Number> for &Number {
	type Output = Number;
	fn mul(self, other: &'b Number) -> Number {
		match (self, other) {
			(Number::Int(v), Number::Int(w)) => Number::Int(v * w),
			(Number::Float(v), Number::Float(w)) => Number::Float(v * w),
			(Number::Decimal(v), Number::Decimal(w)) => Number::Decimal(v * w),
			(Number::Int(v), Number::Float(w)) => Number::Float(*v as f64 * w),
			(Number::Float(v), Number::Int(w)) => Number::Float(v * *w as f64),
			(v, w) => Number::from(v.to_decimal() * w.to_decimal()),
		}
	}
}

impl ops::Div for Number {
	type Output = Self;
	fn div(self, other: Self) -> Self {
		match (self, other) {
			(Number::Int(v), Number::Int(w)) => Number::Int(v / w),
			(Number::Float(v), Number::Float(w)) => Number::Float(v / w),
			(Number::Decimal(v), Number::Decimal(w)) => Number::Decimal(v / w),
			(Number::Int(v), Number::Float(w)) => Number::Float(v as f64 / w),
			(Number::Float(v), Number::Int(w)) => Number::Float(v / w as f64),
			(v, w) => Number::from(v.as_decimal() / w.as_decimal()),
		}
	}
}

impl<'b> ops::Div<&'b Number> for &Number {
	type Output = Number;
	fn div(self, other: &'b Number) -> Number {
		match (self, other) {
			(Number::Int(v), Number::Int(w)) => Number::Int(v / w),
			(Number::Float(v), Number::Float(w)) => Number::Float(v / w),
			(Number::Decimal(v), Number::Decimal(w)) => Number::Decimal(v / w),
			(Number::Int(v), Number::Float(w)) => Number::Float(*v as f64 / w),
			(Number::Float(v), Number::Int(w)) => Number::Float(v / *w as f64),
			(v, w) => Number::from(v.to_decimal() / w.to_decimal()),
		}
	}
}

impl Neg for Number {
	type Output = Self;

	fn neg(self) -> Self::Output {
		match self {
			Self::Int(n) => Number::Int(-n),
			Self::Float(n) => Number::Float(-n),
			Self::Decimal(n) => Number::Decimal(-n),
		}
	}
}

// ------------------------------

impl Sum<Self> for Number {
	fn sum<I>(iter: I) -> Number
	where
		I: Iterator<Item = Self>,
	{
		iter.fold(Number::Int(0), |a, b| a + b)
	}
}

impl<'a> Sum<&'a Self> for Number {
	fn sum<I>(iter: I) -> Number
	where
		I: Iterator<Item = &'a Self>,
	{
		iter.fold(Number::Int(0), |a, b| &a + b)
	}
}

impl Product<Self> for Number {
	fn product<I>(iter: I) -> Number
	where
		I: Iterator<Item = Self>,
	{
		iter.fold(Number::Int(1), |a, b| a * b)
	}
}

impl<'a> Product<&'a Self> for Number {
	fn product<I>(iter: I) -> Number
	where
		I: Iterator<Item = &'a Self>,
	{
		iter.fold(Number::Int(1), |a, b| &a * b)
	}
}

pub struct Sorted<T>(pub T);

pub trait Sort {
	fn sorted(&mut self) -> Sorted<&Self>
	where
		Self: Sized;
}

impl Sort for Vec<Number> {
	fn sorted(&mut self) -> Sorted<&Vec<Number>> {
		self.sort();
		Sorted(self)
	}
}

impl ToFloat for Number {
	fn to_float(&self) -> f64 {
		Number::to_float(*self)
	}
}

impl Encode<()> for Number {
	fn encode<W: std::io::Write>(
		&self,
		w: &mut storekey::Writer<W>,
	) -> std::result::Result<(), storekey::EncodeError> {
		let slice = self.as_decimal_buf();
		w.write_slice(&slice)?;
		let kind = match self {
			Number::Int(_) => NumberKind::Int,
			Number::Float(_) => NumberKind::Float,
			Number::Decimal(_) => NumberKind::Decimal,
		};
		Encode::<()>::encode(&kind, w)?;
		Ok(())
	}
}

impl<'de> BorrowDecode<'de, ()> for Number {
	fn borrow_decode(
		r: &mut storekey::BorrowReader<'de>,
	) -> std::result::Result<Self, storekey::DecodeError> {
		let slice = r.read_cow()?;
		let kind: NumberKind = BorrowDecode::<'de, ()>::borrow_decode(r)?;
		Number::from_decimal_buf_kind(slice.as_ref(), kind)
			.map_err(|_| storekey::DecodeError::InvalidFormat)
	}
}

impl Encode<IndexFormat> for Number {
	fn encode<W: std::io::Write>(
		&self,
		w: &mut storekey::Writer<W>,
	) -> std::result::Result<(), storekey::EncodeError> {
		let slice = self.as_decimal_buf();
		w.write_slice(&slice)
	}
}

impl<'de> BorrowDecode<'de, IndexFormat> for Number {
	fn borrow_decode(
		r: &mut storekey::BorrowReader<'de>,
	) -> std::result::Result<Self, storekey::DecodeError> {
		let slice = r.read_cow()?;
		Number::from_decimal_buf(slice.as_ref()).map_err(|_| storekey::DecodeError::InvalidFormat)
	}
}

/// A trait to extend the Decimal type with additional functionality.
pub trait DecimalExt {
	/// Converts a string to a Decimal, normalizing it in the process.
	///
	/// This method is a convenience wrapper around
	/// `rust_decimal::Decimal::from_str` which can parse a string into a
	/// Decimal and normalize it. If the value has higher precision than the
	/// Decimal type can handle, it will be rounded to the
	/// nearest representable value.
	fn from_str_normalized(s: &str) -> Result<Self, rust_decimal::Error>
	where
		Self: Sized;
}

impl DecimalExt for Decimal {
	fn from_str_normalized(s: &str) -> Result<Decimal, rust_decimal::Error> {
		#[allow(clippy::disallowed_methods)]
		Ok(Decimal::from_str(s)?.normalize())
	}
}

#[cfg(test)]
mod tests {
	use std::cmp::Ordering;

	use ahash::HashSet;
	use rand::Rng;
	use rand::seq::SliceRandom;
	use rust_decimal::Decimal;
	use rust_decimal::prelude::ToPrimitive;

	use super::*;

	#[test]
	fn test_decimal_ext_from_str_normalized() {
		let decimal = Decimal::from_str_normalized("0.0").unwrap();
		assert_eq!(decimal.to_string(), "0");
		assert_eq!(decimal.to_i64(), Some(0));
		assert_eq!(decimal.to_f64(), Some(0.0));

		let decimal = Decimal::from_str_normalized("123.456").unwrap();
		assert_eq!(decimal.to_string(), "123.456");
		assert_eq!(decimal.to_i64(), Some(123));
		assert_eq!(decimal.to_f64(), Some(123.456));

		let decimal =
			Decimal::from_str_normalized("13.5719384719384719385639856394139476937756394756")
				.unwrap();
		assert_eq!(decimal.to_string(), "13.571938471938471938563985639");
		assert_eq!(decimal.to_i64(), Some(13));
		assert_eq!(decimal.to_f64(), Some(13.571_938_471_938_472));
	}

	#[test]
	fn test_try_float_div() {
		let (sum_one, count_one) = (Number::Int(5), Number::Int(2));
		assert_eq!(sum_one.try_float_div(count_one).unwrap(), Number::Float(2.5));
		// i64::MIN

		let (sum_two, count_two) = (Number::Int(10), Number::Int(5));
		assert_eq!(sum_two.try_float_div(count_two).unwrap(), Number::Int(2));

		let (sum_three, count_three) = (Number::Float(6.3), Number::Int(3));
		assert_eq!(sum_three.try_float_div(count_three).unwrap(), Number::Float(2.1));
	}

	#[test]
	fn ord_test() {
		let a = Number::Float(-f64::NAN);
		let b = Number::Float(-f64::INFINITY);
		let c = Number::Float(1f64);
		let d = Number::Decimal(
			Decimal::from_str_normalized("1.0000000000000000000000000002").unwrap(),
		);
		let e = Number::Decimal(Decimal::from_str_normalized("1.1").unwrap());
		let f = Number::Float(1.1f64);
		let g = Number::Float(1.5f64);
		let h = Number::Decimal(Decimal::from_str_normalized("1.5").unwrap());
		let i = Number::Float(f64::INFINITY);
		let j = Number::Float(f64::NAN);
		let original = vec![a, b, c, d, e, f, g, h, i, j];
		let mut copy = original.clone();
		let mut rng = rand::rng();
		copy.shuffle(&mut rng);
		copy.sort();
		assert_eq!(original, copy);
	}

	#[test]
	fn ord_fuzz() {
		fn random_number() -> Number {
			let mut rng = rand::rng();
			match rng.random_range(0..3) {
				0 => Number::Int(rng.random()),
				1 => Number::Float(f64::from_bits(rng.random())),
				_ => Number::Decimal(Number::Float(f64::from_bits(rng.random())).as_decimal()),
			}
		}

		fn random_permutation(number: Number) -> Number {
			let mut rng = rand::rng();
			let value = match rng.random_range(0..4) {
				0 => number + Number::from(rng.random::<f64>()),
				1 if !matches!(number, Number::Int(i64::MIN)) => number * Number::from(-1),
				2 => Number::Float(number.as_float().next_down()),
				_ => number,
			};
			match rng.random_range(0..3) {
				0 => Number::Int(value.as_int()),
				1 => Number::Float(value.as_float()),
				_ => Number::Decimal(value.as_decimal()),
			}
		}

		fn assert_partial_ord(x: Number, y: Number) {
			// PartialOrd requirements
			assert_eq!(x == y, x.partial_cmp(&y) == Some(Ordering::Equal), "{x:?} {y:?}");

			// Ord consistent with PartialOrd
			assert_eq!(x.partial_cmp(&y), Some(x.cmp(&y)), "{x:?} {y:?}");
		}

		fn assert_consistent(a: Number, b: Number, c: Number) {
			assert_partial_ord(a, b);
			assert_partial_ord(b, c);
			assert_partial_ord(c, a);

			// Transitive property (without the fix, these can fail)
			if a == b && b == c {
				assert_eq!(a, c, "{a:?} {b:?} {c:?}");
			}
			if a != b && b == c {
				assert_ne!(a, c, "{a:?} {b:?} {c:?}");
			}
			if a < b && b < c {
				assert!(a < c, "{a:?} {b:?} {c:?}");
			}
			if a > b && b > c {
				assert!(a > c, "{a:?} {b:?} {c:?}");
			}

			// Duality
			assert_eq!(a == b, b == a, "{a:?} {b:?}");
			assert_eq!(a < b, b > a, "{a:?} {b:?}");
		}

		for _ in 0..100000 {
			let base = random_number();
			let a = random_permutation(base);
			let b = random_permutation(a);
			let c = random_permutation(b);
			assert_consistent(a, b, c);
		}
	}

	#[test]
	fn serialised_ord_test() {
		let ordering = [
			Number::from(f64::NEG_INFINITY),
			Number::from(f64::MIN),
			Number::Int(i64::MIN),
			Number::from(-1000),
			Number::from(-100),
			Number::from(-10),
			Number::from(-1.5),
			Number::from(-1),
			Number::from(0),
			Number::from(1),
			Number::from(1.5),
			Number::from(2),
			Number::from(10),
			Number::from(100),
			Number::from(1000),
			Number::from(i64::MAX),
			Number::from(f64::MAX),
			Number::from(f64::INFINITY),
			Number::from(f64::NAN),
		];
		for window in ordering.windows(2) {
			let n1 = &window[0];
			let n2 = &window[1];
			assert!(n1 < n2, "{n1:?} < {n2:?} (before serialization)");
			let b1 = n1.as_decimal_buf();
			let b2 = n2.as_decimal_buf();
			assert!(b1 < b2, "{n1:?} < {n2:?} (after serialization) - {b1:?} < {b2:?}");
			let r1 = Number::from_decimal_buf(&b1).unwrap();
			let r2 = Number::from_decimal_buf(&b2).unwrap();
			assert!(r1.eq(n1), "{r1:?} = {n1:?} (after deserialization)");
			assert!(r2.eq(n2), "{r2:?} = {n2:?} (after deserialization)");
		}
	}

	#[test]
	fn serialised_test() {
		let check = |numbers: &[Number]| {
			let mut buffers = HashSet::default();
			for n1 in numbers {
				let b = n1.as_decimal_buf();
				let n2 = Number::from_decimal_buf(&b).unwrap();
				buffers.insert(b);
				assert!(n1.eq(&n2), "{n1:?} = {n2:?} (after deserialization)");
			}
			assert_eq!(buffers.len(), 1, "{numbers:?}");
		};
		check(&[Number::Int(0), Number::Float(0.0), Number::Decimal(Decimal::ZERO)]);
		check(&[Number::Int(1), Number::Float(1.0), Number::Decimal(Decimal::ONE)]);
		check(&[Number::Int(-1), Number::Float(-1.0), Number::Decimal(Decimal::NEGATIVE_ONE)]);
		check(&[Number::Float(1.5), Number::Decimal(Decimal::from_str_normalized("1.5").unwrap())]);
	}

	#[test]
	fn as_int_lossless_accepts_valid() {
		assert_eq!(Number::Int(0).as_int_lossless(), Some(0));
		assert_eq!(Number::Int(i64::MIN).as_int_lossless(), Some(i64::MIN));
		assert_eq!(Number::Int(i64::MAX).as_int_lossless(), Some(i64::MAX));
		assert_eq!(Number::Float(0.0).as_int_lossless(), Some(0));
		assert_eq!(Number::Float(-0.0).as_int_lossless(), Some(0));
		assert_eq!(Number::Float(7.0).as_int_lossless(), Some(7));
		// `i64::MIN` is exactly representable as `f64` and is the inclusive lower bound.
		assert_eq!(Number::Float(i64::MIN as f64).as_int_lossless(), Some(i64::MIN));
		assert_eq!(Number::Decimal(Decimal::ZERO).as_int_lossless(), Some(0));
		assert_eq!(Number::Decimal(Decimal::ONE).as_int_lossless(), Some(1));
		assert_eq!(Number::Decimal(Decimal::NEGATIVE_ONE).as_int_lossless(), Some(-1));
	}

	#[test]
	fn as_int_lossless_rejects_invalid() {
		assert_eq!(Number::Float(1.5).as_int_lossless(), None);
		assert_eq!(Number::Float(-1.5).as_int_lossless(), None);
		assert_eq!(Number::Float(f64::NAN).as_int_lossless(), None);
		assert_eq!(Number::Float(f64::INFINITY).as_int_lossless(), None);
		assert_eq!(Number::Float(f64::NEG_INFINITY).as_int_lossless(), None);
		// `i64::MAX as f64` rounds up to 2^63, which is *not* in `i64` range —
		// the exclusive upper bound is `-(i64::MIN as f64)`.
		assert_eq!(Number::Float(i64::MAX as f64).as_int_lossless(), None);
		assert_eq!(Number::Float(1e30).as_int_lossless(), None);
		assert_eq!(Number::Float(-1e30).as_int_lossless(), None);
		assert_eq!(
			Number::Decimal(Decimal::from_str_normalized("1.5").unwrap()).as_int_lossless(),
			None,
		);
	}

	#[test]
	fn as_array_index_accepts_valid() {
		assert_eq!(Number::Int(0).as_array_index(), Some(0));
		assert_eq!(Number::Int(7).as_array_index(), Some(7));
		assert_eq!(Number::Float(0.0).as_array_index(), Some(0));
		assert_eq!(Number::Float(-0.0).as_array_index(), Some(0));
		assert_eq!(Number::Float(3.0).as_array_index(), Some(3));
		assert_eq!(Number::Decimal(Decimal::ZERO).as_array_index(), Some(0));
		assert_eq!(Number::Decimal(Decimal::ONE).as_array_index(), Some(1));
	}

	#[test]
	fn as_array_index_rejects_invalid() {
		assert_eq!(Number::Int(-1).as_array_index(), None);
		assert_eq!(Number::Int(i64::MIN).as_array_index(), None);
		assert_eq!(Number::Float(-1.0).as_array_index(), None);
		assert_eq!(Number::Float(1.5).as_array_index(), None);
		assert_eq!(Number::Float(f64::NAN).as_array_index(), None);
		assert_eq!(Number::Float(f64::INFINITY).as_array_index(), None);
		assert_eq!(Number::Float(f64::NEG_INFINITY).as_array_index(), None);
		// 1e30 is far beyond usize::MAX and not exactly representable as usize.
		assert_eq!(Number::Float(1e30).as_array_index(), None);
		assert_eq!(Number::Decimal(Decimal::NEGATIVE_ONE).as_array_index(), None);
		assert_eq!(
			Number::Decimal(Decimal::from_str_normalized("1.5").unwrap()).as_array_index(),
			None,
		);
	}

	#[test]
	fn fixed_int_is_unchanged_regardless_of_precision() {
		assert_eq!(Number::Int(101).fixed(0), Number::Int(101));
		assert_eq!(Number::Int(101).fixed(2), Number::Int(101));
		assert_eq!(Number::Int(101).fixed(319), Number::Int(101));
		assert_eq!(Number::Int(-7).fixed(5), Number::Int(-7));
	}

	#[test]
	fn fixed_float_rounds_to_requested_precision() {
		assert_eq!(Number::Float(101.5).fixed(2), Number::Float(101.5));
		assert_eq!(Number::Float(101.1111111).fixed(2), Number::Float(101.11));
		// Subnormal at precision past f64's significant-digit range: the
		// trailing digits get truncated, producing a smaller-but-finite
		// neighbour rather than 0, inf, or NaN.
		assert_eq!(
			Number::Float(2.2250738585072014e-308).fixed(319),
			Number::Float(2.22507385851e-308),
		);
	}

	#[test]
	fn fixed_float_preserves_non_finite() {
		// The Float arm relies on `format!`/`parse` round-tripping every
		// f64 — including NaN and ±inf. Pin that invariant here so a future
		// change to the formatter cannot silently break the `expect` in
		// `Number::fixed`.
		let Number::Float(nan) = Number::Float(f64::NAN).fixed(2) else {
			panic!("expected Number::Float(NaN)");
		};
		assert!(nan.is_nan());
		assert_eq!(Number::Float(f64::INFINITY).fixed(2), Number::Float(f64::INFINITY));
		assert_eq!(Number::Float(f64::NEG_INFINITY).fixed(2), Number::Float(f64::NEG_INFINITY));
	}

	#[test]
	fn fixed_decimal_uses_round_dp() {
		let d = Decimal::from_str_normalized("1.2345").unwrap();
		assert_eq!(
			Number::Decimal(d).fixed(2),
			Number::Decimal(Decimal::from_str_normalized("1.23").unwrap()),
		);
	}
}