Skip to main content

icydb_schema/
nat_big.rs

1//! Canonical arbitrary-precision unsigned-integer atom.
2
3use crate::{Decimal, NumericValue};
4use candid::{CandidType, Nat as WrappedNat};
5use derive_more::{Add, AddAssign, Sub, SubAssign};
6use num_bigint::BigUint;
7use serde::{Deserialize, Serialize};
8use std::{
9    fmt,
10    iter::{Product, Sum},
11    ops::{Div, DivAssign, Mul, MulAssign},
12    str::FromStr,
13};
14
15//
16// NatBig
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 unsigned integer used by schema and typed values.
37pub struct NatBig(WrappedNat);
38
39impl NatBig {
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    /// Construct from the canonical Candid natural-number representation.
47    #[must_use]
48    pub const fn from_candid(value: WrappedNat) -> Self {
49        Self(value)
50    }
51
52    /// Construct from a `num_bigint` unsigned integer.
53    #[must_use]
54    pub fn from_biguint(value: BigUint) -> Self {
55        Self::from_candid(WrappedNat::from(value))
56    }
57
58    /// Return base-2^32 limbs for decimal key encoding.
59    ///
60    /// This allocates for the returned limb vector.
61    #[must_use]
62    pub fn u32_digits(&self) -> Vec<u32> {
63        self.0.0.to_u32_digits()
64    }
65
66    /// Convert to `u128` when the value is in range.
67    #[must_use]
68    pub fn to_u128(&self) -> Option<u128> {
69        let big = &self.0.0;
70
71        u128::try_from(big).ok()
72    }
73
74    /// Convert to `u64` when the value is in range.
75    #[must_use]
76    pub fn to_u64(&self) -> Option<u64> {
77        let big = &self.0.0;
78
79        u64::try_from(big).ok()
80    }
81
82    /// Serialize this arbitrary-precision natural for internal hash and sort-key framing.
83    #[must_use]
84    pub fn to_leb128(&self) -> Vec<u8> {
85        let mut out = Vec::new();
86        let encoded = self.0.encode(&mut out);
87        debug_assert!(
88            encoded.is_ok(),
89            "Vec-backed unsigned LEB128 encoding failed"
90        );
91
92        out
93    }
94
95    pub(crate) fn to_magnitude_bytes(&self) -> Vec<u8> {
96        self.0.0.to_bytes_be()
97    }
98
99    pub(crate) fn from_magnitude_bytes(magnitude: &[u8]) -> Self {
100        Self::from_biguint(BigUint::from_bytes_be(magnitude))
101    }
102
103    /// Saturating addition (unbounded; equivalent to normal addition).
104    #[must_use]
105    pub fn saturating_add(self, rhs: Self) -> Self {
106        Self(self.0 + rhs.0)
107    }
108
109    /// Saturating subtraction; clamps at zero on underflow.
110    #[must_use]
111    pub fn saturating_sub(self, rhs: Self) -> Self {
112        if rhs > self {
113            return Self::default();
114        }
115
116        Self(self.0 - rhs.0)
117    }
118}
119
120impl fmt::Display for NatBig {
121    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122        self.0.fmt(f)
123    }
124}
125
126impl FromStr for NatBig {
127    type Err = <WrappedNat as FromStr>::Err;
128
129    fn from_str(s: &str) -> Result<Self, Self::Err> {
130        WrappedNat::from_str(s).map(Self::from_candid)
131    }
132}
133
134impl Div for NatBig {
135    type Output = Self;
136
137    fn div(self, other: Self) -> Self::Output {
138        Self(self.0 / other.0)
139    }
140}
141
142impl DivAssign for NatBig {
143    fn div_assign(&mut self, other: Self) {
144        self.0 /= other.0;
145    }
146}
147
148impl From<u64> for NatBig {
149    fn from(n: u64) -> Self {
150        Self::from_candid(WrappedNat::from(n))
151    }
152}
153
154impl From<u32> for NatBig {
155    fn from(n: u32) -> Self {
156        Self::from_candid(WrappedNat::from(n))
157    }
158}
159
160impl Mul for NatBig {
161    type Output = Self;
162
163    fn mul(self, other: Self) -> Self::Output {
164        Self(self.0 * other.0)
165    }
166}
167
168impl MulAssign for NatBig {
169    fn mul_assign(&mut self, other: Self) {
170        self.0 *= other.0;
171    }
172}
173
174impl NumericValue for NatBig {
175    fn try_to_decimal(&self) -> Option<Decimal> {
176        self.to_u128().and_then(Decimal::from_u128)
177    }
178
179    fn try_from_decimal(value: Decimal) -> Option<Self> {
180        value.to_u128().map(WrappedNat::from).map(Self::from_candid)
181    }
182}
183
184impl Product for NatBig {
185    fn product<I: Iterator<Item = Self>>(iter: I) -> Self {
186        iter.fold(Self::from(1_u32), |acc, value| acc * value)
187    }
188}
189
190impl Sum for NatBig {
191    fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
192        iter.fold(Self::default(), |acc, x| acc + x)
193    }
194}
195
196impl TryFrom<i32> for NatBig {
197    type Error = std::num::TryFromIntError;
198
199    fn try_from(n: i32) -> Result<Self, Self::Error> {
200        let v = Self::from_candid(WrappedNat::from(u32::try_from(n)?));
201        Ok(v)
202    }
203}