Skip to main content

icydb_schema/
int_big.rs

1//! Canonical arbitrary-precision signed-integer atom.
2
3use crate::{Decimal, NumericValue};
4use candid::{CandidType, Int as WrappedInt};
5use derive_more::{Add, AddAssign, Sub, SubAssign};
6use num_bigint::BigInt;
7use serde::{Deserialize, Serialize};
8use std::{
9    fmt,
10    iter::{Product, Sum},
11    ops::{Div, DivAssign, Mul, MulAssign, Neg},
12    str::FromStr,
13};
14
15//
16// IntBig
17//
18
19#[derive(
20    Add,
21    AddAssign,
22    CandidType,
23    Clone,
24    Debug,
25    Default,
26    Eq,
27    PartialEq,
28    Hash,
29    Ord,
30    PartialOrd,
31    Serialize,
32    Deserialize,
33    Sub,
34    SubAssign,
35)]
36/// Arbitrary-precision signed integer used by schema and typed values.
37pub struct IntBig(WrappedInt);
38
39impl IntBig {
40    /// Construct from the canonical Candid signed-integer representation.
41    #[must_use]
42    pub const fn from_candid(value: WrappedInt) -> Self {
43        Self(value)
44    }
45
46    /// Construct from a `num_bigint` signed integer.
47    #[must_use]
48    pub fn from_bigint(value: BigInt) -> Self {
49        Self::from_candid(WrappedInt::from(value))
50    }
51
52    /// Return sign and base-2^32 magnitude limbs for decimal key encoding.
53    ///
54    /// This allocates for the returned limb vector.
55    #[must_use]
56    pub fn sign_and_u32_digits(&self) -> (bool, Vec<u32>) {
57        (
58            self.0.0.cmp(&0.into()).is_lt(),
59            self.0.0.magnitude().to_u32_digits(),
60        )
61    }
62
63    /// Convert to `i128` when the value is in range.
64    #[must_use]
65    pub fn to_i128(&self) -> Option<i128> {
66        let big = &self.0.0;
67
68        i128::try_from(big).ok()
69    }
70
71    /// Convert to `i64` when the value is in range.
72    #[must_use]
73    pub fn to_i64(&self) -> Option<i64> {
74        let big = &self.0.0;
75
76        i64::try_from(big).ok()
77    }
78
79    /// Serialize this arbitrary-precision integer for internal hash and sort-key framing.
80    #[must_use]
81    pub fn to_leb128(&self) -> Vec<u8> {
82        let mut out = Vec::new();
83        let encoded = self.0.encode(&mut out);
84        debug_assert!(encoded.is_ok(), "Vec-backed signed LEB128 encoding failed");
85
86        out
87    }
88
89    pub(crate) fn to_sign_and_magnitude_bytes(&self) -> (bool, Vec<u8>) {
90        let (sign, magnitude) = self.0.0.to_bytes_be();
91        (sign == num_bigint::Sign::Minus, magnitude)
92    }
93
94    pub(crate) fn from_sign_and_magnitude_bytes(negative: bool, magnitude: &[u8]) -> Self {
95        let sign = if magnitude.is_empty() {
96            num_bigint::Sign::NoSign
97        } else if negative {
98            num_bigint::Sign::Minus
99        } else {
100            num_bigint::Sign::Plus
101        };
102        Self::from_bigint(BigInt::from_bytes_be(sign, magnitude))
103    }
104
105    /// Saturating addition (unbounded; equivalent to normal addition).
106    #[must_use]
107    pub fn saturating_add(self, rhs: Self) -> Self {
108        Self(self.0 + rhs.0)
109    }
110
111    /// Saturating subtraction (unbounded; equivalent to normal subtraction).
112    #[must_use]
113    pub fn saturating_sub(self, rhs: Self) -> Self {
114        Self(self.0 - rhs.0)
115    }
116}
117
118impl fmt::Display for IntBig {
119    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
120        self.0.fmt(f)
121    }
122}
123
124impl FromStr for IntBig {
125    type Err = <WrappedInt as FromStr>::Err;
126
127    fn from_str(s: &str) -> Result<Self, Self::Err> {
128        WrappedInt::from_str(s).map(Self::from_candid)
129    }
130}
131
132impl Div for IntBig {
133    type Output = Self;
134
135    fn div(self, other: Self) -> Self::Output {
136        Self(self.0 / other.0)
137    }
138}
139
140impl DivAssign for IntBig {
141    fn div_assign(&mut self, other: Self) {
142        self.0 /= other.0;
143    }
144}
145
146impl From<i32> for IntBig {
147    fn from(n: i32) -> Self {
148        Self::from_candid(WrappedInt::from(n))
149    }
150}
151
152impl From<i64> for IntBig {
153    fn from(n: i64) -> Self {
154        Self::from_candid(WrappedInt::from(n))
155    }
156}
157
158impl Mul for IntBig {
159    type Output = Self;
160
161    fn mul(self, other: Self) -> Self::Output {
162        Self(self.0 * other.0)
163    }
164}
165
166impl MulAssign for IntBig {
167    fn mul_assign(&mut self, other: Self) {
168        self.0 *= other.0;
169    }
170}
171
172impl Neg for IntBig {
173    type Output = Self;
174
175    fn neg(self) -> Self::Output {
176        Self::from_bigint(-self.0.0)
177    }
178}
179
180impl NumericValue for IntBig {
181    fn try_to_decimal(&self) -> Option<Decimal> {
182        self.to_i128().and_then(Decimal::from_i128)
183    }
184
185    fn try_from_decimal(value: Decimal) -> Option<Self> {
186        value.to_i128().map(WrappedInt::from).map(Self::from_candid)
187    }
188}
189
190impl Product for IntBig {
191    fn product<I: Iterator<Item = Self>>(iter: I) -> Self {
192        iter.fold(Self::from(1), |acc, value| acc * value)
193    }
194}
195
196impl Sum for IntBig {
197    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
198        iter.fold(Self::default(), |acc, x| acc + x)
199    }
200}