1use crate::bignum;
9use crate::object::{box_, dec, inc, 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)]
18struct Big {
19 header: Header,
20 negative: bool,
21 len: usize,
22}
23
24pub(crate) fn alloc_big(limbs: &[u64], negative: bool) -> Obj {
26 unsafe {
27 let big = crate::object::allocate(size_of::<Big>() + size_of_val(limbs)).cast::<Big>();
28 big.write(Big { header: new_header(TAG_MPZ, 0, 0), negative, len: limbs.len() });
29 std::ptr::copy_nonoverlapping(limbs.as_ptr(), big.add(1).cast::<u64>(), limbs.len());
30 Obj::from_header(big.cast())
31 }
32}
33
34pub(crate) unsafe fn big_parts<'a>(o: Obj) -> (bool, &'a [u64]) {
36 let big = o.header().cast::<Big>();
37 ((*big).negative, std::slice::from_raw_parts(big.add(1).cast::<u64>(), (*big).len))
38}
39
40#[inline(always)]
43pub(crate) unsafe fn unshared(o: Obj) -> Obj {
44 if is_scalar(o) {
46 return o;
47 }
48 unshared_object(o)
49}
50
51#[inline(never)]
52unsafe fn unshared_object(o: Obj) -> Obj {
53 if crate::object::is_persistent(o) {
54 return o;
55 }
56 let (negative, limbs) = big_parts(o);
57 alloc_big(limbs, negative)
58}
59
60#[inline(always)]
67pub(crate) unsafe fn owned(o: Obj) -> Obj {
68 if is_scalar(o) || crate::object::is_exclusive(o) {
69 return o;
70 }
71 owned_shared(o)
72}
73
74#[inline(never)]
75unsafe fn owned_shared(o: Obj) -> Obj {
76 let copy = unshared_object(o);
77 dec(o);
79 copy
80}
81
82pub(crate) unsafe fn free_big(o: Obj) {
83 let big = o.header().cast::<Big>();
84 crate::object::deallocate(big.cast(), size_of::<Big>() + (*big).len * size_of::<u64>());
85}
86
87unsafe fn limbs<'a>(o: Obj, small: &'a mut [u64; 1]) -> &'a [u64] {
89 if is_scalar(o) {
90 small[0] = unbox(o) as u64;
91 if small[0] == 0 {
92 &[]
93 } else {
94 small
95 }
96 } else {
97 big_parts(o).1
98 }
99}
100
101fn from_limbs(mut limbs: &[u64]) -> Obj {
103 while let [rest @ .., 0] = limbs {
105 limbs = rest;
106 }
107 match limbs {
108 [] => box_(0),
109 [single] if *single <= MAX_SMALL as u64 => box_(*single as usize),
110 _ => alloc_big(limbs, false),
111 }
112}
113
114fn from_u64(value: u64) -> Obj {
115 from_limbs(&[value])
116}
117
118fn from_u128(value: u128) -> Obj {
119 from_limbs(&[value as u64, (value >> 64) as u64])
120}
121
122unsafe fn binary(a: Obj, b: Obj, op: impl FnOnce(&[u64], &[u64]) -> bignum::Limbs) -> Obj {
124 let (mut sa, mut sb) = ([0u64; 1], [0u64; 1]);
125 from_limbs(&op(limbs(a, &mut sa), limbs(b, &mut sb)))
126}
127
128unsafe fn compare(a: Obj, b: Obj) -> Ordering {
129 if is_scalar(a) && is_scalar(b) {
130 return unbox(a).cmp(&unbox(b));
131 }
132 let (mut sa, mut sb) = ([0u64; 1], [0u64; 1]);
133 bignum::compare(limbs(a, &mut sa), limbs(b, &mut sb))
134}
135
136unsafe fn small(o: Obj) -> Option<usize> {
138 is_scalar(o).then(|| unbox(o))
139}
140
141pub fn usize_to_nat(n: usize) -> Obj {
142 from_u64(n as u64)
143}
144
145pub fn unsigned_to_nat(n: u32) -> Obj {
146 from_u64(n as u64)
147}
148
149pub fn uint64_to_nat(n: u64) -> Obj {
150 from_u64(n)
151}
152
153pub fn uint8_to_nat(n: u8) -> Obj {
154 box_(n as usize)
155}
156
157pub fn uint16_to_nat(n: u16) -> Obj {
158 box_(n as usize)
159}
160
161pub fn uint32_to_nat(n: u32) -> Obj {
162 from_u64(n as u64)
163}
164
165pub fn cstr_to_nat(digits: &str) -> Obj {
167 from_limbs(&bignum::from_decimal(digits).expect("inlean: malformed Nat literal"))
168}
169
170unsafe fn low_bits(o: Obj) -> u64 {
172 let mut scratch = [0u64; 1];
173 limbs(o, &mut scratch).first().copied().unwrap_or(0)
174}
175
176macro_rules! of_nat {
177 ($($name:ident $mk:ident $ty:ty),*) => {$(
178 pub unsafe fn $name(a: Obj) -> $ty {
180 low_bits(a) as $ty
181 }
182
183 pub unsafe fn $mk(a: Obj) -> $ty {
185 let result = low_bits(a) as $ty;
186 dec(a);
187 result
188 }
189 )*};
190}
191
192of_nat!(
193 uint8_of_nat uint8_of_nat_mk u8,
194 uint16_of_nat uint16_of_nat_mk u16,
195 uint32_of_nat uint32_of_nat_mk u32,
196 uint64_of_nat uint64_of_nat_mk u64,
197 usize_of_nat usize_of_nat_mk usize
198);
199
200pub unsafe fn int8_of_nat(a: Obj) -> u8 {
201 low_bits(a) as u8
202}
203
204pub unsafe fn int16_of_nat(a: Obj) -> u16 {
205 low_bits(a) as u16
206}
207
208pub unsafe fn int32_of_nat(a: Obj) -> u32 {
209 low_bits(a) as u32
210}
211
212pub unsafe fn int64_of_nat(a: Obj) -> u64 {
213 low_bits(a)
214}
215
216pub unsafe fn isize_of_nat(a: Obj) -> usize {
217 low_bits(a) as usize
218}
219
220pub unsafe fn nat_succ(a: Obj) -> Obj {
221 nat_add(a, box_(1))
222}
223
224pub unsafe fn nat_add(a: Obj, b: Obj) -> Obj {
225 if is_scalar(a) && is_scalar(b) {
226 return from_u64(unbox(a) as u64 + unbox(b) as u64);
228 }
229 binary(a, b, bignum::add)
230}
231
232pub unsafe fn nat_sub(a: Obj, b: Obj) -> Obj {
234 if is_scalar(a) && is_scalar(b) {
235 return box_(unbox(a).saturating_sub(unbox(b)));
236 }
237 if compare(a, b) == Ordering::Less {
238 return box_(0);
239 }
240 binary(a, b, bignum::sub)
241}
242
243pub unsafe fn nat_pred(a: Obj) -> Obj {
244 nat_sub(a, box_(1))
245}
246
247pub unsafe fn nat_mul(a: Obj, b: Obj) -> Obj {
248 if is_scalar(a) && is_scalar(b) {
249 return from_u128(unbox(a) as u128 * unbox(b) as u128);
250 }
251 binary(a, b, bignum::mul)
252}
253
254pub unsafe fn nat_div(a: Obj, b: Obj) -> Obj {
256 if is_scalar(a) && is_scalar(b) {
257 return box_(unbox(a).checked_div(unbox(b)).unwrap_or(0));
258 }
259 if b == box_(0) {
260 return box_(0);
261 }
262 binary(a, b, |x, y| match bignum::power_of_two(y) {
263 Some(bits) => bignum::shr(x, bits),
264 None => bignum::divrem(x, y).0,
265 })
266}
267
268pub unsafe fn nat_div_exact(a: Obj, b: Obj) -> Obj {
270 nat_div(a, b)
271}
272
273pub unsafe fn nat_mod(a: Obj, b: Obj) -> Obj {
275 if is_scalar(a) && is_scalar(b) {
276 return box_(unbox(a).checked_rem(unbox(b)).unwrap_or(unbox(a)));
277 }
278 let (mut sa, mut sb) = ([0u64; 1], [0u64; 1]);
279 let (x, y) = (limbs(a, &mut sa), limbs(b, &mut sb));
280 let bits = bignum::power_of_two(y);
283 let unchanged = match bits {
284 Some(bits) => bignum::bit_length(x) <= bits,
285 None => y.is_empty() || bignum::compare(x, y) == Ordering::Less,
286 };
287 if unchanged {
288 inc(a);
289 return a;
290 }
291 from_limbs(&match bits {
292 Some(bits) => bignum::low_bits(x, bits),
293 None => bignum::divrem(x, y).1,
294 })
295}
296
297pub unsafe fn nat_dec_eq(a: Obj, b: Obj) -> u8 {
298 (compare(a, b) == Ordering::Equal) as u8
299}
300
301pub unsafe fn nat_dec_lt(a: Obj, b: Obj) -> u8 {
302 (compare(a, b) == Ordering::Less) as u8
303}
304
305pub unsafe fn nat_dec_le(a: Obj, b: Obj) -> u8 {
306 (compare(a, b) != Ordering::Greater) as u8
307}
308
309pub unsafe fn nat_land(a: Obj, b: Obj) -> Obj {
310 binary(a, b, |x, y| bignum::bitwise(x, y, |p, q| p & q))
311}
312
313pub unsafe fn nat_lor(a: Obj, b: Obj) -> Obj {
314 binary(a, b, |x, y| bignum::bitwise(x, y, |p, q| p | q))
315}
316
317pub unsafe fn nat_lxor(a: Obj, b: Obj) -> Obj {
318 binary(a, b, |x, y| bignum::bitwise(x, y, |p, q| p ^ q))
319}
320
321fn too_large(what: &str) -> ! {
323 panic!("inlean: out of memory: {what} is too large")
324}
325
326pub unsafe fn nat_shiftl(a: Obj, b: Obj) -> Obj {
327 if a == box_(0) {
328 return a;
329 }
330 let bits = small(b).unwrap_or_else(|| too_large("the shift amount"));
331 binary(a, b, |x, _| bignum::shl(x, bits))
332}
333
334pub unsafe fn nat_shiftr(a: Obj, b: Obj) -> Obj {
335 match small(b) {
336 Some(bits) => binary(a, b, |x, _| bignum::shr(x, bits)),
337 None => box_(0),
339 }
340}
341
342pub unsafe fn nat_pow(a: Obj, b: Obj) -> Obj {
343 if a == box_(0) || a == box_(1) {
344 return if b == box_(0) { box_(1) } else { a };
346 }
347 let exponent = small(b).unwrap_or_else(|| too_large("the exponent"));
348 binary(a, b, |x, _| bignum::pow(x, exponent))
349}
350
351pub unsafe fn nat_gcd(a: Obj, b: Obj) -> Obj {
352 binary(a, b, bignum::gcd)
353}
354
355pub unsafe fn nat_log2(a: Obj) -> Obj {
357 let mut scratch = [0u64; 1];
358 box_(bignum::bit_length(limbs(a, &mut scratch)).saturating_sub(1))
359}
360
361pub unsafe fn nat_powmod(base: Obj, exponent: Obj, modulus: Obj) -> Obj {
362 let (mut sb, mut se, mut sm) = ([0u64; 1], [0u64; 1], [0u64; 1]);
363 let (base, exponent, modulus) = (limbs(base, &mut sb), limbs(exponent, &mut se), limbs(modulus, &mut sm));
364 if modulus.is_empty() {
365 let exponent = match exponent {
367 [] => 0,
368 [single] if *single <= MAX_SMALL as u64 => *single as usize,
369 _ => too_large("the exponent"),
370 };
371 return from_limbs(&bignum::pow(base, exponent));
372 }
373 let reduce = |x: &[u64]| bignum::divrem(x, modulus).1;
374 let mut result = reduce(&[1]);
375 let mut square = reduce(base);
376 for bit in 0..bignum::bit_length(exponent) {
377 if exponent[bit / 64] >> (bit % 64) & 1 == 1 {
378 result = reduce(&bignum::mul(&result, &square));
379 }
380 square = reduce(&bignum::mul(&square, &square));
381 }
382 from_limbs(&result)
383}
384
385pub unsafe fn float_of_nat(a: Obj) -> f64 {
387 let mut scratch = [0u64; 1];
388 let limbs = limbs(a, &mut scratch);
389 match limbs {
390 [] => 0.0,
391 [single] => *single as f64,
392 _ => {
393 let bits = bignum::bit_length(limbs);
396 let shift = bits - 64;
397 let mut top = bignum::shr(limbs, shift)[0];
398 if *bignum::shl(&[top], shift) != *limbs {
399 top |= 1;
400 }
401 (top as f64) * 2f64.powi(shift as i32)
402 }
403 }
404}
405
406pub unsafe fn to_decimal(a: Obj) -> String {
408 let mut scratch = [0u64; 1];
409 bignum::to_decimal(limbs(a, &mut scratch))
410}
411
412pub unsafe fn to_u128(a: Obj) -> Option<u128> {
414 let mut scratch = [0u64; 1];
415 match limbs(a, &mut scratch) {
416 [] => Some(0),
417 [low] => Some(*low as u128),
418 [low, high] => Some((*high as u128) << 64 | *low as u128),
419 _ => None,
420 }
421}
422
423pub fn of_u128(value: u128) -> Obj {
424 from_u128(value)
425}
426
427pub unsafe fn ordering(a: Obj, b: Obj) -> Ordering {
428 compare(a, b)
429}
430
431pub(crate) fn of_limbs(limbs: &[u64]) -> Obj {
436 from_limbs(limbs)
437}
438
439pub(crate) unsafe fn with_limbs<R>(a: Obj, read: impl FnOnce(&[u64]) -> R) -> R {
441 let mut scratch = [0u64; 1];
442 read(limbs(a, &mut scratch))
443}
444
445pub(crate) const OPS: &[&str] = &[
446 "usize_to_nat", "uint64_to_nat", "uint8_to_nat", "uint16_to_nat", "uint32_to_nat",
447 "uint8_of_nat", "uint16_of_nat", "uint32_of_nat", "uint64_of_nat", "usize_of_nat",
448 "uint8_of_nat_mk", "uint16_of_nat_mk", "uint32_of_nat_mk", "uint64_of_nat_mk", "usize_of_nat_mk",
449 "int8_of_nat", "int16_of_nat", "int32_of_nat", "int64_of_nat", "isize_of_nat",
450 "nat_succ", "nat_add", "nat_sub", "nat_pred", "nat_mul", "nat_div", "nat_div_exact", "nat_mod",
451 "nat_dec_eq", "nat_dec_lt", "nat_dec_le", "nat_land", "nat_lor", "nat_lxor", "nat_shiftl",
452 "nat_shiftr", "nat_pow", "nat_gcd", "nat_log2", "nat_powmod", "float_of_nat",
453];