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    /// Return the magnitude's bit length without allocating an encoded copy.
41    #[must_use]
42    pub fn magnitude_bits(&self) -> u64 {
43        self.0.0.bits()
44    }
45
46    /// Return the exact signed LEB128 byte length without allocating or encoding.
47    #[must_use]
48    pub fn leb128_len(&self) -> u64 {
49        let bits = self.magnitude_bits();
50        // Signed groups reserve a sign bit. A negative power of two needs one
51        // fewer bit than the corresponding positive value (-64 fits; 64 does
52        // not). Only a seven-bit boundary can change the resulting byte count.
53        let negative_boundary = self.0.0.sign() == num_bigint::Sign::Minus
54            && bits.is_multiple_of(7)
55            && self.0.0.trailing_zeros() == Some(bits.saturating_sub(1));
56        bits / 7 + 1 - u64::from(negative_boundary)
57    }
58
59    /// Construct from the canonical Candid signed-integer representation.
60    #[must_use]
61    pub const fn from_candid(value: WrappedInt) -> Self {
62        Self(value)
63    }
64
65    /// Construct from a `num_bigint` signed integer.
66    #[must_use]
67    pub fn from_bigint(value: BigInt) -> Self {
68        Self::from_candid(WrappedInt::from(value))
69    }
70
71    /// Return sign and base-2^32 magnitude limbs for decimal key encoding.
72    ///
73    /// This allocates for the returned limb vector.
74    #[must_use]
75    pub fn sign_and_u32_digits(&self) -> (bool, Vec<u32>) {
76        (
77            self.0.0.cmp(&0.into()).is_lt(),
78            self.0.0.magnitude().to_u32_digits(),
79        )
80    }
81
82    /// Convert to `i128` when the value is in range.
83    #[must_use]
84    pub fn to_i128(&self) -> Option<i128> {
85        let big = &self.0.0;
86
87        i128::try_from(big).ok()
88    }
89
90    /// Convert to `i64` when the value is in range.
91    #[must_use]
92    pub fn to_i64(&self) -> Option<i64> {
93        let big = &self.0.0;
94
95        i64::try_from(big).ok()
96    }
97
98    /// Serialize this arbitrary-precision integer for internal hash and sort-key framing.
99    #[must_use]
100    pub fn to_leb128(&self) -> Vec<u8> {
101        let mut out = Vec::new();
102        let encoded = self.0.encode(&mut out);
103        debug_assert!(encoded.is_ok(), "Vec-backed signed LEB128 encoding failed");
104
105        out
106    }
107
108    pub(crate) fn to_sign_and_magnitude_bytes(&self) -> (bool, Vec<u8>) {
109        let (sign, magnitude) = self.0.0.to_bytes_be();
110        (sign == num_bigint::Sign::Minus, magnitude)
111    }
112
113    pub(crate) fn from_sign_and_magnitude_bytes(negative: bool, magnitude: &[u8]) -> Self {
114        let sign = if magnitude.is_empty() {
115            num_bigint::Sign::NoSign
116        } else if negative {
117            num_bigint::Sign::Minus
118        } else {
119            num_bigint::Sign::Plus
120        };
121        Self::from_bigint(BigInt::from_bytes_be(sign, magnitude))
122    }
123
124    /// Saturating addition (unbounded; equivalent to normal addition).
125    #[must_use]
126    pub fn saturating_add(self, rhs: Self) -> Self {
127        Self(self.0 + rhs.0)
128    }
129
130    /// Saturating subtraction (unbounded; equivalent to normal subtraction).
131    #[must_use]
132    pub fn saturating_sub(self, rhs: Self) -> Self {
133        Self(self.0 - rhs.0)
134    }
135}
136
137impl fmt::Display for IntBig {
138    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139        self.0.fmt(f)
140    }
141}
142
143impl FromStr for IntBig {
144    type Err = <WrappedInt as FromStr>::Err;
145
146    fn from_str(s: &str) -> Result<Self, Self::Err> {
147        WrappedInt::from_str(s).map(Self::from_candid)
148    }
149}
150
151impl Div for IntBig {
152    type Output = Self;
153
154    fn div(self, other: Self) -> Self::Output {
155        Self(self.0 / other.0)
156    }
157}
158
159impl DivAssign for IntBig {
160    fn div_assign(&mut self, other: Self) {
161        self.0 /= other.0;
162    }
163}
164
165impl From<i32> for IntBig {
166    fn from(n: i32) -> Self {
167        Self::from_candid(WrappedInt::from(n))
168    }
169}
170
171impl From<i64> for IntBig {
172    fn from(n: i64) -> Self {
173        Self::from_candid(WrappedInt::from(n))
174    }
175}
176
177impl Mul for IntBig {
178    type Output = Self;
179
180    fn mul(self, other: Self) -> Self::Output {
181        Self(self.0 * other.0)
182    }
183}
184
185impl MulAssign for IntBig {
186    fn mul_assign(&mut self, other: Self) {
187        self.0 *= other.0;
188    }
189}
190
191impl Neg for IntBig {
192    type Output = Self;
193
194    fn neg(self) -> Self::Output {
195        Self::from_bigint(-self.0.0)
196    }
197}
198
199impl NumericValue for IntBig {
200    fn try_to_decimal(&self) -> Option<Decimal> {
201        self.to_i128().and_then(Decimal::from_i128)
202    }
203
204    fn try_from_decimal(value: Decimal) -> Option<Self> {
205        value.to_i128().map(WrappedInt::from).map(Self::from_candid)
206    }
207}
208
209impl Product for IntBig {
210    fn product<I: Iterator<Item = Self>>(iter: I) -> Self {
211        iter.fold(Self::from(1), |acc, value| acc * value)
212    }
213}
214
215impl Sum for IntBig {
216    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
217        iter.fold(Self::default(), |acc, x| acc + x)
218    }
219}