Skip to main content

icydb_schema/
nat_big.rs

1//! Canonical arbitrary-precision unsigned-integer atom.
2
3use crate::{
4    Decimal, NumericValue,
5    integer_wire::{self, IntegerWire},
6};
7use candid::{CandidType, Nat as WrappedNat};
8use derive_more::{Add, AddAssign, Sub, SubAssign};
9use num_bigint::BigUint;
10use serde::{Deserialize, Serialize};
11use std::{
12    fmt,
13    iter::{Product, Sum},
14    ops::{Div, DivAssign, Mul, MulAssign},
15    str::FromStr,
16};
17
18//
19// NatBig
20//
21
22#[derive(
23    Add,
24    AddAssign,
25    CandidType,
26    Clone,
27    Debug,
28    Default,
29    Eq,
30    PartialEq,
31    Hash,
32    Ord,
33    PartialOrd,
34    Sub,
35    SubAssign,
36)]
37/// Arbitrary-precision unsigned integer used by schema and typed values.
38///
39/// Candid uses its native integer type; human-readable Serde uses decimal text.
40/// Binary Serde uses native small integers and tagged little-endian wide bytes.
41pub struct NatBig(WrappedNat);
42
43impl NatBig {
44    /// Return the magnitude's bit length without allocating an encoded copy.
45    #[must_use]
46    pub fn magnitude_bits(&self) -> u64 {
47        self.0.0.bits()
48    }
49
50    /// Return the exact unsigned LEB128 byte length without allocating or encoding.
51    #[must_use]
52    pub fn leb128_len(&self) -> u64 {
53        self.magnitude_bits().div_ceil(7).max(1)
54    }
55
56    /// Construct from the canonical Candid natural-number representation.
57    #[must_use]
58    pub const fn from_candid(value: WrappedNat) -> Self {
59        Self(value)
60    }
61
62    /// Construct from a `num_bigint` unsigned integer.
63    #[must_use]
64    pub fn from_biguint(value: BigUint) -> Self {
65        Self::from_candid(WrappedNat::from(value))
66    }
67
68    /// Borrow little-endian base-2^32 limbs without allocation.
69    pub fn u32_digits(&self) -> impl DoubleEndedIterator<Item = u32> + ExactSizeIterator + '_ {
70        self.0.0.iter_u32_digits()
71    }
72
73    /// Convert to `u128` when the value is in range.
74    #[must_use]
75    pub fn to_u128(&self) -> Option<u128> {
76        let big = &self.0.0;
77
78        u128::try_from(big).ok()
79    }
80
81    /// Convert to `u64` when the value is in range.
82    #[must_use]
83    pub fn to_u64(&self) -> Option<u64> {
84        let big = &self.0.0;
85
86        u64::try_from(big).ok()
87    }
88
89    /// Serialize this arbitrary-precision natural for internal hash and sort-key framing.
90    #[must_use]
91    pub fn to_leb128(&self) -> Vec<u8> {
92        self.leb128_bytes().collect()
93    }
94
95    /// Iterate canonical unsigned LEB128 bytes with constant scratch and no allocation.
96    pub fn leb128_bytes(&self) -> impl Iterator<Item = u8> + '_ {
97        crate::leb128::bytes(self.u32_digits(), false, self.leb128_len())
98    }
99
100    pub(crate) fn to_magnitude_bytes(&self) -> Vec<u8> {
101        self.0.0.to_bytes_be()
102    }
103
104    pub(crate) fn from_magnitude_bytes(magnitude: &[u8]) -> Self {
105        Self::from_biguint(BigUint::from_bytes_be(magnitude))
106    }
107
108    /// Saturating addition (unbounded; equivalent to normal addition).
109    #[must_use]
110    pub fn saturating_add(self, rhs: Self) -> Self {
111        Self(self.0 + rhs.0)
112    }
113
114    /// Saturating subtraction; clamps at zero on underflow.
115    #[must_use]
116    pub fn saturating_sub(self, rhs: Self) -> Self {
117        if rhs > self {
118            return Self::default();
119        }
120
121        Self(self.0 - rhs.0)
122    }
123}
124
125impl<'de> Deserialize<'de> for NatBig {
126    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
127        integer_wire::deserialize_integer(deserializer)
128    }
129}
130
131impl fmt::Display for NatBig {
132    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133        self.0.fmt(f)
134    }
135}
136
137impl FromStr for NatBig {
138    type Err = <WrappedNat as FromStr>::Err;
139
140    fn from_str(s: &str) -> Result<Self, Self::Err> {
141        WrappedNat::from_str(s).map(Self::from_candid)
142    }
143}
144
145impl Div for NatBig {
146    type Output = Self;
147
148    fn div(self, other: Self) -> Self::Output {
149        Self(self.0 / other.0)
150    }
151}
152
153impl DivAssign for NatBig {
154    fn div_assign(&mut self, other: Self) {
155        self.0 /= other.0;
156    }
157}
158
159impl From<u64> for NatBig {
160    fn from(n: u64) -> Self {
161        Self::from_candid(WrappedNat::from(n))
162    }
163}
164
165impl From<u32> for NatBig {
166    fn from(n: u32) -> Self {
167        Self::from_candid(WrappedNat::from(n))
168    }
169}
170
171impl IntegerWire for NatBig {
172    fn from_signed(value: i64) -> Option<Self> {
173        u64::try_from(value).ok().map(Self::from)
174    }
175
176    fn from_unsigned(value: u64) -> Self {
177        Self::from(value)
178    }
179
180    fn from_wire_bytes(value: &[u8]) -> Option<Self> {
181        integer_wire::unsigned_body(value)
182            .map(|body| Self::from_biguint(BigUint::from_bytes_le(body)))
183    }
184}
185
186impl Mul for NatBig {
187    type Output = Self;
188
189    fn mul(self, other: Self) -> Self::Output {
190        Self(self.0 * other.0)
191    }
192}
193
194impl MulAssign for NatBig {
195    fn mul_assign(&mut self, other: Self) {
196        self.0 *= other.0;
197    }
198}
199
200impl NumericValue for NatBig {
201    fn try_to_decimal(&self) -> Option<Decimal> {
202        self.to_u128().and_then(Decimal::from_u128)
203    }
204
205    fn try_from_decimal(value: Decimal) -> Option<Self> {
206        value.to_u128().map(WrappedNat::from).map(Self::from_candid)
207    }
208}
209
210impl Product for NatBig {
211    fn product<I: Iterator<Item = Self>>(iter: I) -> Self {
212        iter.fold(Self::from(1_u32), |acc, value| acc * value)
213    }
214}
215
216impl Serialize for NatBig {
217    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
218        if serializer.is_human_readable() {
219            return serializer.collect_str(&self.0.0);
220        }
221        if let Some(value) = self.to_u64() {
222            return serializer.serialize_u64(value);
223        }
224        serializer.serialize_bytes(&integer_wire::unsigned_bytes(self.u32_digits()))
225    }
226}
227
228impl Sum for NatBig {
229    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
230        iter.fold(Self::default(), |acc, x| acc + x)
231    }
232}
233
234impl TryFrom<i32> for NatBig {
235    type Error = std::num::TryFromIntError;
236
237    fn try_from(n: i32) -> Result<Self, Self::Error> {
238        let v = Self::from_candid(WrappedNat::from(u32::try_from(n)?));
239        Ok(v)
240    }
241}