1use std::{
58 cmp::Ordering,
59 fmt::{Debug, Display},
60 hash::{Hash, Hasher},
61 iter::Sum,
62 ops::{Add, Deref, Div, Mul, Sub},
63 str::FromStr,
64};
65
66#[cfg(feature = "defi")]
67use alloy_primitives::U256;
68use nautilus_core::{
69 correctness::{
70 CorrectnessError, CorrectnessResult, CorrectnessResultExt, FAILED,
71 check_in_range_inclusive_f64,
72 },
73 string::formatting::Separable,
74};
75use rust_decimal::Decimal;
76use serde::{Deserialize, Deserializer, Serialize};
77
78#[cfg(not(feature = "defi"))]
79use super::fixed::FIXED_SCALAR_RAW;
80#[cfg(feature = "defi")]
81use super::fixed::compare_raw;
82use super::fixed::{
83 FIXED_PRECISION, FIXED_SCALAR, MAX_PRECISION, canonical_raw, check_fixed_precision,
84 checked_mul_div_fixed, checked_mul_div_raw, format_scaled_u128,
85 mantissa_exponent_to_fixed_i128, mantissa_exponent_to_raw_checked, parse_decimal_mantissa,
86 raw_scale, raw_scales_match, remove_underscores, scaled_raw_to_decimal,
87};
88#[cfg(not(feature = "high-precision"))]
89use super::fixed::{check_fixed_raw_u64 as check_fixed_raw, f64_to_fixed_u64, fixed_u64_to_f64};
90#[cfg(feature = "high-precision")]
91use super::fixed::{check_fixed_raw_u128 as check_fixed_raw, f64_to_fixed_u128, fixed_u128_to_f64};
92use crate::deserialization::StringInput;
93#[cfg(feature = "defi")]
94use crate::types::fixed::MAX_FLOAT_PRECISION;
95
96#[cfg(feature = "high-precision")]
101pub type QuantityRaw = u128;
102
103#[cfg(not(feature = "high-precision"))]
104pub type QuantityRaw = u64;
105
106#[unsafe(no_mangle)]
115#[allow(unsafe_code)]
116pub static QUANTITY_RAW_MAX: QuantityRaw =
117 (QUANTITY_MAX as QuantityRaw) * (FIXED_SCALAR as QuantityRaw);
118
119pub const QUANTITY_UNDEF: QuantityRaw = QuantityRaw::MAX;
121
122#[cfg(feature = "high-precision")]
127pub const QUANTITY_MAX: f64 = 34_028_236_692_093.0;
129
130#[cfg(not(feature = "high-precision"))]
131pub const QUANTITY_MAX: f64 = 18_446_744_073.0;
133
134pub const QUANTITY_MIN: f64 = 0.0;
138
139#[repr(C)]
150#[derive(Clone, Copy, Default, Eq)]
151#[cfg_attr(
152 feature = "python",
153 pyo3::pyclass(module = "nautilus_trader.model", frozen, from_py_object)
154)]
155#[cfg_attr(
156 feature = "python",
157 pyo3_stub_gen::derive::gen_stub_pyclass(module = "nautilus_trader.model")
158)]
159pub struct Quantity {
160 pub(crate) raw: QuantityRaw,
161 pub precision: u8,
163}
164
165impl Quantity {
166 pub fn new_checked(value: f64, precision: u8) -> CorrectnessResult<Self> {
178 check_in_range_inclusive_f64(value, QUANTITY_MIN, QUANTITY_MAX, "value")?;
179
180 #[cfg(feature = "defi")]
181 if precision > MAX_FLOAT_PRECISION {
182 return Err(CorrectnessError::PredicateViolation {
184 message: format!(
185 "`precision` exceeded maximum float precision ({MAX_FLOAT_PRECISION}), use `Quantity::from_wei()` for wei values instead"
186 ),
187 });
188 }
189
190 check_fixed_precision(precision)?;
191
192 #[cfg(feature = "high-precision")]
193 let raw = f64_to_fixed_u128(value, precision);
194 #[cfg(not(feature = "high-precision"))]
195 let raw = f64_to_fixed_u64(value, precision);
196
197 Ok(Self { raw, precision })
198 }
199
200 #[must_use]
206 pub fn new(value: f64, precision: u8) -> Self {
207 Self::new_checked(value, precision).expect_display(FAILED)
208 }
209
210 #[inline]
216 #[must_use]
217 pub fn from_raw(raw: QuantityRaw, precision: u8) -> Self {
218 Self::from_raw_checked(raw, precision).expect_display(FAILED)
219 }
220
221 #[inline]
232 pub fn from_raw_checked(raw: QuantityRaw, precision: u8) -> CorrectnessResult<Self> {
233 if raw == QUANTITY_UNDEF && precision != 0 {
234 return Err(CorrectnessError::PredicateViolation {
235 message: "`precision` must be 0 when `raw` is QUANTITY_UNDEF".to_string(),
236 });
237 }
238
239 if raw != QUANTITY_UNDEF && raw > QUANTITY_RAW_MAX {
240 return Err(CorrectnessError::PredicateViolation {
241 message: format!("raw value {raw} exceeds QUANTITY_RAW_MAX={QUANTITY_RAW_MAX}"),
242 });
243 }
244
245 check_fixed_precision(precision)?;
246 if raw != QUANTITY_UNDEF {
247 check_fixed_raw(raw, precision).map_err(|e| CorrectnessError::PredicateViolation {
248 message: e.to_string(),
249 })?;
250 }
251
252 Ok(Self { raw, precision })
253 }
254
255 #[must_use]
260 pub fn checked_rescale(self, precision: u8) -> Option<Self> {
261 if self.raw > QUANTITY_RAW_MAX
262 || precision < self.precision
263 || check_fixed_precision(self.precision).is_err()
264 || check_fixed_precision(precision).is_err()
265 {
266 return None;
267 }
268
269 let source_scale = FIXED_PRECISION.max(self.precision);
270 let target_scale = FIXED_PRECISION.max(precision);
271 let factor = QuantityRaw::pow(10, u32::from(target_scale - source_scale));
272 let raw = self.raw.checked_mul(factor)?;
273 Self::from_raw_checked(raw, precision).ok()
274 }
275
276 #[must_use]
283 pub fn checked_floor_to_increment(self, increment: Self) -> Option<Self> {
284 if increment.is_zero() {
285 return None;
286 }
287
288 let precision = self.precision.max(increment.precision);
289 let value = self.checked_rescale(precision)?;
290 let step = increment.checked_rescale(precision)?;
291 let raw = value.raw - value.raw % step.raw;
292 let scale = QuantityRaw::pow(
293 10,
294 u32::from(precision.max(FIXED_PRECISION) - increment.precision.max(FIXED_PRECISION)),
295 );
296
297 Self::from_raw_checked(raw / scale, increment.precision).ok()
298 }
299
300 #[must_use]
307 pub fn checked_add(self, rhs: Self) -> Option<Self> {
308 if self.raw == QUANTITY_UNDEF || rhs.raw == QUANTITY_UNDEF {
309 return None;
310 }
311
312 if !raw_scales_match(self.precision, rhs.precision) {
313 return None;
314 }
315
316 let raw = self.raw.checked_add(rhs.raw)?;
317 if raw > QUANTITY_RAW_MAX {
318 return None;
319 }
320
321 Some(Self {
322 raw,
323 precision: self.precision.max(rhs.precision),
324 })
325 }
326
327 #[must_use]
333 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
334 if self.raw == QUANTITY_UNDEF || rhs.raw == QUANTITY_UNDEF {
335 return None;
336 }
337
338 if !raw_scales_match(self.precision, rhs.precision) {
339 return None;
340 }
341
342 let raw = self.raw.checked_sub(rhs.raw)?;
343
344 Some(Self {
345 raw,
346 precision: self.precision.max(rhs.precision),
347 })
348 }
349
350 #[must_use]
358 pub fn saturating_add(self, rhs: Self) -> Self {
359 assert!(
360 raw_scales_match(self.precision, rhs.precision),
361 "Cannot add `Quantity` values with mismatched decimal scales"
362 );
363
364 Self {
365 raw: self.raw.saturating_add(rhs.raw).min(QUANTITY_RAW_MAX),
366 precision: self.precision.max(rhs.precision),
367 }
368 }
369
370 #[must_use]
382 pub fn saturating_sub(self, rhs: Self) -> Self {
383 assert!(
384 raw_scales_match(self.precision, rhs.precision),
385 "Cannot subtract `Quantity` values with mismatched decimal scales"
386 );
387 let precision = self.precision.max(rhs.precision);
388 let raw = self.raw.saturating_sub(rhs.raw);
389 if raw == 0 && self.raw < rhs.raw {
390 log::warn!(
391 "Saturating Quantity subtraction: {self} - {rhs} < 0, clamped to 0 (precision={precision})"
392 );
393 }
394
395 Self { raw, precision }
396 }
397
398 #[must_use]
404 pub fn zero(precision: u8) -> Self {
405 check_fixed_precision(precision).expect_display(FAILED);
406 Self { raw: 0, precision }
407 }
408
409 #[must_use]
411 pub fn is_undefined(&self) -> bool {
412 self.raw == QUANTITY_UNDEF
413 }
414
415 #[must_use]
428 #[inline]
429 pub const fn raw(&self) -> QuantityRaw {
430 self.raw
431 }
432
433 #[must_use]
435 #[inline]
436 pub fn is_zero(&self) -> bool {
437 self.raw == 0
438 }
439
440 #[must_use]
442 #[inline]
443 pub fn non_zero(&self) -> bool {
444 self.raw != 0
445 }
446
447 #[must_use]
449 #[inline]
450 pub fn is_positive(&self) -> bool {
451 self.raw != QUANTITY_UNDEF && self.raw > 0
452 }
453
454 #[cfg(feature = "high-precision")]
455 #[must_use]
461 pub fn as_f64(&self) -> f64 {
462 #[cfg(feature = "defi")]
463 assert!(
464 self.precision <= MAX_FLOAT_PRECISION,
465 "Invalid f64 conversion beyond `MAX_FLOAT_PRECISION` (16)"
466 );
467
468 fixed_u128_to_f64(self.raw)
469 }
470
471 #[cfg(not(feature = "high-precision"))]
472 #[must_use]
474 pub fn as_f64(&self) -> f64 {
475 fixed_u64_to_f64(self.raw)
476 }
477
478 #[must_use]
480 pub fn as_decimal(&self) -> Decimal {
481 let precision_diff = FIXED_PRECISION.saturating_sub(self.precision);
483 let rescaled_raw = self.raw / QuantityRaw::pow(10, u32::from(precision_diff));
484
485 #[allow(
489 clippy::unnecessary_cast,
490 clippy::cast_lossless,
491 reason = "cast is real when QuantityRaw is u64, no-op when u128"
492 )]
493 scaled_raw_to_decimal(rescaled_raw as i128, self.precision)
494 }
495
496 #[must_use]
498 #[allow(
499 clippy::unnecessary_fallible_conversions,
500 reason = "try_from is infallible when QuantityRaw is u64, fallible when u128"
501 )]
502 #[cfg(not(feature = "defi"))]
503 pub(crate) fn raw_as_decimal(raw: QuantityRaw) -> Decimal {
504 let whole =
505 i128::try_from(raw / FIXED_SCALAR_RAW).expect("Whole raw quantity must fit in Decimal");
506 let fractional = i128::try_from(raw % FIXED_SCALAR_RAW)
507 .expect("Fractional raw quantity must fit in Decimal");
508
509 Decimal::from(whole) + Decimal::from_i128_with_scale(fractional, u32::from(FIXED_PRECISION))
510 }
511
512 #[must_use]
514 pub fn to_formatted_string(&self) -> String {
515 format!("{self}").separate_with_underscores()
516 }
517
518 fn raw_at_precision(&self) -> QuantityRaw {
519 let precision_diff = FIXED_PRECISION.saturating_sub(self.precision);
520 self.raw / QuantityRaw::pow(10, u32::from(precision_diff))
521 }
522
523 fn raw_as_u128(raw: QuantityRaw) -> u128 {
524 #[allow(
525 clippy::useless_conversion,
526 reason = "u128::from is a widening conversion when QuantityRaw is u64"
527 )]
528 u128::from(raw)
529 }
530
531 pub fn from_decimal_dp(decimal: Decimal, precision: u8) -> CorrectnessResult<Self> {
544 if decimal.mantissa() < 0 {
545 return Err(CorrectnessError::PredicateViolation {
546 message: format!(
547 "Decimal value '{decimal}' is negative, Quantity must be non-negative"
548 ),
549 });
550 }
551
552 let exponent = -(decimal.scale() as i8);
553 let raw_i128 = mantissa_exponent_to_fixed_i128(decimal.mantissa(), exponent, precision)?;
554
555 let raw: QuantityRaw =
556 raw_i128
557 .try_into()
558 .map_err(|_| CorrectnessError::PredicateViolation {
559 message: format!(
560 "Decimal value exceeds QuantityRaw range [0, {QUANTITY_RAW_MAX}]"
561 ),
562 })?;
563
564 if raw > QUANTITY_RAW_MAX {
565 return Err(CorrectnessError::PredicateViolation {
566 message: format!(
567 "Raw value {raw} exceeds QUANTITY_RAW_MAX={QUANTITY_RAW_MAX} for Quantity"
568 ),
569 });
570 }
571
572 Ok(Self { raw, precision })
573 }
574
575 pub fn from_decimal(decimal: Decimal) -> CorrectnessResult<Self> {
587 let precision = (decimal.scale() as u8).min(MAX_PRECISION);
588 Self::from_decimal_dp(decimal, precision)
589 }
590
591 #[must_use]
600 pub fn from_mantissa_exponent(mantissa: u64, exponent: i8, precision: u8) -> Self {
601 check_fixed_precision(precision).expect_display(FAILED);
602
603 if mantissa == 0 {
604 return Self { raw: 0, precision };
605 }
606
607 let raw_i128 = mantissa_exponent_to_fixed_i128(i128::from(mantissa), exponent, precision)
608 .expect("Overflow in Quantity::from_mantissa_exponent");
609
610 let raw: QuantityRaw = raw_i128
611 .try_into()
612 .expect("Raw value exceeds QuantityRaw range in Quantity::from_mantissa_exponent");
613 assert!(
614 raw <= QUANTITY_RAW_MAX,
615 "`raw` value {raw} exceeded QUANTITY_RAW_MAX={QUANTITY_RAW_MAX} for Quantity"
616 );
617
618 Self { raw, precision }
619 }
620
621 pub fn from_mantissa_exponent_checked(
628 mantissa: u64,
629 exponent: i8,
630 precision: u8,
631 ) -> CorrectnessResult<Self> {
632 let raw = mantissa_exponent_to_raw_checked::<QuantityRaw>(
633 i128::from(mantissa),
634 exponent,
635 precision,
636 "Quantity::from_mantissa_exponent",
637 "QuantityRaw",
638 "Quantity",
639 )?;
640
641 Self::from_raw_checked(raw, precision)
642 }
643
644 #[cfg(feature = "defi")]
652 pub fn from_u256(amount: U256, precision: u8) -> CorrectnessResult<Self> {
653 let scaled_amount = if precision < FIXED_PRECISION {
655 amount
656 .checked_mul(U256::from(
657 10u128.pow(u32::from(FIXED_PRECISION - precision)),
658 ))
659 .ok_or_else(|| CorrectnessError::PredicateViolation {
660 message: format!(
661 "Amount overflow during scaling to fixed precision: {} * 10^{}",
662 amount,
663 FIXED_PRECISION - precision
664 ),
665 })?
666 } else {
667 amount
668 };
669
670 let raw = QuantityRaw::try_from(scaled_amount).map_err(|_| {
671 CorrectnessError::PredicateViolation {
672 message: format!("U256 scaled amount {scaled_amount} exceeds QuantityRaw range"),
673 }
674 })?;
675
676 Self::from_raw_checked(raw, precision)
677 }
678}
679
680impl From<Quantity> for f64 {
681 fn from(qty: Quantity) -> Self {
682 qty.as_f64()
683 }
684}
685
686impl From<&Quantity> for f64 {
687 fn from(qty: &Quantity) -> Self {
688 qty.as_f64()
689 }
690}
691
692impl From<i32> for Quantity {
693 fn from(value: i32) -> Self {
699 assert!(
700 value >= 0,
701 "Cannot create Quantity from negative i32: {value}. Use u32 or check value is non-negative."
702 );
703 Self::from_mantissa_exponent(u64::from(value.cast_unsigned()), 0, 0)
704 }
705}
706
707impl From<i64> for Quantity {
708 fn from(value: i64) -> Self {
714 assert!(
715 value >= 0,
716 "Cannot create Quantity from negative i64: {value}. Use u64 or check value is non-negative."
717 );
718 Self::from_mantissa_exponent(value.cast_unsigned(), 0, 0)
719 }
720}
721
722impl From<u32> for Quantity {
723 fn from(value: u32) -> Self {
724 Self::from_mantissa_exponent(u64::from(value), 0, 0)
725 }
726}
727
728impl From<u64> for Quantity {
729 fn from(value: u64) -> Self {
730 Self::from_mantissa_exponent(value, 0, 0)
731 }
732}
733
734impl Hash for Quantity {
735 fn hash<H: Hasher>(&self, state: &mut H) {
736 canonical_raw(self.raw, self.precision).hash(state);
737 }
738}
739
740impl PartialEq for Quantity {
741 #[inline]
742 fn eq(&self, other: &Self) -> bool {
743 self.cmp(other) == Ordering::Equal
744 }
745}
746
747impl PartialOrd for Quantity {
748 #[inline]
749 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
750 Some(self.cmp(other))
751 }
752}
753
754impl Ord for Quantity {
755 #[inline]
756 fn cmp(&self, other: &Self) -> Ordering {
757 #[cfg(feature = "defi")]
758 {
759 compare_raw(self.raw, self.precision, other.raw, other.precision)
760 }
761
762 #[cfg(not(feature = "defi"))]
763 {
764 self.raw.cmp(&other.raw)
765 }
766 }
767}
768
769impl Deref for Quantity {
770 type Target = QuantityRaw;
771
772 fn deref(&self) -> &Self::Target {
773 &self.raw
774 }
775}
776
777impl Add for Quantity {
778 type Output = Self;
779 #[inline]
780 fn add(self, rhs: Self) -> Self::Output {
781 #[cfg(feature = "defi")]
782 assert!(
783 raw_scales_match(self.precision, rhs.precision),
784 "Cannot add `Quantity` values with mismatched decimal scales"
785 );
786 Self {
787 raw: self
788 .raw
789 .checked_add(rhs.raw)
790 .expect("Overflow occurred when adding `Quantity`"),
791 precision: self.precision.max(rhs.precision),
792 }
793 }
794}
795
796impl Sum for Quantity {
797 fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
798 iter.reduce(|acc, x| acc + x)
799 .unwrap_or_else(|| Self::zero(0))
800 }
801}
802
803impl<'a> Sum<&'a Self> for Quantity {
804 fn sum<I: Iterator<Item = &'a Self>>(iter: I) -> Self {
805 iter.copied().sum()
806 }
807}
808
809impl Sub for Quantity {
810 type Output = Self;
811 #[inline]
812 fn sub(self, rhs: Self) -> Self::Output {
813 #[cfg(feature = "defi")]
814 assert!(
815 raw_scales_match(self.precision, rhs.precision),
816 "Cannot subtract `Quantity` values with mismatched decimal scales"
817 );
818 Self {
819 raw: self
820 .raw
821 .checked_sub(rhs.raw)
822 .expect("Underflow occurred when subtracting `Quantity`"),
823 precision: self.precision.max(rhs.precision),
824 }
825 }
826}
827
828impl Mul for Quantity {
829 type Output = Self;
830 fn mul(self, rhs: Self) -> Self::Output {
831 let result_raw = if self.raw != QUANTITY_UNDEF
832 && rhs.raw != QUANTITY_UNDEF
833 && self.precision <= FIXED_PRECISION
834 && rhs.precision <= FIXED_PRECISION
835 {
836 checked_mul_div_fixed(self.raw, rhs.raw)
837 } else {
838 let scalar = QuantityRaw::try_from(raw_scale(self.precision.min(rhs.precision)))
839 .expect("Fixed-point scale fits QuantityRaw");
840 checked_mul_div_raw(self.raw, rhs.raw, scalar)
841 }
842 .filter(|raw| *raw <= QUANTITY_RAW_MAX)
843 .expect("Overflow occurred when multiplying `Quantity`");
844
845 Self {
846 raw: result_raw,
847 precision: self.precision.max(rhs.precision),
848 }
849 }
850}
851
852impl Add<Decimal> for Quantity {
853 type Output = Decimal;
854 fn add(self, rhs: Decimal) -> Self::Output {
855 self.as_decimal() + rhs
856 }
857}
858
859impl Sub<Decimal> for Quantity {
860 type Output = Decimal;
861 fn sub(self, rhs: Decimal) -> Self::Output {
862 self.as_decimal() - rhs
863 }
864}
865
866impl Mul<Decimal> for Quantity {
867 type Output = Decimal;
868 fn mul(self, rhs: Decimal) -> Self::Output {
869 self.as_decimal() * rhs
870 }
871}
872
873impl Div<Decimal> for Quantity {
874 type Output = Decimal;
875 fn div(self, rhs: Decimal) -> Self::Output {
876 self.as_decimal() / rhs
877 }
878}
879
880impl Add<f64> for Quantity {
881 type Output = f64;
882 fn add(self, rhs: f64) -> Self::Output {
883 self.as_f64() + rhs
884 }
885}
886
887impl Sub<f64> for Quantity {
888 type Output = f64;
889 fn sub(self, rhs: f64) -> Self::Output {
890 self.as_f64() - rhs
891 }
892}
893
894impl Mul<f64> for Quantity {
895 type Output = f64;
896 fn mul(self, rhs: f64) -> Self::Output {
897 self.as_f64() * rhs
898 }
899}
900
901impl Div<f64> for Quantity {
902 type Output = f64;
903 fn div(self, rhs: f64) -> Self::Output {
904 self.as_f64() / rhs
905 }
906}
907
908impl From<Quantity> for QuantityRaw {
909 fn from(value: Quantity) -> Self {
910 value.raw
911 }
912}
913
914impl From<&Quantity> for QuantityRaw {
915 fn from(value: &Quantity) -> Self {
916 value.raw
917 }
918}
919
920impl From<Quantity> for Decimal {
921 fn from(value: Quantity) -> Self {
922 value.as_decimal()
923 }
924}
925
926impl From<&Quantity> for Decimal {
927 fn from(value: &Quantity) -> Self {
928 value.as_decimal()
929 }
930}
931
932impl FromStr for Quantity {
933 type Err = String;
934
935 fn from_str(value: &str) -> Result<Self, Self::Err> {
936 let clean_value = remove_underscores(value);
937 if clean_value.contains('e') || clean_value.contains('E') {
938 let decimal = Decimal::from_scientific(&clean_value)
939 .map_err(|e| format!("Error parsing `input` string '{value}' as Decimal: {e}"))?;
940 let precision = decimal.scale() as u8;
941 return Self::from_decimal_dp(decimal, precision).map_err(|e| e.to_string());
942 }
943
944 let (mantissa, precision) = parse_decimal_mantissa(&clean_value)
945 .map_err(|e| format!("Error parsing `input` string '{value}' as Decimal: {e}"))?;
946 if mantissa < 0 {
947 return Err(format!(
948 "Decimal value '{clean_value}' is negative, Quantity must be non-negative"
949 ));
950 }
951 let exponent = -i8::try_from(precision).map_err(|e| e.to_string())?;
952 let raw = mantissa_exponent_to_raw_checked::<QuantityRaw>(
953 mantissa,
954 exponent,
955 precision,
956 "Quantity::from_str",
957 "QuantityRaw",
958 "Quantity",
959 )
960 .map_err(|e| e.to_string())?;
961 Self::from_raw_checked(raw, precision).map_err(|e| e.to_string())
962 }
963}
964
965impl From<&str> for Quantity {
966 fn from(value: &str) -> Self {
967 Self::from_str(value).expect(FAILED)
968 }
969}
970
971impl From<String> for Quantity {
972 fn from(value: String) -> Self {
973 Self::from_str(&value).expect(FAILED)
974 }
975}
976
977impl From<&String> for Quantity {
978 fn from(value: &String) -> Self {
979 Self::from_str(value).expect(FAILED)
980 }
981}
982
983impl Debug for Quantity {
984 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
985 write!(
986 f,
987 "{}({})",
988 stringify!(Quantity),
989 format_scaled_u128(Self::raw_as_u128(self.raw_at_precision()), self.precision),
990 )
991 }
992}
993
994impl Display for Quantity {
995 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
996 write!(
997 f,
998 "{}",
999 format_scaled_u128(Self::raw_as_u128(self.raw_at_precision()), self.precision),
1000 )
1001 }
1002}
1003
1004impl Serialize for Quantity {
1005 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1006 where
1007 S: serde::Serializer,
1008 {
1009 serializer.serialize_str(&self.to_string())
1010 }
1011}
1012
1013impl<'de> Deserialize<'de> for Quantity {
1014 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1015 where
1016 D: Deserializer<'de>,
1017 {
1018 let StringInput(qty_str) = Deserialize::deserialize(deserializer)?;
1019 Self::from_str(qty_str.as_ref()).map_err(serde::de::Error::custom)
1020 }
1021}
1022
1023pub fn check_positive_quantity(value: Quantity, param: &str) -> CorrectnessResult<()> {
1029 if !value.is_positive() {
1030 return Err(CorrectnessError::NotPositive {
1031 param: param.to_string(),
1032 value: value.to_string(),
1033 type_name: "`Quantity`",
1034 });
1035 }
1036 Ok(())
1037}
1038
1039#[cfg(test)]
1040mod tests {
1041 use std::str::FromStr;
1042
1043 use nautilus_core::{approx_eq, correctness::CorrectnessError};
1044 use rstest::rstest;
1045 use rust_decimal_macros::dec;
1046
1047 use super::*;
1048 use crate::types::fixed::FIXED_SCALAR_RAW;
1049 #[cfg(not(feature = "defi"))]
1050 use crate::types::fixed::MAX_FLOAT_PRECISION;
1051
1052 #[cfg(feature = "high-precision")]
1053 #[rstest]
1054 #[case(QUANTITY_RAW_MAX, dec!(34028236692093))]
1055 #[case(80_000_000_000_000_000_000_000_000_000, dec!(8000000000000))]
1056 fn test_as_decimal_above_decimal_mantissa(#[case] raw: QuantityRaw, #[case] expected: Decimal) {
1057 let qty = Quantity::from_raw(raw, 16);
1060
1061 assert_eq!(qty.as_decimal(), expected);
1062 }
1063
1064 #[rstest]
1065 fn test_max_quantity_round_trips_through_raw() {
1066 let qty = Quantity::new(QUANTITY_MAX, 0);
1069
1070 assert_eq!(qty.raw, QUANTITY_RAW_MAX);
1071 assert!(Quantity::from_raw_checked(qty.raw, 0).is_ok());
1072 assert!(qty.checked_add(Quantity::zero(0)).is_some());
1073 }
1074
1075 #[rstest]
1076 fn test_check_quantity_positive() {
1077 let qty = Quantity::new(0.0, 0);
1078 let error = check_positive_quantity(qty, "qty").unwrap_err();
1079
1080 assert_eq!(
1081 error,
1082 CorrectnessError::NotPositive {
1083 param: "qty".to_string(),
1084 value: "0".to_string(),
1085 type_name: "`Quantity`",
1086 }
1087 );
1088 assert_eq!(
1089 error.to_string(),
1090 "invalid `Quantity` for 'qty' not positive, was 0"
1091 );
1092 }
1093
1094 #[rstest]
1095 #[cfg(all(not(feature = "defi"), not(feature = "high-precision")))]
1096 #[should_panic(expected = "`precision` exceeded maximum `FIXED_PRECISION` (9), was 17")]
1097 fn test_invalid_precision_new() {
1098 let _ = Quantity::new(1.0, 17);
1100 }
1101
1102 #[rstest]
1103 #[cfg(all(not(feature = "defi"), feature = "high-precision"))]
1104 #[should_panic(expected = "`precision` exceeded maximum `FIXED_PRECISION` (16), was 17")]
1105 fn test_invalid_precision_new() {
1106 let _ = Quantity::new(1.0, 17);
1108 }
1109
1110 #[rstest]
1111 #[cfg(not(feature = "defi"))]
1112 #[should_panic(expected = "Condition failed: `precision` exceeded maximum `FIXED_PRECISION`")]
1113 fn test_invalid_precision_from_raw() {
1114 let _ = Quantity::from_raw(1, FIXED_PRECISION + 1);
1116 }
1117
1118 #[rstest]
1119 #[cfg(not(feature = "defi"))]
1120 #[should_panic(expected = "Condition failed: `precision` exceeded maximum `FIXED_PRECISION`")]
1121 fn test_invalid_precision_zero() {
1122 let _ = Quantity::zero(FIXED_PRECISION + 1);
1124 }
1125
1126 #[rstest]
1127 fn test_mixed_precision_add() {
1128 let q1 = Quantity::new(1.0, 1);
1129 let q2 = Quantity::new(1.0, 2);
1130 let result = q1 + q2;
1131 assert_eq!(result.precision, 2);
1132 assert_eq!(result.as_f64(), 2.0);
1133 }
1134
1135 #[rstest]
1136 fn test_sum_owned_quantities() {
1137 let quantities = [Quantity::new(1.25, 2), Quantity::new(2.75, 2)];
1138 let result: Quantity = quantities.into_iter().sum();
1139
1140 assert_eq!(result.as_decimal(), dec!(4.00));
1141 assert_eq!(result.precision, 2);
1142 }
1143
1144 #[rstest]
1145 fn test_sum_borrowed_quantities() {
1146 let quantities = [Quantity::new(0.125, 3), Quantity::new(0.375, 3)];
1147 let result: Quantity = quantities.iter().sum();
1148
1149 assert_eq!(result.as_decimal(), dec!(0.500));
1150 assert_eq!(result.precision, 3);
1151 }
1152
1153 #[rstest]
1154 fn test_sum_mixed_precision_quantities() {
1155 let quantities = [
1156 Quantity::new(1.2, 1),
1157 Quantity::new(3.45, 2),
1158 Quantity::new(0.006, 3),
1159 ];
1160 let result: Quantity = quantities.into_iter().sum();
1161
1162 assert_eq!(result.as_decimal(), dec!(4.656));
1163 assert_eq!(result.precision, 3);
1164 }
1165
1166 #[rstest]
1167 fn test_sum_empty_quantity_iterator() {
1168 let result: Quantity = std::iter::empty::<Quantity>().sum();
1169
1170 assert_eq!(result.as_decimal(), dec!(0));
1171 assert_eq!(result.precision, 0);
1172 }
1173
1174 #[rstest]
1175 fn test_mixed_precision_sub() {
1176 let q1 = Quantity::new(2.0, 1);
1177 let q2 = Quantity::new(1.0, 2);
1178 let result = q1 - q2;
1179 assert_eq!(result.precision, 2);
1180 assert_eq!(result.as_f64(), 1.0);
1181 }
1182
1183 #[rstest]
1184 fn test_mixed_precision_mul() {
1185 let q1 = Quantity::new(2.0, 1);
1186 let q2 = Quantity::new(3.0, 2);
1187 let result = q1 * q2;
1188 assert_eq!(result.precision, 2);
1189 assert_eq!(result.as_f64(), 6.0);
1190 }
1191
1192 #[rstest]
1193 fn test_mul_retains_precision_and_finer_raw_digits() {
1194 let result = Quantity::from("1.5") * Quantity::from("1.5");
1195 let raw = Quantity::from("2.25").raw();
1196 let reconstructed = Quantity::from_raw_checked(raw, 2).unwrap();
1197
1198 assert_eq!(result.raw(), raw);
1199 assert_eq!(result.precision, 1);
1200 assert_eq!(result.as_decimal(), dec!(2.2));
1201 assert_eq!(result.to_string(), "2.2");
1202 assert_eq!(reconstructed.raw(), raw);
1203 assert_eq!(reconstructed.precision, 2);
1204 assert_eq!(reconstructed.as_decimal(), dec!(2.25));
1205 assert!(Quantity::from_raw_checked(result.raw(), result.precision).is_err());
1206 }
1207
1208 #[rstest]
1209 #[case(1, 0)]
1210 #[case(11, FIXED_PRECISION - 1)]
1211 fn test_from_raw_checked_rejects_spurious_digits(
1212 #[case] raw: QuantityRaw,
1213 #[case] precision: u8,
1214 ) {
1215 let scale = QuantityRaw::pow(10, u32::from(FIXED_PRECISION - precision));
1216 let remainder = raw % scale;
1217 let error = Quantity::from_raw_checked(raw, precision).unwrap_err();
1218
1219 assert_eq!(
1220 error,
1221 CorrectnessError::PredicateViolation {
1222 message: format!(
1223 "Invalid fixed-point raw value {raw} for precision {precision}: \
1224 remainder {remainder} when divided by scale {scale}. \
1225 Raw value should be a multiple of {scale}. \
1226 This indicates data corruption or incorrect precision/scaling upstream"
1227 ),
1228 }
1229 );
1230 }
1231
1232 #[rstest]
1233 #[should_panic(expected = "Condition failed: Invalid fixed-point raw value")]
1234 fn test_from_raw_rejects_spurious_digits() {
1235 let _ = Quantity::from_raw(1, 0);
1236 }
1237
1238 #[rstest]
1239 #[case(0, 0)]
1240 #[case(0, FIXED_PRECISION)]
1241 #[case(10, FIXED_PRECISION - 1)]
1242 #[case(1, FIXED_PRECISION)]
1243 #[case(QUANTITY_UNDEF, 0)]
1244 fn test_from_raw_checked_preserves_aligned_values(
1245 #[case] raw: QuantityRaw,
1246 #[case] precision: u8,
1247 ) {
1248 let quantity = Quantity::from_raw_checked(raw, precision).unwrap();
1249
1250 assert_eq!(quantity.raw(), raw);
1251 assert_eq!(quantity.precision, precision);
1252 assert_eq!(Quantity::from_raw(raw, precision), quantity);
1253 }
1254
1255 #[rstest]
1256 #[case(0, false)]
1257 #[case(FIXED_SCALAR as QuantityRaw, true)]
1258 #[case(QUANTITY_UNDEF, true)]
1259 fn test_non_zero(#[case] raw: QuantityRaw, #[case] expected: bool) {
1260 let qty = Quantity::from_raw(raw, 0);
1261 assert_eq!(qty.non_zero(), expected);
1262 }
1263
1264 #[rstest]
1265 fn test_new() {
1266 let value = 0.00812;
1267 let qty = Quantity::new(value, 8);
1268 assert_eq!(qty, qty);
1269 assert_eq!(qty.raw, Quantity::from(&format!("{value}")).raw);
1270 assert_eq!(qty.precision, 8);
1271 assert_eq!(qty, Quantity::from("0.00812000"));
1272 assert_eq!(qty.as_decimal(), dec!(0.00812000));
1273 assert_eq!(qty.to_string(), "0.00812000");
1274 assert!(qty.non_zero());
1275 assert!(qty.is_positive());
1276 assert!(approx_eq!(f64, qty.as_f64(), 0.00812, epsilon = 0.000_001));
1277 }
1278
1279 #[rstest]
1280 fn test_check_quantity_positive_ok() {
1281 let qty = Quantity::new(10.0, 0);
1282 check_positive_quantity(qty, "qty").unwrap();
1283 }
1284
1285 #[rstest]
1286 fn test_negative_quantity_validation() {
1287 assert!(Quantity::new_checked(-1.0, FIXED_PRECISION).is_err());
1288 }
1289
1290 #[rstest]
1291 fn test_new_checked_returns_typed_error_with_stable_display() {
1292 let error = Quantity::new_checked(QUANTITY_MAX + 1.0, FIXED_PRECISION).unwrap_err();
1293
1294 assert!(matches!(error, CorrectnessError::OutOfRange { .. }));
1295 assert_eq!(
1296 error.to_string(),
1297 format!(
1298 "invalid f64 for 'value' not in range [{QUANTITY_MIN}, {QUANTITY_MAX}], was {}",
1299 QUANTITY_MAX + 1.0
1300 )
1301 );
1302 }
1303
1304 #[rstest]
1305 fn test_from_raw_checked_returns_typed_error_with_stable_display() {
1306 let error = Quantity::from_raw_checked(QUANTITY_UNDEF, 3).unwrap_err();
1307
1308 assert_eq!(
1309 error,
1310 CorrectnessError::PredicateViolation {
1311 message: "`precision` must be 0 when `raw` is QUANTITY_UNDEF".to_string(),
1312 }
1313 );
1314 assert_eq!(
1315 error.to_string(),
1316 "`precision` must be 0 when `raw` is QUANTITY_UNDEF"
1317 );
1318 }
1319
1320 #[rstest]
1321 fn test_undefined() {
1322 let qty = Quantity::from_raw(QUANTITY_UNDEF, 0);
1323 assert_eq!(qty.raw, QUANTITY_UNDEF);
1324 assert!(qty.is_undefined());
1325 }
1326
1327 #[rstest]
1328 fn test_zero() {
1329 let qty = Quantity::zero(8);
1330 assert_eq!(qty.raw, 0);
1331 assert_eq!(qty.precision, 8);
1332 assert!(qty.is_zero());
1333 assert!(!qty.is_positive());
1334 }
1335
1336 #[rstest]
1337 fn test_from_i32_exact() {
1338 let values = [0, 1, i32::MAX];
1339 let quantities = values.map(Quantity::from);
1340 let expected =
1341 values.map(|value| (QuantityRaw::try_from(value).unwrap() * FIXED_SCALAR_RAW, 0));
1342
1343 assert_eq!(
1344 quantities.map(|quantity| (quantity.raw, quantity.precision)),
1345 expected
1346 );
1347 }
1348
1349 #[rstest]
1350 fn test_from_i64_exact() {
1351 let max = quantity_max_i64();
1352 let values = [0, 1, max];
1353 let quantities = values.map(Quantity::from);
1354 let expected =
1355 values.map(|value| (QuantityRaw::try_from(value).unwrap() * FIXED_SCALAR_RAW, 0));
1356
1357 assert_eq!(
1358 quantities.map(|quantity| (quantity.raw, quantity.precision)),
1359 expected
1360 );
1361 }
1362
1363 #[rstest]
1364 fn test_from_u32_exact() {
1365 let values = [0, 1, u32::MAX];
1366 let quantities = values.map(Quantity::from);
1367 let expected = values.map(|value| (QuantityRaw::from(value) * FIXED_SCALAR_RAW, 0));
1368
1369 assert_eq!(
1370 quantities.map(|quantity| (quantity.raw, quantity.precision)),
1371 expected
1372 );
1373 }
1374
1375 #[rstest]
1376 fn test_from_u64_exact() {
1377 let max = quantity_max_u64();
1378 let values = [0, 1, max];
1379 let quantities = values.map(Quantity::from);
1380 let expected = values.map(|value| (QuantityRaw::from(value) * FIXED_SCALAR_RAW, 0));
1381
1382 assert_eq!(
1383 quantities.map(|quantity| (quantity.raw, quantity.precision)),
1384 expected
1385 );
1386 }
1387
1388 #[rstest]
1389 #[should_panic(
1390 expected = "Cannot create Quantity from negative i32: -1. Use u32 or check value is non-negative."
1391 )]
1392 fn test_from_i32_negative_panics() {
1393 let _ = Quantity::from(-1_i32);
1394 }
1395
1396 #[rstest]
1397 #[should_panic(
1398 expected = "Cannot create Quantity from negative i64: -1. Use u64 or check value is non-negative."
1399 )]
1400 fn test_from_i64_negative_panics() {
1401 let _ = Quantity::from(-1_i64);
1402 }
1403
1404 #[rstest]
1405 #[cfg_attr(
1406 feature = "high-precision",
1407 should_panic(expected = "exceeded QUANTITY_RAW_MAX")
1408 )]
1409 #[cfg_attr(
1410 not(feature = "high-precision"),
1411 should_panic(expected = "Raw value exceeds QuantityRaw range")
1412 )]
1413 fn test_from_i64_overflow_panics() {
1414 let max = quantity_max_i64();
1415
1416 let _ = Quantity::from(max + 1);
1417 }
1418
1419 #[rstest]
1420 #[cfg_attr(
1421 feature = "high-precision",
1422 should_panic(expected = "exceeded QUANTITY_RAW_MAX")
1423 )]
1424 #[cfg_attr(
1425 not(feature = "high-precision"),
1426 should_panic(expected = "Raw value exceeds QuantityRaw range")
1427 )]
1428 fn test_from_u64_overflow_panics() {
1429 let max = quantity_max_u64();
1430
1431 let _ = Quantity::from(max + 1);
1432 }
1433
1434 fn quantity_max_i64() -> i64 {
1435 i64::try_from(QUANTITY_RAW_MAX / FIXED_SCALAR_RAW).unwrap()
1436 }
1437
1438 #[allow(
1439 clippy::useless_conversion,
1440 reason = "try_from is a no-op when QuantityRaw is u64, and narrows when u128 (high-precision)"
1441 )]
1442 fn quantity_max_u64() -> u64 {
1443 u64::try_from(QUANTITY_RAW_MAX / FIXED_SCALAR_RAW).unwrap()
1444 }
1445
1446 #[rstest] fn test_with_maximum_value() {
1448 let qty = Quantity::new_checked(QUANTITY_MAX, 0);
1449 assert!(qty.is_ok());
1450 }
1451
1452 #[rstest]
1453 fn test_with_minimum_positive_value() {
1454 let value = 0.000_000_001;
1455 let qty = Quantity::new(value, 9);
1456 assert_eq!(qty.raw, Quantity::from("0.000000001").raw);
1457 assert_eq!(qty.as_decimal(), dec!(0.000000001));
1458 assert_eq!(qty.to_string(), "0.000000001");
1459 }
1460
1461 #[rstest]
1462 fn test_with_minimum_value() {
1463 let qty = Quantity::new(QUANTITY_MIN, 9);
1464 assert_eq!(qty.raw, 0);
1465 assert_eq!(qty.as_decimal(), dec!(0));
1466 assert_eq!(qty.to_string(), "0.000000000");
1467 }
1468
1469 #[rstest]
1470 fn test_is_zero() {
1471 let qty = Quantity::zero(8);
1472 assert_eq!(qty, qty);
1473 assert_eq!(qty.raw, 0);
1474 assert_eq!(qty.precision, 8);
1475 assert_eq!(qty, Quantity::from("0.00000000"));
1476 assert_eq!(qty.as_decimal(), dec!(0));
1477 assert_eq!(qty.to_string(), "0.00000000");
1478 assert!(qty.is_zero());
1479 }
1480
1481 #[rstest]
1482 fn test_precision() {
1483 let value = 1.001;
1484 let qty = Quantity::new(value, 2);
1485 assert_eq!(qty.to_string(), "1.00");
1486 }
1487
1488 #[rstest]
1489 fn test_new_from_str() {
1490 let qty = Quantity::new(0.008_120_00, 8);
1491 assert_eq!(qty, qty);
1492 assert_eq!(qty.precision, 8);
1493 assert_eq!(qty, Quantity::from("0.00812000"));
1494 assert_eq!(qty.to_string(), "0.00812000");
1495 }
1496
1497 #[rstest]
1498 #[case("0", 0)]
1499 #[case("1.1", 1)]
1500 #[case("1.123456789", 9)]
1501 fn test_from_str_valid_input(#[case] input: &str, #[case] expected_prec: u8) {
1502 let qty = Quantity::from(input);
1503 assert_eq!(qty.precision, expected_prec);
1504 assert_eq!(qty.as_decimal(), Decimal::from_str(input).unwrap());
1505 }
1506
1507 #[rstest]
1508 #[should_panic(expected = "ParseFloatError")]
1509 fn test_from_str_invalid_input() {
1510 let input = "invalid";
1511 let _ = Quantity::new(f64::from_str(input).unwrap(), 8);
1512 }
1513
1514 #[rstest]
1515 fn test_from_str_errors() {
1516 assert!(Quantity::from_str("invalid").is_err());
1517 assert!(Quantity::from_str("12.34.56").is_err());
1518 assert!(Quantity::from_str("").is_err());
1519 assert!(Quantity::from_str("-1").is_err()); assert!(Quantity::from_str("-0.001").is_err());
1521 }
1522
1523 #[rstest]
1524 #[case("1e7", 0, 10_000_000.0)]
1525 #[case("2.5e3", 0, 2_500.0)]
1526 #[case("1.234e-2", 5, 0.01234)]
1527 #[case("5E-3", 3, 0.005)]
1528 #[case("1.0e6", 0, 1_000_000.0)]
1529 fn test_from_str_scientific_notation(
1530 #[case] input: &str,
1531 #[case] expected_precision: u8,
1532 #[case] expected_value: f64,
1533 ) {
1534 let qty = Quantity::from_str(input).unwrap();
1535 assert_eq!(qty.precision, expected_precision);
1536 assert!(approx_eq!(
1537 f64,
1538 qty.as_f64(),
1539 expected_value,
1540 epsilon = 1e-10
1541 ));
1542 }
1543
1544 #[rstest]
1545 #[case("1_234.56", 2, 1234.56)]
1546 #[case("1000000", 0, 1_000_000.0)]
1547 #[case("99_999.999_99", 5, 99_999.999_99)]
1548 fn test_from_str_with_underscores(
1549 #[case] input: &str,
1550 #[case] expected_precision: u8,
1551 #[case] expected_value: f64,
1552 ) {
1553 let qty = Quantity::from_str(input).unwrap();
1554 assert_eq!(qty.precision, expected_precision);
1555 assert!(approx_eq!(
1556 f64,
1557 qty.as_f64(),
1558 expected_value,
1559 epsilon = 1e-10
1560 ));
1561 }
1562
1563 #[rstest]
1564 fn test_from_decimal_dp_preservation() {
1565 let decimal = dec!(123.456789);
1567 let qty = Quantity::from_decimal_dp(decimal, 6).unwrap();
1568 assert_eq!(qty.precision, 6);
1569 assert!(approx_eq!(f64, qty.as_f64(), 123.456_789, epsilon = 1e-10));
1570
1571 let expected_raw = 123_456_789_u64 * 10_u64.pow(u32::from(FIXED_PRECISION - 6));
1573 assert_eq!(qty.raw, QuantityRaw::from(expected_raw));
1574 }
1575
1576 #[rstest]
1577 fn test_from_decimal_dp_rounding() {
1578 let decimal = dec!(1.005);
1580 let qty = Quantity::from_decimal_dp(decimal, 2).unwrap();
1581 assert_eq!(qty.as_f64(), 1.0); let decimal = dec!(1.015);
1584 let qty = Quantity::from_decimal_dp(decimal, 2).unwrap();
1585 assert_eq!(qty.as_f64(), 1.02); }
1587
1588 #[rstest]
1589 fn test_from_decimal_infers_precision() {
1590 let decimal = dec!(123.456);
1592 let qty = Quantity::from_decimal(decimal).unwrap();
1593 assert_eq!(qty.precision, 3);
1594 assert!(approx_eq!(f64, qty.as_f64(), 123.456, epsilon = 1e-10));
1595
1596 let decimal = dec!(100);
1598 let qty = Quantity::from_decimal(decimal).unwrap();
1599 assert_eq!(qty.precision, 0);
1600 assert_eq!(qty.as_f64(), 100.0);
1601
1602 let decimal = dec!(1.23456789);
1604 let qty = Quantity::from_decimal(decimal).unwrap();
1605 assert_eq!(qty.precision, 8);
1606 assert!(approx_eq!(f64, qty.as_f64(), 1.234_567_89, epsilon = 1e-10));
1607 }
1608
1609 #[rstest]
1610 fn test_from_decimal_trailing_zeros() {
1611 let decimal = dec!(5.670);
1613 assert_eq!(decimal.scale(), 3); let qty = Quantity::from_decimal(decimal).unwrap();
1617 assert_eq!(qty.precision, 3);
1618 assert!(approx_eq!(f64, qty.as_f64(), 5.67, epsilon = 1e-10));
1619
1620 let normalized = decimal.normalize();
1622 assert_eq!(normalized.scale(), 2);
1623 let qty_normalized = Quantity::from_decimal(normalized).unwrap();
1624 assert_eq!(qty_normalized.precision, 2);
1625 }
1626
1627 #[rstest]
1628 #[case("1.00", 2)]
1629 #[case("1.0", 1)]
1630 #[case("1.000", 3)]
1631 #[case("100.00", 2)]
1632 #[case("0.10", 2)]
1633 #[case("0.100", 3)]
1634 fn test_from_str_preserves_trailing_zeros(#[case] input: &str, #[case] expected_precision: u8) {
1635 let qty = Quantity::from_str(input).unwrap();
1636 assert_eq!(qty.precision, expected_precision);
1637 }
1638
1639 #[rstest]
1640 #[case(0, 0)]
1641 #[case(1, 0)]
1642 #[case(5, 0)]
1643 #[case(10, 1)]
1644 #[case(14, 1)]
1645 #[case(15, 2)]
1646 #[case(16, 2)]
1647 #[case(25, 2)]
1648 #[case(35, 4)]
1649 fn test_from_decimal_rounds_excess_precision(
1650 #[case] mantissa: i128,
1651 #[case] expected_raw: QuantityRaw,
1652 #[values(1, 10)] excess: u32,
1653 ) {
1654 let decimal = Decimal::from_i128_with_scale(
1655 mantissa * 10_i128.pow(excess - 1),
1656 u32::from(MAX_PRECISION) + excess,
1657 );
1658
1659 let quantity = Quantity::from_decimal(decimal).unwrap();
1660
1661 assert_eq!(
1662 (quantity.raw(), quantity.precision),
1663 (expected_raw, MAX_PRECISION)
1664 );
1665 }
1666
1667 #[rstest]
1668 fn test_from_decimal_rounding_carries_into_integer() {
1669 let precision = u32::from(MAX_PRECISION);
1670 let decimal = Decimal::from_i128_with_scale(10_i128.pow(precision + 1) - 5, precision + 1);
1671
1672 let quantity = Quantity::from_decimal(decimal).unwrap();
1673
1674 assert_eq!(quantity.raw(), QuantityRaw::pow(10, precision));
1675 assert_eq!(quantity.precision, MAX_PRECISION);
1676 }
1677
1678 #[rstest]
1679 fn test_from_decimal_rejects_negative_rounding_to_zero() {
1680 let decimal = Decimal::from_i128_with_scale(-1, u32::from(MAX_PRECISION) + 1);
1681 let error = Quantity::from_decimal(decimal).unwrap_err();
1682
1683 assert_eq!(
1684 error.to_string(),
1685 format!("Decimal value '{decimal}' is negative, Quantity must be non-negative"),
1686 );
1687 }
1688
1689 #[rstest]
1690 fn test_from_decimal_rejects_overflow() {
1691 let error = Quantity::from_decimal(Decimal::MAX).unwrap_err();
1692
1693 let expected = if cfg!(feature = "high-precision") {
1694 "Overflow when scaling mantissa to fixed precision".to_string()
1695 } else {
1696 format!("Decimal value exceeds QuantityRaw range [0, {QUANTITY_RAW_MAX}]")
1697 };
1698
1699 assert_eq!(error.to_string(), expected);
1700 }
1701
1702 #[rstest]
1703 fn test_from_decimal_negative_quantity_errors() {
1704 let decimal = dec!(-123.45);
1706 let result = Quantity::from_decimal(decimal);
1707 assert!(result.is_err());
1708
1709 let result = Quantity::from_decimal_dp(decimal, 2);
1711 assert!(result.is_err());
1712 }
1713
1714 #[rstest]
1715 fn test_from_decimal_dp_negative_returns_typed_error_with_stable_display() {
1716 let error = Quantity::from_decimal_dp(dec!(-1.5), 2).unwrap_err();
1717 assert_eq!(
1718 error,
1719 CorrectnessError::PredicateViolation {
1720 message: "Decimal value '-1.5' is negative, Quantity must be non-negative"
1721 .to_string(),
1722 }
1723 );
1724 assert_eq!(
1725 error.to_string(),
1726 "Decimal value '-1.5' is negative, Quantity must be non-negative",
1727 );
1728 }
1729
1730 #[cfg(not(feature = "high-precision"))]
1731 #[rstest]
1732 fn test_from_decimal_dp_rejects_quantity_raw_overflow() {
1733 let error = Quantity::from_decimal_dp(dec!(20_000_000_000), 0).unwrap_err();
1734
1735 assert_eq!(
1736 error,
1737 CorrectnessError::PredicateViolation {
1738 message: format!("Decimal value exceeds QuantityRaw range [0, {QUANTITY_RAW_MAX}]"),
1739 }
1740 );
1741 }
1742
1743 #[cfg(feature = "high-precision")]
1744 #[rstest]
1745 fn test_from_decimal_dp_rejects_value_above_quantity_max() {
1746 let value = 34_028_236_692_094_u64;
1747 let raw = u128::from(value) * FIXED_SCALAR_RAW;
1748 let error = Quantity::from_decimal_dp(Decimal::from(value), 0).unwrap_err();
1749
1750 assert_eq!(
1751 error,
1752 CorrectnessError::PredicateViolation {
1753 message: format!(
1754 "Raw value {raw} exceeds QUANTITY_RAW_MAX={QUANTITY_RAW_MAX} for Quantity"
1755 ),
1756 }
1757 );
1758 }
1759
1760 #[rstest]
1761 fn test_add() {
1762 let a = 1.0;
1763 let b = 2.0;
1764 let quantity1 = Quantity::new(1.0, 0);
1765 let quantity2 = Quantity::new(2.0, 0);
1766 let quantity3 = quantity1 + quantity2;
1767 assert_eq!(quantity3.raw, Quantity::new(a + b, 0).raw);
1768 }
1769
1770 #[rstest]
1771 fn test_sub() {
1772 let a = 3.0;
1773 let b = 2.0;
1774 let quantity1 = Quantity::new(a, 0);
1775 let quantity2 = Quantity::new(b, 0);
1776 let quantity3 = quantity1 - quantity2;
1777 assert_eq!(quantity3.raw, Quantity::new(a - b, 0).raw);
1778 }
1779
1780 #[rstest]
1781 fn test_quantity_checked_add_within_bounds() {
1782 let a = Quantity::new(10.0, 2);
1783 let b = Quantity::new(5.0, 2);
1784 assert_eq!(a.checked_add(b), Some(Quantity::new(15.0, 2)));
1785 }
1786
1787 #[rstest]
1788 fn test_quantity_checked_rescale_native_precision() {
1789 let quantity = Quantity::from("1.25");
1790 let rescaled = quantity.checked_rescale(4).unwrap();
1791
1792 assert_eq!(rescaled.raw, quantity.raw);
1793 assert_eq!(rescaled.precision, 4);
1794 assert_eq!(rescaled.as_decimal(), dec!(1.25));
1795 assert_eq!(quantity.checked_rescale(0), None);
1796 assert_eq!(
1797 Quantity::from_raw(QUANTITY_UNDEF, 0).checked_rescale(0),
1798 None
1799 );
1800 assert_eq!(quantity.checked_rescale(u8::MAX), None);
1801 let mut invalid = quantity;
1802 invalid.precision = u8::MAX;
1803 assert_eq!(invalid.checked_rescale(0), None);
1804 }
1805
1806 #[cfg(feature = "defi")]
1807 #[rstest]
1808 #[case("1.25", 18, Some("1.250000000000000000"))]
1809 #[case("1.250000000000000000", 2, None)]
1810 #[case("1.250000000000000001", 2, None)]
1811 #[case("1.25000000000000001", 18, Some("1.250000000000000010"))]
1812 #[case("1.250000000000000001", 17, None)]
1813 fn test_quantity_checked_rescale_mixed_scales(
1814 #[case] value: &str,
1815 #[case] precision: u8,
1816 #[case] expected: Option<&str>,
1817 ) {
1818 let actual = Quantity::from(value).checked_rescale(precision);
1819
1820 assert_eq!(actual, expected.map(Quantity::from));
1821 assert_eq!(actual.map(|qty| qty.precision), expected.map(|_| precision));
1822 }
1823
1824 #[cfg(feature = "defi")]
1825 #[rstest]
1826 fn test_quantity_checked_rescale_rejects_overflow() {
1827 let quantity = Quantity::from_raw(QUANTITY_RAW_MAX, 0);
1828
1829 assert_eq!(quantity.checked_rescale(18), None);
1830 assert_eq!(
1831 quantity.checked_floor_to_increment(Quantity::from("0.000000000000000001")),
1832 None
1833 );
1834 }
1835
1836 #[rstest]
1837 #[case("0.749", "0.50", "0.50")]
1838 #[case("0.49", "0.50", "0.00")]
1839 #[case("1.23456789", "0.000001", "1.234567")]
1840 #[case("0", "0.5", "0.0")]
1841 fn test_quantity_checked_floor_to_increment(
1842 #[case] value: &str,
1843 #[case] increment: &str,
1844 #[case] expected: &str,
1845 ) {
1846 let increment = Quantity::from(increment);
1847 let actual = Quantity::from(value)
1848 .checked_floor_to_increment(increment)
1849 .unwrap();
1850
1851 assert_eq!(actual, Quantity::from(expected));
1852 assert_eq!(actual.precision, increment.precision);
1853 }
1854
1855 #[rstest]
1856 fn test_quantity_checked_floor_requires_explicit_precision_for_finer_raw_digits() {
1857 let product = Quantity::from("1.5") * Quantity::from("1.5");
1858 let increment = Quantity::from("0.1");
1859 let rescaled = product.checked_rescale(2).unwrap();
1860 let floored = rescaled.checked_floor_to_increment(increment).unwrap();
1861
1862 assert_eq!(product.raw(), Quantity::from("2.25").raw());
1863 assert_eq!(product.precision, 1);
1864 assert_eq!(product.checked_rescale(1), None);
1865 assert_eq!(product.checked_floor_to_increment(increment), None);
1866 assert_eq!(rescaled.raw(), product.raw());
1867 assert_eq!(rescaled.precision, 2);
1868 assert_eq!(floored.raw(), Quantity::from("2.2").raw());
1869 assert_eq!(floored.precision, 1);
1870 }
1871
1872 #[cfg(feature = "defi")]
1873 #[rstest]
1874 #[case("0.59999999999999999", "0.005000", "0.595000")]
1875 #[case("0.599999999999999999", "0.005000", "0.595000")]
1876 #[case("0.600000", "0.00000000000000001", "0.60000000000000000")]
1877 #[case("0.59999999999999999", "0.000000000000000001", "0.599999999999999990")]
1878 fn test_quantity_checked_floor_aligns_raw_scales(
1879 #[case] value: &str,
1880 #[case] increment: &str,
1881 #[case] expected: &str,
1882 ) {
1883 let increment = Quantity::from(increment);
1884 let actual = Quantity::from(value)
1885 .checked_floor_to_increment(increment)
1886 .unwrap();
1887
1888 assert_eq!(actual, Quantity::from(expected));
1889 assert_eq!(actual.precision, increment.precision);
1890 }
1891
1892 #[rstest]
1893 fn test_quantity_checked_floor_rejects_invalid_operands() {
1894 let quantity = Quantity::from(1);
1895 let invalid = Quantity::from_raw(QUANTITY_UNDEF, 0);
1896
1897 assert_eq!(quantity.checked_floor_to_increment(Quantity::from(0)), None);
1898 assert_eq!(quantity.checked_floor_to_increment(invalid), None);
1899 assert_eq!(invalid.checked_floor_to_increment(quantity), None);
1900 }
1901
1902 #[rstest]
1903 fn test_quantity_checked_add_above_max_returns_none() {
1904 let near_max = Quantity::from_raw(QUANTITY_RAW_MAX, 0);
1905 let one = Quantity::new(1.0, 0);
1906 assert_eq!(near_max.checked_add(one), None);
1907 }
1908
1909 #[rstest]
1910 fn test_quantity_checked_sub_within_bounds() {
1911 let a = Quantity::new(10.0, 2);
1912 let b = Quantity::new(3.0, 2);
1913 assert_eq!(a.checked_sub(b), Some(Quantity::new(7.0, 2)));
1914 }
1915
1916 #[rstest]
1917 fn test_quantity_checked_sub_underflow_returns_none() {
1918 let a = Quantity::new(3.0, 2);
1919 let b = Quantity::new(10.0, 2);
1920 assert_eq!(a.checked_sub(b), None);
1921 }
1922
1923 #[rstest]
1924 fn test_quantity_checked_sub_to_zero() {
1925 let a = Quantity::new(5.0, 2);
1926 assert_eq!(a.checked_sub(a), Some(Quantity::zero(2)));
1927 }
1928
1929 #[rstest]
1930 fn test_quantity_from_raw_checked_allows_undef_and_rejects_above_max() {
1931 assert_eq!(
1932 Quantity::from_raw_checked(QUANTITY_UNDEF, 0).unwrap().raw,
1933 QUANTITY_UNDEF
1934 );
1935 assert_eq!(
1936 Quantity::from_raw_checked(QUANTITY_RAW_MAX + 1, 0)
1937 .unwrap_err()
1938 .to_string(),
1939 format!(
1940 "raw value {} exceeds QUANTITY_RAW_MAX={QUANTITY_RAW_MAX}",
1941 QUANTITY_RAW_MAX + 1
1942 )
1943 );
1944 }
1945
1946 #[rstest]
1947 fn test_quantity_as_f64() {
1948 assert_eq!(Quantity::new(2.5, 1).as_f64(), 2.5);
1949 assert_eq!(Quantity::new(0.0, 1).as_f64(), 0.0);
1950 }
1951
1952 #[rstest]
1953 fn test_quantity_deref_yields_raw() {
1954 assert_eq!(*Quantity::from_raw(2_500, FIXED_PRECISION), 2_500);
1955 }
1956
1957 #[rstest]
1958 fn test_quantity_checked_arith_rejects_undef() {
1959 let undef = Quantity::from_raw(QUANTITY_UNDEF, 0);
1960 let one = Quantity::new(1.0, 0);
1961 assert_eq!(undef.checked_add(one), None);
1962 assert_eq!(one.checked_add(undef), None);
1963 assert_eq!(undef.checked_sub(one), None);
1964 assert_eq!(one.checked_sub(undef), None);
1965 }
1966
1967 #[rstest]
1968 fn test_quantity_checked_add_at_exact_max_returns_some() {
1969 let near_max = Quantity::from_raw(QUANTITY_RAW_MAX - 1, FIXED_PRECISION);
1970 let one_unit = Quantity::from_raw(1, FIXED_PRECISION);
1971 assert_eq!(
1972 near_max.checked_add(one_unit),
1973 Some(Quantity::from_raw(QUANTITY_RAW_MAX, FIXED_PRECISION)),
1974 );
1975 }
1976
1977 #[rstest]
1978 fn test_quantity_checked_arith_uses_max_precision() {
1979 let a = Quantity::new(10.5, 1);
1980 let b = Quantity::new(2.25, 2);
1981 let sum = a.checked_add(b).unwrap();
1982 assert_eq!(sum.precision, 2);
1983 assert_eq!(sum.as_f64(), 12.75);
1984
1985 let diff = a.checked_sub(b).unwrap();
1986 assert_eq!(diff.precision, 2);
1987 assert_eq!(diff.as_f64(), 8.25);
1988 }
1989
1990 #[rstest]
1991 fn test_mul() {
1992 let value = 2.0;
1993 let quantity1 = Quantity::new(value, 1);
1994 let quantity2 = Quantity::new(value, 1);
1995 let quantity3 = quantity1 * quantity2;
1996 assert_eq!(quantity3.raw, Quantity::new(value * value, 0).raw);
1997 }
1998
1999 #[rstest]
2000 fn test_mul_avoids_intermediate_raw_overflow() {
2001 let scalar = FIXED_SCALAR_RAW;
2002 #[cfg(feature = "high-precision")]
2003 let (lhs_raw, rhs_raw, expected_raw) =
2004 (100_000 * scalar, 100 * scalar, 10_000_000 * scalar);
2005 #[cfg(not(feature = "high-precision"))]
2006 let (lhs_raw, rhs_raw, expected_raw) = (
2007 9_000_000_000 * scalar,
2008 2 * scalar + 1,
2009 18_000_000_009 * scalar,
2010 );
2011 let lhs = Quantity::from_raw(lhs_raw, FIXED_PRECISION);
2012 let rhs = Quantity::from_raw(rhs_raw, FIXED_PRECISION);
2013 let result = lhs * rhs;
2014
2015 assert_eq!(lhs_raw.checked_mul(rhs_raw), None);
2016 assert_eq!(result.raw, expected_raw);
2017 assert_eq!(result.precision, FIXED_PRECISION);
2018 }
2019
2020 #[rstest]
2021 #[should_panic(expected = "Overflow occurred when multiplying `Quantity`")]
2022 fn test_mul_panics_when_scaled_result_exceeds_quantity_max() {
2023 let lhs = Quantity::from_raw(QUANTITY_RAW_MAX, FIXED_PRECISION);
2024 let rhs = Quantity::from(2);
2025
2026 let _ = lhs * rhs;
2027 }
2028
2029 #[rstest]
2030 fn test_comparisons() {
2031 assert_eq!(Quantity::new(1.0, 1), Quantity::new(1.0, 1));
2032 assert_eq!(Quantity::new(1.0, 1), Quantity::new(1.0, 2));
2033 assert_ne!(Quantity::new(1.1, 1), Quantity::new(1.0, 1));
2034 assert!(Quantity::new(1.0, 1) <= Quantity::new(1.0, 2));
2035 assert!(Quantity::new(1.1, 1) > Quantity::new(1.0, 1));
2036 assert!(Quantity::new(1.0, 1) >= Quantity::new(1.0, 1));
2037 assert!(Quantity::new(1.0, 1) >= Quantity::new(1.0, 2));
2038 assert!(Quantity::new(1.0, 1) >= Quantity::new(1.0, 2));
2039 assert!(Quantity::new(0.9, 1) < Quantity::new(1.0, 1));
2040 assert!(Quantity::new(0.9, 1) <= Quantity::new(1.0, 2));
2041 assert!(Quantity::new(0.9, 1) <= Quantity::new(1.0, 1));
2042 }
2043
2044 #[rstest]
2045 fn test_debug() {
2046 let quantity = Quantity::from_str("44.12").unwrap();
2047 let result = format!("{quantity:?}");
2048 assert_eq!(result, "Quantity(44.12)");
2049 }
2050
2051 #[rstest]
2052 fn test_display() {
2053 let quantity = Quantity::from_str("44.12").unwrap();
2054 let result = format!("{quantity}");
2055 assert_eq!(result, "44.12");
2056 }
2057
2058 #[rstest]
2059 #[case(44.12, 2, "Quantity(44.12)", "44.12")] #[case(1234.567, 8, "Quantity(1234.56700000)", "1234.56700000")] #[cfg_attr(
2062 feature = "defi",
2063 case(
2064 1_000_000_000_000_000_000.0,
2065 18,
2066 "Quantity(1.000000000000000000)",
2067 "1.000000000000000000"
2068 )
2069 )] fn test_debug_display_precision_handling(
2071 #[case] value: f64,
2072 #[case] precision: u8,
2073 #[case] expected_debug: &str,
2074 #[case] expected_display: &str,
2075 ) {
2076 let quantity = if precision > MAX_FLOAT_PRECISION {
2077 Quantity::from_raw(value as QuantityRaw, precision)
2079 } else {
2080 Quantity::new(value, precision)
2081 };
2082
2083 assert_eq!(format!("{quantity:?}"), expected_debug);
2084 assert_eq!(format!("{quantity}"), expected_display);
2085 }
2086
2087 #[rstest]
2088 fn test_to_formatted_string() {
2089 let qty = Quantity::new(1234.5678, 4);
2090 let formatted = qty.to_formatted_string();
2091 assert_eq!(formatted, "1_234.5678");
2092 assert_eq!(qty.to_string(), "1234.5678");
2093 }
2094
2095 #[rstest]
2096 fn test_saturating_sub() {
2097 let q1 = Quantity::new(100.0, 2);
2098 let q2 = Quantity::new(50.0, 2);
2099 let q3 = Quantity::new(150.0, 2);
2100
2101 let result = q1.saturating_sub(q2);
2102 assert_eq!(result, Quantity::new(50.0, 2));
2103
2104 let result = q1.saturating_sub(q3);
2105 assert_eq!(result, Quantity::zero(2));
2106 assert_eq!(result.raw, 0);
2107 }
2108
2109 #[rstest]
2110 fn test_saturating_sub_overflow_bug() {
2111 use crate::types::fixed::FIXED_PRECISION;
2114 let precision = 3;
2115 let scale = QuantityRaw::from(10u64.pow(u32::from(FIXED_PRECISION - precision)));
2116
2117 let peak_qty = Quantity::from_raw(79 * scale, precision);
2119 let order_qty = Quantity::from_raw(80 * scale, precision);
2120
2121 let result = peak_qty.saturating_sub(order_qty);
2123 assert_eq!(result.raw, 0);
2124 assert_eq!(result, Quantity::zero(precision));
2125 }
2126
2127 #[rstest]
2128 fn test_hash() {
2129 use std::{
2130 collections::hash_map::DefaultHasher,
2131 hash::{Hash, Hasher},
2132 };
2133
2134 let q1 = Quantity::new(100.0, 1);
2135 let q2 = Quantity::new(100.0, 1);
2136 let q3 = Quantity::new(200.0, 1);
2137
2138 let mut s1 = DefaultHasher::new();
2139 let mut s2 = DefaultHasher::new();
2140 let mut s3 = DefaultHasher::new();
2141
2142 q1.hash(&mut s1);
2143 q2.hash(&mut s2);
2144 q3.hash(&mut s3);
2145
2146 assert_eq!(
2147 s1.finish(),
2148 s2.finish(),
2149 "Equal quantities must hash equally"
2150 );
2151 assert_ne!(
2152 s1.finish(),
2153 s3.finish(),
2154 "Different quantities must hash differently"
2155 );
2156 }
2157
2158 #[rstest]
2159 fn test_quantity_serde_json_round_trip() {
2160 let original = Quantity::new(123.456, 3);
2161 let json_str = serde_json::to_string(&original).unwrap();
2162 assert_eq!(json_str, "\"123.456\"");
2163
2164 let deserialized: Quantity = serde_json::from_str(&json_str).unwrap();
2165 assert_eq!(deserialized, original);
2166 assert_eq!(deserialized.precision, 3);
2167 }
2168
2169 #[rstest]
2170 fn test_quantity_serde_json_from_value_round_trip() {
2171 let original = Quantity::new(123.456, 3);
2172 let value = serde_json::to_value(original).unwrap();
2173 assert_eq!(value, serde_json::json!("123.456"));
2174
2175 let deserialized: Quantity = serde_json::from_value(value).unwrap();
2176 assert_eq!(deserialized, original);
2177 assert_eq!(deserialized.precision, 3);
2178 }
2179
2180 #[rstest]
2181 fn test_quantity_deserialize_invalid_string_returns_error() {
2182 let result = serde_json::from_str::<Quantity>("\"not-a-quantity\"");
2183 let error = result.unwrap_err();
2184 assert!(
2185 error.to_string().contains("Error parsing"),
2186 "unexpected message: {error}"
2187 );
2188 }
2189
2190 #[rstest]
2191 fn test_quantity_deserialize_negative_returns_error() {
2192 let result = serde_json::from_str::<Quantity>("\"-1.5\"");
2193 let error = result.unwrap_err();
2194 assert!(
2195 error.to_string().contains("negative"),
2196 "unexpected message: {error}"
2197 );
2198 }
2199
2200 #[rstest]
2201 fn test_from_mantissa_exponent_exact_precision() {
2202 let qty = Quantity::from_mantissa_exponent(12345, -2, 2);
2203 assert_eq!(qty.as_f64(), 123.45);
2204 }
2205
2206 #[rstest]
2207 fn test_from_mantissa_exponent_excess_rounds_down() {
2208 let qty = Quantity::from_mantissa_exponent(12345, -3, 2);
2211 assert_eq!(qty.as_f64(), 12.34);
2212 }
2213
2214 #[rstest]
2215 fn test_from_mantissa_exponent_excess_rounds_up() {
2216 let qty = Quantity::from_mantissa_exponent(12355, -3, 2);
2218 assert_eq!(qty.as_f64(), 12.36);
2219 }
2220
2221 #[rstest]
2222 fn test_from_mantissa_exponent_positive_exponent() {
2223 let qty = Quantity::from_mantissa_exponent(5, 2, 0);
2224 assert_eq!(qty.as_f64(), 500.0);
2225 }
2226
2227 #[rstest]
2228 fn test_from_mantissa_exponent_zero() {
2229 let qty = Quantity::from_mantissa_exponent(0, 2, 2);
2230 assert_eq!(qty.as_f64(), 0.0);
2231 }
2232
2233 #[cfg(feature = "high-precision")]
2234 #[rstest]
2235 fn test_max_raw_precision_16_string_round_trip() {
2236 let quantity = Quantity::from_raw(QUANTITY_RAW_MAX, 16);
2237
2238 let decoded = quantity.to_string().parse::<Quantity>().unwrap();
2239
2240 assert_eq!(decoded, quantity);
2241 assert_eq!(decoded.raw, QUANTITY_RAW_MAX);
2242 assert_eq!(decoded.precision, 16);
2243 }
2244
2245 #[cfg(all(feature = "defi", feature = "high-precision"))]
2246 #[rstest]
2247 fn test_wei_above_decimal_mantissa_formats_exactly() {
2248 let raw = 80_000_000_000_000_000_250_000_000_000_u128;
2249 let qty = Quantity::from_raw(raw, 18);
2250
2251 assert_eq!(qty.to_string(), "80000000000.000000250000000000");
2252 }
2253
2254 #[rstest]
2255 fn test_from_mantissa_exponent_checked_exact_precision() {
2256 let qty = Quantity::from_mantissa_exponent_checked(12345, -2, 2).unwrap();
2257 assert_eq!(qty.as_decimal(), dec!(123.45));
2258 }
2259
2260 #[rstest]
2261 fn test_from_mantissa_exponent_checked_zero_with_large_exponent() {
2262 let qty = Quantity::from_mantissa_exponent_checked(0, 119, 2).unwrap();
2263 assert_eq!(qty.as_decimal(), dec!(0.00));
2264 }
2265
2266 #[rstest]
2267 fn test_from_mantissa_exponent_checked_invalid_precision() {
2268 #[cfg(feature = "defi")]
2269 let invalid_precision = crate::defi::WEI_PRECISION + 1;
2270 #[cfg(not(feature = "defi"))]
2271 let invalid_precision = FIXED_PRECISION + 1;
2272
2273 let error = Quantity::from_mantissa_exponent_checked(1, 0, invalid_precision).unwrap_err();
2274 assert!(error.to_string().contains("`precision` exceeded maximum"));
2275 }
2276
2277 #[rstest]
2278 fn test_from_mantissa_exponent_checked_overflow_returns_error() {
2279 let error = Quantity::from_mantissa_exponent_checked(u64::MAX, 100, 0).unwrap_err();
2280 assert!(
2281 error
2282 .to_string()
2283 .contains("Overflow in Quantity::from_mantissa_exponent")
2284 );
2285 }
2286
2287 #[rstest]
2288 #[should_panic(expected = "Quantity::from_mantissa_exponent")]
2289 fn test_from_mantissa_exponent_overflow_panics() {
2290 let _ = Quantity::from_mantissa_exponent(u64::MAX, 9, 0);
2291 }
2292
2293 #[rstest]
2294 #[should_panic(expected = "exceeds i128 range")]
2295 fn test_from_mantissa_exponent_large_exponent_panics() {
2296 let _ = Quantity::from_mantissa_exponent(1, 119, 0);
2297 }
2298
2299 #[rstest]
2300 fn test_from_mantissa_exponent_zero_with_large_exponent() {
2301 let qty = Quantity::from_mantissa_exponent(0, 119, 0);
2302 assert_eq!(qty.as_f64(), 0.0);
2303 }
2304
2305 #[rstest]
2306 fn test_from_mantissa_exponent_very_negative_exponent_rounds_to_zero() {
2307 let qty = Quantity::from_mantissa_exponent(12345, -120, 2);
2308 assert_eq!(qty.as_f64(), 0.0);
2309 }
2310
2311 #[rstest]
2312 fn test_f64_operations() {
2313 let q = Quantity::new(10.5, 2);
2314 assert_eq!(q + 1.0, 11.5);
2315 assert_eq!(q - 1.0, 9.5);
2316 assert_eq!(q * 2.0, 21.0);
2317 assert_eq!(q / 2.0, 5.25);
2318 }
2319
2320 #[rstest]
2321 fn test_decimal_arithmetic_operations() {
2322 let qty = Quantity::new(100.0, 2);
2323 assert_eq!(qty + dec!(50.25), dec!(150.25));
2324 assert_eq!(qty - dec!(30.50), dec!(69.50));
2325 assert_eq!(qty * dec!(1.5), dec!(150.00));
2326 assert_eq!(qty / dec!(4), dec!(25.00));
2327 }
2328
2329 #[rstest]
2333 #[cfg(feature = "defi")]
2334 #[case::sell_tx_rain_amount(
2335 U256::from_str_radix("42193532365637161405123", 10).unwrap(),
2336 18,
2337 "42193.532365637161405123"
2338 )]
2339 #[case::sell_tx_weth_amount(
2340 U256::from_str_radix("112633187203033110", 10).unwrap(),
2341 18,
2342 "0.112633187203033110"
2343 )]
2344 fn test_from_u256_real_swap_data(
2345 #[case] amount: U256,
2346 #[case] precision: u8,
2347 #[case] expected_str: &str,
2348 ) {
2349 let qty = Quantity::from_u256(amount, precision).unwrap();
2350 assert_eq!(qty.precision, precision);
2351 assert_eq!(qty.as_decimal().to_string(), expected_str);
2352 }
2353
2354 #[rstest]
2355 #[cfg(feature = "defi")]
2356 fn test_from_u256_overflow_returns_typed_error_with_stable_display() {
2357 let error = Quantity::from_u256(U256::MAX, 0).unwrap_err();
2358 match error {
2359 CorrectnessError::PredicateViolation { ref message } => {
2360 assert!(
2361 message.contains("Amount overflow during scaling to fixed precision"),
2362 "unexpected message: {message:?}",
2363 );
2364 }
2365 _ => panic!("expected PredicateViolation, was {error:?}"),
2366 }
2367 }
2368
2369 #[rstest]
2370 #[cfg(feature = "defi")]
2371 fn test_from_u256_rejects_amount_above_quantity_raw_range() {
2372 let amount = U256::from(u128::MAX) + U256::from(1_u8);
2373 let error = Quantity::from_u256(amount, 18).unwrap_err();
2374
2375 assert_eq!(
2376 error,
2377 CorrectnessError::PredicateViolation {
2378 message: format!("U256 scaled amount {amount} exceeds QuantityRaw range"),
2379 }
2380 );
2381 }
2382
2383 #[rstest]
2384 #[cfg(feature = "defi")]
2385 fn test_from_u256_invalid_precision_returns_typed_error() {
2386 let error = Quantity::from_u256(U256::from(1u8), 19).unwrap_err();
2387 match error {
2388 CorrectnessError::PredicateViolation { ref message } => {
2389 assert!(
2390 message.contains("WEI_PRECISION"),
2391 "unexpected message: {message:?}",
2392 );
2393 }
2394 _ => panic!("expected PredicateViolation, was {error:?}"),
2395 }
2396 }
2397
2398 #[rstest]
2399 #[cfg(feature = "defi")]
2400 fn test_from_u256_raw_above_max_returns_typed_error() {
2401 let raw = QUANTITY_RAW_MAX + 1;
2404 let error = Quantity::from_u256(U256::from(raw), FIXED_PRECISION).unwrap_err();
2405 match error {
2406 CorrectnessError::PredicateViolation { ref message } => {
2407 assert!(
2408 message.contains("QUANTITY_RAW_MAX"),
2409 "unexpected message: {message:?}",
2410 );
2411 }
2412 _ => panic!("expected PredicateViolation, was {error:?}"),
2413 }
2414 }
2415}
2416
2417#[cfg(test)]
2418mod property_tests {
2419 use proptest::prelude::*;
2420 use rstest::rstest;
2421
2422 use super::*;
2423 use crate::types::fixed::FIXED_SCALAR_RAW;
2424 #[cfg(not(feature = "defi"))]
2425 use crate::types::fixed::MAX_FLOAT_PRECISION;
2426
2427 fn quantity_value_strategy() -> impl Strategy<Value = f64> {
2429 prop_oneof![
2431 0.00001..1.0,
2433 1.0..100_000.0,
2435 100_000.0..1_000_000.0,
2437 Just(0.0),
2439 Just(QUANTITY_MAX / 2.0),
2441 ]
2442 }
2443
2444 fn precision_strategy() -> impl Strategy<Value = u8> {
2446 let upper = FIXED_PRECISION.min(MAX_FLOAT_PRECISION);
2447 prop_oneof![Just(0u8), 0u8..=upper, Just(FIXED_PRECISION),]
2448 }
2449
2450 fn precision_strategy_non_zero() -> impl Strategy<Value = u8> {
2451 let upper = FIXED_PRECISION.clamp(1, MAX_FLOAT_PRECISION);
2452 prop_oneof![Just(upper), Just(FIXED_PRECISION.max(1)), 1u8..=upper,]
2453 }
2454
2455 fn raw_for_precision_strategy() -> impl Strategy<Value = (QuantityRaw, u8)> {
2456 precision_strategy().prop_flat_map(|precision| {
2457 let step_u128 = 10u128.pow(u32::from(FIXED_PRECISION.saturating_sub(precision)));
2458 #[cfg(feature = "high-precision")]
2459 let max_steps_u128 = QUANTITY_RAW_MAX / step_u128;
2460 #[cfg(not(feature = "high-precision"))]
2461 let max_steps_u128 = u128::from(QUANTITY_RAW_MAX) / step_u128;
2462
2463 (0u128..=max_steps_u128).prop_map(move |steps_u128| {
2464 let raw_u128 = steps_u128 * step_u128;
2465 #[cfg(feature = "high-precision")]
2466 let raw = raw_u128;
2467 #[cfg(not(feature = "high-precision"))]
2468 let raw = raw_u128
2469 .try_into()
2470 .expect("raw value should fit in QuantityRaw");
2471 (raw, precision)
2472 })
2473 })
2474 }
2475
2476 const DECIMAL_MAX_MANTISSA: u128 = 79_228_162_514_264_337_593_543_950_335;
2477
2478 fn decimal_compatible(raw: QuantityRaw, precision: u8) -> bool {
2479 if precision > MAX_FLOAT_PRECISION {
2480 return false;
2481 }
2482 let precision_diff = u32::from(FIXED_PRECISION.saturating_sub(precision));
2483 let divisor = 10u128.pow(precision_diff);
2484 #[cfg(feature = "high-precision")]
2485 let rescaled_raw = raw / divisor;
2486 #[cfg(not(feature = "high-precision"))]
2487 let rescaled_raw = u128::from(raw) / divisor;
2488 rescaled_raw <= DECIMAL_MAX_MANTISSA
2491 }
2492
2493 proptest! {
2494 #[rstest]
2496 fn prop_quantity_serde_round_trip(
2497 (raw, precision) in raw_for_precision_strategy()
2498 ) {
2499 let original = Quantity::from_raw(raw, precision);
2500
2501 let string_repr = original.to_string();
2503 let from_string: Quantity = string_repr.parse().unwrap();
2504 prop_assert_eq!(from_string.raw, original.raw);
2505 prop_assert_eq!(from_string.precision, original.precision);
2506
2507 let json = serde_json::to_string(&original).unwrap();
2509 let from_json: Quantity = serde_json::from_str(&json).unwrap();
2510 prop_assert_eq!(from_json.precision, original.precision);
2511 prop_assert_eq!(from_json.raw, original.raw);
2512 }
2513
2514 #[rstest]
2516 fn prop_quantity_arithmetic_associative(
2517 a in quantity_value_strategy().prop_filter("Reasonable values", |&x| x > 1e-3 && x < 1e6),
2518 b in quantity_value_strategy().prop_filter("Reasonable values", |&x| x > 1e-3 && x < 1e6),
2519 c in quantity_value_strategy().prop_filter("Reasonable values", |&x| x > 1e-3 && x < 1e6),
2520 precision in precision_strategy()
2521 ) {
2522 let q_a = Quantity::new(a, precision);
2523 let q_b = Quantity::new(b, precision);
2524 let q_c = Quantity::new(c, precision);
2525
2526 let expected = q_a
2527 .raw
2528 .checked_add(q_b.raw)
2529 .and_then(|sum| sum.checked_add(q_c.raw))
2530 .filter(|sum| *sum <= QUANTITY_RAW_MAX);
2531
2532 if let Some(expected) = expected {
2533 let left = (q_a + q_b) + q_c;
2534 let right = q_a + (q_b + q_c);
2535 prop_assert_eq!(left.raw, expected);
2536 prop_assert_eq!(right.raw, expected);
2537 }
2538 }
2539
2540 #[rstest]
2542 fn prop_quantity_addition_subtraction_inverse(
2543 base in quantity_value_strategy().prop_filter("Reasonable values", |&x| x < 1e6),
2544 delta in quantity_value_strategy().prop_filter("Reasonable values", |&x| x > 1e-3 && x < 1e6),
2545 precision in precision_strategy()
2546 ) {
2547 let q_base = Quantity::new(base, precision);
2548 let q_delta = Quantity::new(delta, precision);
2549
2550 let expected = q_base
2551 .raw
2552 .checked_add(q_delta.raw)
2553 .filter(|sum| *sum <= QUANTITY_RAW_MAX);
2554
2555 if expected.is_some() {
2556 prop_assert_eq!((q_base + q_delta) - q_delta, q_base);
2557 }
2558 }
2559
2560 #[rstest]
2563 fn prop_quantity_checked_add_matches_spec(
2564 a in quantity_value_strategy(),
2565 b in quantity_value_strategy(),
2566 precision in precision_strategy()
2567 ) {
2568 let q_a = Quantity::new(a, precision);
2569 let q_b = Quantity::new(b, precision);
2570 let expected = q_a.raw
2571 .checked_add(q_b.raw)
2572 .filter(|r| *r <= QUANTITY_RAW_MAX)
2573 .filter(|_| q_a.raw != QUANTITY_UNDEF && q_b.raw != QUANTITY_UNDEF)
2574 .map(|raw| Quantity { raw, precision: q_a.precision.max(q_b.precision) });
2575 prop_assert_eq!(q_a.checked_add(q_b), expected);
2576 }
2577
2578 #[rstest]
2581 fn prop_quantity_checked_sub_matches_spec(
2582 a in quantity_value_strategy(),
2583 b in quantity_value_strategy(),
2584 precision in precision_strategy()
2585 ) {
2586 let q_a = Quantity::new(a, precision);
2587 let q_b = Quantity::new(b, precision);
2588 let expected = q_a.raw
2589 .checked_sub(q_b.raw)
2590 .filter(|_| q_a.raw != QUANTITY_UNDEF && q_b.raw != QUANTITY_UNDEF)
2591 .map(|raw| Quantity { raw, precision: q_a.precision.max(q_b.precision) });
2592 prop_assert_eq!(q_a.checked_sub(q_b), expected);
2593 }
2594
2595 #[rstest]
2597 fn prop_quantity_ordering_transitive(
2598 a in quantity_value_strategy(),
2599 b in quantity_value_strategy(),
2600 c in quantity_value_strategy(),
2601 precision in precision_strategy()
2602 ) {
2603 let q_a = Quantity::new(a, precision);
2604 let q_b = Quantity::new(b, precision);
2605 let q_c = Quantity::new(c, precision);
2606
2607 if q_a <= q_b && q_b <= q_c {
2609 prop_assert!(q_a <= q_c, "Transitivity failed: {} <= {} <= {} but {} > {}",
2610 q_a.as_f64(), q_b.as_f64(), q_c.as_f64(), q_a.as_f64(), q_c.as_f64());
2611 }
2612 }
2613
2614 #[rstest]
2616 fn prop_quantity_string_parsing_precision(
2617 integral in 0u32..1_000_000,
2618 fractional in 0u32..1_000_000,
2619 precision in precision_strategy_non_zero()
2620 ) {
2621 let pow = 10u128.pow(u32::from(precision));
2623 let fractional_mod = u128::from(fractional) % pow;
2624 let fractional_str = format!("{:0width$}", fractional_mod, width = precision as usize);
2625 let quantity_str = format!("{integral}.{fractional_str}");
2626
2627 let parsed: Quantity = quantity_str.parse().unwrap();
2628 prop_assert_eq!(parsed.precision, precision);
2629
2630 let round_trip = parsed.to_string();
2632 let expected_value = format!("{integral}.{fractional_str}");
2633 prop_assert_eq!(round_trip, expected_value);
2634 }
2635
2636 #[rstest]
2638 fn prop_quantity_arithmetic_bounds(
2639 a in quantity_value_strategy(),
2640 b in quantity_value_strategy(),
2641 precision in precision_strategy()
2642 ) {
2643 let q_a = Quantity::new(a, precision);
2644 let q_b = Quantity::new(b, precision);
2645
2646 let sum_f64 = q_a.as_f64() + q_b.as_f64();
2648 if sum_f64.is_finite() && (QUANTITY_MIN..=QUANTITY_MAX).contains(&sum_f64) {
2649 let sum = q_a + q_b;
2650 prop_assert!(sum.as_f64().is_finite());
2651 prop_assert!(!sum.is_undefined());
2652 }
2653
2654 let diff_f64 = q_a.as_f64() - q_b.as_f64();
2656 if diff_f64.is_finite() && (QUANTITY_MIN..=QUANTITY_MAX).contains(&diff_f64) {
2657 let diff = q_a - q_b;
2658 prop_assert!(diff.as_f64().is_finite());
2659 prop_assert!(!diff.is_undefined());
2660 }
2661 }
2662
2663 #[rstest]
2665 fn prop_quantity_multiplication_non_negative(
2666 a in quantity_value_strategy().prop_filter("Reasonable values", |&x| x > 0.0 && x < 10.0),
2667 b in quantity_value_strategy().prop_filter("Reasonable values", |&x| x > 0.0 && x < 10.0),
2668 precision in precision_strategy()
2669 ) {
2670 let q_a = Quantity::new(a, precision);
2671 let q_b = Quantity::new(b, precision);
2672
2673 let raw_product_check = q_a.raw.checked_mul(q_b.raw);
2675
2676 if let Some(raw_product) = raw_product_check {
2677 let scaled_raw = raw_product / FIXED_SCALAR_RAW;
2679 if scaled_raw <= QUANTITY_RAW_MAX {
2680 let product = q_a * q_b;
2682 prop_assert!(product.as_f64() >= 0.0, "Quantity multiplication produced negative value: {}", product.as_f64());
2683 }
2684 }
2685 }
2686
2687 #[rstest]
2689 fn prop_quantity_zero_addition_identity(
2690 value in quantity_value_strategy(),
2691 precision in precision_strategy()
2692 ) {
2693 let q = Quantity::new(value, precision);
2694 let zero = Quantity::zero(precision);
2695
2696 prop_assert_eq!(q + zero, q);
2698 prop_assert_eq!(zero + q, q);
2699 }
2700 }
2701
2702 proptest! {
2703 #[rstest]
2705 fn prop_quantity_as_decimal_preserves_precision(
2706 (raw, precision) in raw_for_precision_strategy()
2707 ) {
2708 prop_assume!(decimal_compatible(raw, precision));
2709 let quantity = Quantity::from_raw(raw, precision);
2710 let decimal = quantity.as_decimal();
2711 prop_assert_eq!(decimal.scale(), u32::from(precision));
2712 }
2713
2714 #[rstest]
2716 fn prop_quantity_as_decimal_matches_display(
2717 (raw, precision) in raw_for_precision_strategy()
2718 ) {
2719 prop_assume!(decimal_compatible(raw, precision));
2720 let quantity = Quantity::from_raw(raw, precision);
2721 let display_str = format!("{quantity}");
2722 let decimal_str = quantity.as_decimal().to_string();
2723 prop_assert_eq!(display_str, decimal_str);
2724 }
2725
2726 #[rstest]
2728 fn prop_quantity_from_decimal_roundtrip(
2729 (raw, precision) in raw_for_precision_strategy()
2730 ) {
2731 prop_assume!(decimal_compatible(raw, precision));
2732 let original = Quantity::from_raw(raw, precision);
2733 let decimal = original.as_decimal();
2734 let reconstructed = Quantity::from_decimal(decimal).unwrap();
2735 prop_assert_eq!(original.raw, reconstructed.raw);
2736 prop_assert_eq!(original.precision, reconstructed.precision);
2737 }
2738
2739 #[rstest]
2741 fn prop_quantity_from_raw_round_trip(
2742 (raw, precision) in raw_for_precision_strategy()
2743 ) {
2744 let quantity = Quantity::from_raw(raw, precision);
2745 prop_assert_eq!(quantity.raw, raw);
2746 prop_assert_eq!(quantity.precision, precision);
2747 }
2748 }
2749}