1use crate::bignum;
9use crate::object::{box_, dec, is_scalar, new_header, unbox, Header, Obj, TAG_MPZ};
10use std::cmp::Ordering;
11
12pub const MAX_SMALL: usize = usize::MAX >> 1;
14
15#[repr(C)]
17struct Big {
18 header: Header,
19 negative: bool,
20 limbs: Vec<u64>,
21}
22
23pub(crate) fn alloc_big(limbs: Vec<u64>, negative: bool) -> Obj {
25 crate::object::count_object(1);
26 let big = Box::new(Big { header: new_header(TAG_MPZ, 0, 0), negative, limbs });
27 Obj::from_header(Box::into_raw(big).cast())
28}
29
30pub(crate) unsafe fn big_parts<'a>(o: Obj) -> (bool, &'a [u64]) {
32 let big = &*o.header().cast::<Big>();
33 (big.negative, &big.limbs)
34}
35
36pub(crate) unsafe fn free_big(o: Obj) {
37 crate::object::count_object(-1);
38 drop(Box::from_raw(o.header().cast::<Big>()));
39}
40
41unsafe fn limbs<'a>(o: Obj, small: &'a mut [u64; 1]) -> &'a [u64] {
43 if is_scalar(o) {
44 small[0] = unbox(o) as u64;
45 if small[0] == 0 {
46 &[]
47 } else {
48 small
49 }
50 } else {
51 &(*o.header().cast::<Big>()).limbs
52 }
53}
54
55fn from_limbs(mut limbs: Vec<u64>) -> Obj {
56 while limbs.last() == Some(&0) {
58 limbs.pop();
59 }
60 match limbs.as_slice() {
61 [] => box_(0),
62 [single] if *single <= MAX_SMALL as u64 => box_(*single as usize),
63 _ => alloc_big(limbs, false),
64 }
65}
66
67fn from_u64(value: u64) -> Obj {
68 from_limbs(if value == 0 { Vec::new() } else { vec![value] })
69}
70
71fn from_u128(value: u128) -> Obj {
72 let mut limbs = vec![value as u64, (value >> 64) as u64];
73 while limbs.last() == Some(&0) {
74 limbs.pop();
75 }
76 from_limbs(limbs)
77}
78
79unsafe fn binary(a: Obj, b: Obj, op: impl FnOnce(&[u64], &[u64]) -> Vec<u64>) -> Obj {
81 let (mut sa, mut sb) = ([0u64; 1], [0u64; 1]);
82 from_limbs(op(limbs(a, &mut sa), limbs(b, &mut sb)))
83}
84
85unsafe fn compare(a: Obj, b: Obj) -> Ordering {
86 if is_scalar(a) && is_scalar(b) {
87 return unbox(a).cmp(&unbox(b));
88 }
89 let (mut sa, mut sb) = ([0u64; 1], [0u64; 1]);
90 bignum::compare(limbs(a, &mut sa), limbs(b, &mut sb))
91}
92
93unsafe fn small(o: Obj) -> Option<usize> {
95 is_scalar(o).then(|| unbox(o))
96}
97
98pub fn usize_to_nat(n: usize) -> Obj {
99 from_u64(n as u64)
100}
101
102pub fn unsigned_to_nat(n: u32) -> Obj {
103 from_u64(n as u64)
104}
105
106pub fn uint64_to_nat(n: u64) -> Obj {
107 from_u64(n)
108}
109
110pub fn uint8_to_nat(n: u8) -> Obj {
111 box_(n as usize)
112}
113
114pub fn uint16_to_nat(n: u16) -> Obj {
115 box_(n as usize)
116}
117
118pub fn uint32_to_nat(n: u32) -> Obj {
119 from_u64(n as u64)
120}
121
122pub fn cstr_to_nat(digits: &str) -> Obj {
124 from_limbs(bignum::from_decimal(digits).expect("inlean: malformed Nat literal"))
125}
126
127unsafe fn low_bits(o: Obj) -> u64 {
129 let mut scratch = [0u64; 1];
130 limbs(o, &mut scratch).first().copied().unwrap_or(0)
131}
132
133macro_rules! of_nat {
134 ($($name:ident $mk:ident $ty:ty),*) => {$(
135 pub unsafe fn $name(a: Obj) -> $ty {
137 low_bits(a) as $ty
138 }
139
140 pub unsafe fn $mk(a: Obj) -> $ty {
142 let result = low_bits(a) as $ty;
143 dec(a);
144 result
145 }
146 )*};
147}
148
149of_nat!(
150 uint8_of_nat uint8_of_nat_mk u8,
151 uint16_of_nat uint16_of_nat_mk u16,
152 uint32_of_nat uint32_of_nat_mk u32,
153 uint64_of_nat uint64_of_nat_mk u64,
154 usize_of_nat usize_of_nat_mk usize
155);
156
157pub unsafe fn int8_of_nat(a: Obj) -> u8 {
158 low_bits(a) as u8
159}
160
161pub unsafe fn int16_of_nat(a: Obj) -> u16 {
162 low_bits(a) as u16
163}
164
165pub unsafe fn int32_of_nat(a: Obj) -> u32 {
166 low_bits(a) as u32
167}
168
169pub unsafe fn int64_of_nat(a: Obj) -> u64 {
170 low_bits(a)
171}
172
173pub unsafe fn isize_of_nat(a: Obj) -> usize {
174 low_bits(a) as usize
175}
176
177pub unsafe fn nat_succ(a: Obj) -> Obj {
178 nat_add(a, box_(1))
179}
180
181pub unsafe fn nat_add(a: Obj, b: Obj) -> Obj {
182 if is_scalar(a) && is_scalar(b) {
183 return from_u64(unbox(a) as u64 + unbox(b) as u64);
185 }
186 binary(a, b, bignum::add)
187}
188
189pub unsafe fn nat_sub(a: Obj, b: Obj) -> Obj {
191 if is_scalar(a) && is_scalar(b) {
192 return box_(unbox(a).saturating_sub(unbox(b)));
193 }
194 if compare(a, b) == Ordering::Less {
195 return box_(0);
196 }
197 binary(a, b, bignum::sub)
198}
199
200pub unsafe fn nat_pred(a: Obj) -> Obj {
201 nat_sub(a, box_(1))
202}
203
204pub unsafe fn nat_mul(a: Obj, b: Obj) -> Obj {
205 if is_scalar(a) && is_scalar(b) {
206 return from_u128(unbox(a) as u128 * unbox(b) as u128);
207 }
208 binary(a, b, bignum::mul)
209}
210
211pub unsafe fn nat_div(a: Obj, b: Obj) -> Obj {
213 if is_scalar(a) && is_scalar(b) {
214 return box_(unbox(a).checked_div(unbox(b)).unwrap_or(0));
215 }
216 if b == box_(0) {
217 return box_(0);
218 }
219 binary(a, b, |x, y| bignum::divrem(x, y).0)
220}
221
222pub unsafe fn nat_div_exact(a: Obj, b: Obj) -> Obj {
224 nat_div(a, b)
225}
226
227pub unsafe fn nat_mod(a: Obj, b: Obj) -> Obj {
229 if is_scalar(a) && is_scalar(b) {
230 return box_(unbox(a).checked_rem(unbox(b)).unwrap_or(unbox(a)));
231 }
232 if b == box_(0) {
233 return binary(a, b, |x, _| x.to_vec());
234 }
235 binary(a, b, |x, y| bignum::divrem(x, y).1)
236}
237
238pub unsafe fn nat_dec_eq(a: Obj, b: Obj) -> u8 {
239 (compare(a, b) == Ordering::Equal) as u8
240}
241
242pub unsafe fn nat_dec_lt(a: Obj, b: Obj) -> u8 {
243 (compare(a, b) == Ordering::Less) as u8
244}
245
246pub unsafe fn nat_dec_le(a: Obj, b: Obj) -> u8 {
247 (compare(a, b) != Ordering::Greater) as u8
248}
249
250pub unsafe fn nat_land(a: Obj, b: Obj) -> Obj {
251 binary(a, b, |x, y| bignum::bitwise(x, y, |p, q| p & q))
252}
253
254pub unsafe fn nat_lor(a: Obj, b: Obj) -> Obj {
255 binary(a, b, |x, y| bignum::bitwise(x, y, |p, q| p | q))
256}
257
258pub unsafe fn nat_lxor(a: Obj, b: Obj) -> Obj {
259 binary(a, b, |x, y| bignum::bitwise(x, y, |p, q| p ^ q))
260}
261
262fn too_large(what: &str) -> ! {
264 panic!("inlean: out of memory: {what} is too large")
265}
266
267pub unsafe fn nat_shiftl(a: Obj, b: Obj) -> Obj {
268 if a == box_(0) {
269 return a;
270 }
271 let bits = small(b).unwrap_or_else(|| too_large("the shift amount"));
272 binary(a, b, |x, _| bignum::shl(x, bits))
273}
274
275pub unsafe fn nat_shiftr(a: Obj, b: Obj) -> Obj {
276 match small(b) {
277 Some(bits) => binary(a, b, |x, _| bignum::shr(x, bits)),
278 None => box_(0),
280 }
281}
282
283pub unsafe fn nat_pow(a: Obj, b: Obj) -> Obj {
284 if a == box_(0) || a == box_(1) {
285 return if b == box_(0) { box_(1) } else { a };
287 }
288 let exponent = small(b).unwrap_or_else(|| too_large("the exponent"));
289 binary(a, b, |x, _| bignum::pow(x, exponent))
290}
291
292pub unsafe fn nat_gcd(a: Obj, b: Obj) -> Obj {
293 binary(a, b, bignum::gcd)
294}
295
296pub unsafe fn nat_log2(a: Obj) -> Obj {
298 let mut scratch = [0u64; 1];
299 box_(bignum::bit_length(limbs(a, &mut scratch)).saturating_sub(1))
300}
301
302pub unsafe fn nat_powmod(base: Obj, exponent: Obj, modulus: Obj) -> Obj {
303 let (mut sb, mut se, mut sm) = ([0u64; 1], [0u64; 1], [0u64; 1]);
304 let (base, exponent, modulus) = (limbs(base, &mut sb), limbs(exponent, &mut se), limbs(modulus, &mut sm));
305 if modulus.is_empty() {
306 let exponent = match exponent {
308 [] => 0,
309 [single] if *single <= MAX_SMALL as u64 => *single as usize,
310 _ => too_large("the exponent"),
311 };
312 return from_limbs(bignum::pow(base, exponent));
313 }
314 let reduce = |x: &[u64]| bignum::divrem(x, modulus).1;
315 let mut result = reduce(&[1]);
316 let mut square = reduce(base);
317 for bit in 0..bignum::bit_length(exponent) {
318 if exponent[bit / 64] >> (bit % 64) & 1 == 1 {
319 result = reduce(&bignum::mul(&result, &square));
320 }
321 square = reduce(&bignum::mul(&square, &square));
322 }
323 from_limbs(result)
324}
325
326pub unsafe fn float_of_nat(a: Obj) -> f64 {
328 let mut scratch = [0u64; 1];
329 let limbs = limbs(a, &mut scratch);
330 match limbs {
331 [] => 0.0,
332 [single] => *single as f64,
333 _ => {
334 let bits = bignum::bit_length(limbs);
337 let shift = bits - 64;
338 let mut top = bignum::shr(limbs, shift)[0];
339 if bignum::shl(&[top], shift) != limbs {
340 top |= 1;
341 }
342 (top as f64) * 2f64.powi(shift as i32)
343 }
344 }
345}
346
347pub unsafe fn to_decimal(a: Obj) -> String {
349 let mut scratch = [0u64; 1];
350 bignum::to_decimal(limbs(a, &mut scratch))
351}
352
353pub unsafe fn to_u128(a: Obj) -> Option<u128> {
355 let mut scratch = [0u64; 1];
356 match limbs(a, &mut scratch) {
357 [] => Some(0),
358 [low] => Some(*low as u128),
359 [low, high] => Some((*high as u128) << 64 | *low as u128),
360 _ => None,
361 }
362}
363
364pub fn of_u128(value: u128) -> Obj {
365 from_u128(value)
366}
367
368pub unsafe fn ordering(a: Obj, b: Obj) -> Ordering {
369 compare(a, b)
370}
371
372pub(crate) fn of_limbs(limbs: Vec<u64>) -> Obj {
375 from_limbs(limbs)
376}
377
378pub(crate) const OPS: &[&str] = &[
379 "usize_to_nat", "uint64_to_nat", "uint8_to_nat", "uint16_to_nat", "uint32_to_nat",
380 "uint8_of_nat", "uint16_of_nat", "uint32_of_nat", "uint64_of_nat", "usize_of_nat",
381 "uint8_of_nat_mk", "uint16_of_nat_mk", "uint32_of_nat_mk", "uint64_of_nat_mk", "usize_of_nat_mk",
382 "int8_of_nat", "int16_of_nat", "int32_of_nat", "int64_of_nat", "isize_of_nat",
383 "nat_succ", "nat_add", "nat_sub", "nat_pred", "nat_mul", "nat_div", "nat_div_exact", "nat_mod",
384 "nat_dec_eq", "nat_dec_lt", "nat_dec_le", "nat_land", "nat_lor", "nat_lxor", "nat_shiftl",
385 "nat_shiftr", "nat_pow", "nat_gcd", "nat_log2", "nat_powmod", "float_of_nat",
386];