Skip to main content

tvm_ffi/big_int/
mod.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 *   http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied.  See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19//! Integers with inline `i64` storage and arbitrary-precision arithmetic.
20mod int_ops;
21
22use crate::derive::Object;
23use crate::error::{Error, OVERFLOW_ERROR, Result, VALUE_ERROR};
24use crate::object::{Object, ObjectArc, ObjectCoreWithExtraItems, unsafe_};
25use crate::type_traits::AnyCompatible;
26use std::alloc::Layout;
27use std::cmp::Ordering;
28use std::ffi::c_void;
29use std::fmt::{Debug, Display, Write as _};
30use std::hash::{Hash, Hasher};
31use std::ops::{
32    Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Div, DivAssign,
33    Mul, MulAssign, Neg, Not, Rem, RemAssign, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign,
34};
35use std::str::FromStr;
36use std::sync::atomic::AtomicU64;
37use tvm_ffi_sys::TVMFFIObjectDeleterFlagBitMask::kTVMFFIObjectDeleterFlagBitMaskWeak;
38use tvm_ffi_sys::TVMFFITypeIndex as TypeIndex;
39use tvm_ffi_sys::{COMBINED_REF_COUNT_BOTH_ONE, TVMFFIAny, TVMFFIAnyDataUnion, TVMFFIObject};
40
41/// An arbitrary-precision signed integer.
42///
43/// Its layout is part of the stable FFI ABI, so a `BigInt` passes across
44/// languages without conversion. A value that fits `i64` is stored inline, and
45/// a wider value uses a heap object of its minimal two's-complement `i64`
46/// words, least-significant word first. Results are always in that canonical
47/// form, so equality is word-wise.
48///
49/// Arithmetic is unbounded and signed. `/` and `%` truncate toward zero;
50/// [`floor_div`](Self::floor_div) and [`floor_mod`](Self::floor_mod) round down.
51/// Bitwise operations sign-extend infinitely, and negative shift counts are errors.
52/// Like the primitive operators, `/`, `%`, `<<` and `>>` panic on those errors;
53/// the `try_*` methods return them instead, as ffi callbacks need since a panic
54/// cannot unwind across them.
55#[repr(C)]
56pub struct BigInt {
57    data: TVMFFIAny,
58}
59
60// SAFETY: a `BigInt` is immutable: an inline `i64` or an immutable big-integer object.
61unsafe impl Send for BigInt {}
62unsafe impl Sync for BigInt {}
63
64// BigIntObj for heap-allocated integers: the word count, then the canonical
65// two's-complement words as trailing items. Mirrors C++ `detail::BigIntObj`.
66#[repr(C)]
67#[derive(Object)]
68#[object(type_key = "ffi.BigInt", unsafe type_index = TypeIndex::kTVMFFIBigInt, final)]
69struct BigIntObj {
70    object: Object,
71    size: usize,
72}
73
74unsafe impl ObjectCoreWithExtraItems for BigIntObj {
75    type ExtraItem = i64;
76    #[inline]
77    /// Get the count of extra items (the logical word count)
78    fn extra_items_count(this: &Self) -> usize {
79        this.size
80    }
81}
82
83// `BigInt::try_build` allocates from the C allocator like C++
84// `make_inplace_array_object`, so it can prune the logical size in place (C++
85// `ShrinkSize`): `free` needs no layout, unlike Rust's global allocator.
86unsafe extern "C" {
87    fn malloc(size: usize) -> *mut c_void;
88    fn free(ptr: *mut c_void);
89}
90
91/// Release an object from `BigInt::try_build`: free the allocation; the words
92/// need no destructor.
93unsafe extern "C" fn delete_obj(ptr: *mut c_void, flags: i32) {
94    if flags & kTVMFFIObjectDeleterFlagBitMaskWeak as i32 != 0 {
95        unsafe { free(ptr) };
96    }
97}
98
99/// Layout of an object with `len` words; `None` beyond `isize::MAX` bytes.
100fn obj_layout(len: usize) -> Option<Layout> {
101    let words = Layout::array::<i64>(len).ok()?;
102    Some(Layout::new::<BigIntObj>().extend(words).ok()?.0)
103}
104
105impl BigInt {
106    /// Create the integer zero.
107    pub fn new() -> Self {
108        Self::from_i64(0)
109    }
110
111    #[inline]
112    fn from_i64(value: i64) -> Self {
113        Self {
114            data: TVMFFIAny {
115                type_index: TypeIndex::kTVMFFIInt as i32,
116                small_str_len: 0,
117                data_union: TVMFFIAnyDataUnion { v_int64: value },
118            },
119        }
120    }
121
122    /// Take ownership of a canonical multiword object without an extra reference.
123    #[inline]
124    fn from_obj(obj: *mut BigIntObj) -> Self {
125        Self {
126            data: TVMFFIAny {
127                type_index: TypeIndex::kTVMFFIBigInt as i32,
128                small_str_len: 0,
129                data_union: TVMFFIAnyDataUnion {
130                    v_obj: obj.cast::<TVMFFIObject>(),
131                },
132            },
133        }
134    }
135
136    /// Create from two's-complement `i64` words, least-significant word first.
137    ///
138    /// Redundant sign-extension words are pruned and a value that fits `i64`
139    /// is stored inline; an empty slice is zero.
140    #[doc(hidden)]
141    #[inline]
142    pub fn from_words(words: &[i64]) -> Self {
143        let size = int_ops::normalized_len(words);
144        if size <= 1 {
145            return Self::from_i64(words.first().copied().unwrap_or(0));
146        }
147        // Allocated at its final length, so the crate's generic extra-items deleter fits.
148        unsafe {
149            let mut obj = ObjectArc::new_with_extra_items(BigIntObj {
150                object: Object::new(),
151                size,
152            });
153            let items = BigIntObj::extra_items_ptr(ObjectArc::as_mut_ptr(&mut obj));
154            std::ptr::copy_nonoverlapping(words.as_ptr(), items, size);
155            Self::from_obj(ObjectArc::into_raw(obj) as *mut BigIntObj)
156        }
157    }
158
159    /// Build from `len` words, word `i` being `word(i)` called in increasing order,
160    /// written straight into a fresh object whose redundant sign words are then
161    /// pruned in place; `None` when the object cannot be allocated.
162    #[inline]
163    fn try_build(len: usize, mut word: impl FnMut(usize) -> i64) -> Option<Self> {
164        let layout = obj_layout(len)?;
165        unsafe {
166            let obj = malloc(layout.size()).cast::<BigIntObj>();
167            if obj.is_null() {
168                return None;
169            }
170            let data = obj.add(1).cast::<i64>();
171            for i in 0..len {
172                data.add(i).write(word(i));
173            }
174            let size = int_ops::normalized_len(std::slice::from_raw_parts(data, len));
175            if size <= 1 {
176                let value = if size == 1 { *data } else { 0 };
177                free(obj.cast());
178                return Some(Self::from_i64(value));
179            }
180            obj.cast::<TVMFFIObject>().write(TVMFFIObject {
181                combined_ref_count: AtomicU64::new(COMBINED_REF_COUNT_BOTH_ONE),
182                type_index: TypeIndex::kTVMFFIBigInt as i32,
183                __padding: 0,
184                deleter: Some(delete_obj),
185            });
186            std::ptr::addr_of_mut!((*obj).size).write(size);
187            Some(Self::from_obj(obj))
188        }
189    }
190
191    /// Like `try_build`, but like `Vec`, exhaustion aborts.
192    #[inline]
193    fn build(len: usize, word: impl FnMut(usize) -> i64) -> Self {
194        Self::try_build(len, word).unwrap_or_else(|| {
195            std::alloc::handle_alloc_error(obj_layout(len).unwrap_or(Layout::new::<BigIntObj>()))
196        })
197    }
198
199    /// Borrow the canonical two's-complement words, least-significant word first.
200    ///
201    /// The slice is never empty and its last word carries the sign.
202    #[doc(hidden)]
203    pub fn words(&self) -> &[i64] {
204        unsafe {
205            if self.data.type_index == TypeIndex::kTVMFFIInt as i32 {
206                std::slice::from_ref(&self.data.data_union.v_int64)
207            } else {
208                BigIntObj::extra_items(self.data.data_union.v_obj as *const BigIntObj)
209            }
210        }
211    }
212
213    /// Whether the value is negative.
214    pub fn is_negative(&self) -> bool {
215        int_ops::is_negative(self.words())
216    }
217
218    /// Whether the value is zero.
219    #[inline]
220    pub fn is_zero(&self) -> bool {
221        self.to_i64() == Some(0)
222    }
223
224    /// Return the value when it fits `i64`.
225    ///
226    /// See also `i64::try_from(&big)`, which returns an `OverflowError` instead.
227    #[inline]
228    pub fn to_i64(&self) -> Option<i64> {
229        if self.data.type_index == TypeIndex::kTVMFFIInt as i32 {
230            Some(unsafe { self.data.data_union.v_int64 })
231        } else {
232            None
233        }
234    }
235
236    /// Return the value when it fits `u64`.
237    pub fn to_u64(&self) -> Option<u64> {
238        match *self.words() {
239            [w0] => u64::try_from(w0).ok(),
240            [w0, 0] => Some(w0 as u64),
241            _ => None,
242        }
243    }
244
245    /// Return the value when it fits `i128`.
246    pub fn to_i128(&self) -> Option<i128> {
247        match *self.words() {
248            [w0] => Some(i128::from(w0)),
249            [w0, w1] => Some((i128::from(w1) << 64) | i128::from(w0 as u64)),
250            _ => None,
251        }
252    }
253
254    /// Return the value when it fits `u128`.
255    pub fn to_u128(&self) -> Option<u128> {
256        let combine = |w0: i64, w1: i64| (u128::from(w1 as u64) << 64) | u128::from(w0 as u64);
257        match *self.words() {
258            [w0] => u128::try_from(w0).ok(),
259            [w0, w1] if w1 >= 0 => Some(combine(w0, w1)),
260            [w0, w1, 0] => Some(combine(w0, w1)),
261            _ => None,
262        }
263    }
264
265    /// Convert to the nearest finite double, rounding ties to even.
266    ///
267    /// Raises `OverflowError` when the value rounds beyond the finite range.
268    pub fn to_f64(&self) -> Result<f64> {
269        match self.to_i64() {
270            Some(value) => Ok(value as f64),
271            None => int_ops::to_f64(self.words()),
272        }
273    }
274
275    /// Quotient rounded toward zero; raises `ZeroDivisionError`.
276    pub fn try_div(&self, rhs: &BigInt) -> Result<BigInt> {
277        div_impl(self, rhs)
278    }
279
280    /// Remainder of truncating division, zero or with the dividend's sign.
281    pub fn try_rem(&self, rhs: &BigInt) -> Result<BigInt> {
282        rem_impl(self, rhs)
283    }
284
285    /// Truncating quotient and remainder in one pass; raises `ZeroDivisionError`.
286    pub fn div_rem(&self, rhs: &BigInt) -> Result<(BigInt, BigInt)> {
287        if let (Some(x), Some(y)) = (self.to_i64(), rhs.to_i64())
288            && let Some(q) = int_ops::trunc_div_i64(x, y)?
289        {
290            return Ok((Self::from_i64(q), Self::from_i64(x.wrapping_rem(y))));
291        }
292        int_ops::div_rem(self.words(), rhs.words())
293    }
294
295    /// Quotient rounded toward negative infinity; raises `ZeroDivisionError`.
296    pub fn floor_div(&self, rhs: &BigInt) -> Result<BigInt> {
297        floor_div_impl(self, rhs)
298    }
299
300    /// Remainder of floor division, zero or with the divisor's sign.
301    pub fn floor_mod(&self, rhs: &BigInt) -> Result<BigInt> {
302        floor_mod_impl(self, rhs)
303    }
304
305    /// Left shift; negative counts raise `ValueError`, excessive growth `OverflowError`.
306    pub fn try_shl<C: Into<BigInt>>(&self, count: C) -> Result<BigInt> {
307        shl_impl(self, &count.into())
308    }
309
310    /// Sign-extending right shift; negative counts raise `ValueError`.
311    pub fn try_shr<C: Into<BigInt>>(&self, count: C) -> Result<BigInt> {
312        shr_impl(self, &count.into())
313    }
314}
315
316impl Default for BigInt {
317    #[inline]
318    fn default() -> Self {
319        Self::new()
320    }
321}
322
323/// Macro to implement From for integer types that always fit i64
324macro_rules! impl_big_int_from_int {
325    ($($int_type:ty),* $(,)?) => {
326        $(
327            impl From<$int_type> for BigInt {
328                #[inline]
329                fn from(value: $int_type) -> Self {
330                    Self::from_i64(value as i64)
331                }
332            }
333        )*
334    };
335}
336
337impl_big_int_from_int!(i8, i16, i32, i64, isize, u8, u16, u32);
338
339impl From<bool> for BigInt {
340    #[inline]
341    fn from(value: bool) -> Self {
342        Self::from_i64(i64::from(value))
343    }
344}
345
346impl From<u64> for BigInt {
347    fn from(value: u64) -> Self {
348        match i64::try_from(value) {
349            Ok(value) => Self::from_i64(value),
350            Err(_) => Self::from_words(&[value as i64, 0]),
351        }
352    }
353}
354
355impl From<usize> for BigInt {
356    #[inline]
357    fn from(value: usize) -> Self {
358        Self::from(value as u64)
359    }
360}
361
362impl From<i128> for BigInt {
363    fn from(value: i128) -> Self {
364        match i64::try_from(value) {
365            Ok(value) => Self::from_i64(value),
366            // The arithmetic shift keeps the sign in the high word.
367            Err(_) => Self::from_words(&[value as i64, (value >> 64) as i64]),
368        }
369    }
370}
371
372impl From<u128> for BigInt {
373    fn from(value: u128) -> Self {
374        match i64::try_from(value) {
375            Ok(value) => Self::from_i64(value),
376            // The zero guard keeps the value positive; normalization prunes it when redundant.
377            Err(_) => Self::from_words(&[value as i64, (value >> 64) as i64, 0]),
378        }
379    }
380}
381
382// Narrowing to a primitive integer, as std's `TryFrom` between integer types.
383macro_rules! impl_try_from_big_int {
384    ($($t:ty => $to:ident),*) => {$(
385        impl TryFrom<&BigInt> for $t {
386            type Error = Error;
387
388            fn try_from(value: &BigInt) -> Result<Self> {
389                value.$to().ok_or_else(|| {
390                    Error::new(OVERFLOW_ERROR, &format!("{} does not fit in {}", value, stringify!($t)))
391                })
392            }
393        }
394    )*};
395}
396
397impl_try_from_big_int!(i64 => to_i64, u64 => to_u64, i128 => to_i128, u128 => to_u128);
398
399impl TryFrom<f64> for BigInt {
400    type Error = Error;
401
402    /// Convert a finite double by truncating toward zero.
403    ///
404    /// NaN raises `ValueError` and infinity raises `OverflowError`.
405    fn try_from(value: f64) -> Result<Self> {
406        // The upper bound is exclusive: i64::MAX rounds up to 2^63 as a double.
407        const LOWER: f64 = i64::MIN as f64;
408        if (LOWER..-LOWER).contains(&value) {
409            return Ok(Self::from_i64(value as i64));
410        }
411        if value.is_nan() {
412            return Err(Error::new(VALUE_ERROR, "Cannot convert NaN to BigInt"));
413        }
414        if value.is_infinite() {
415            return Err(Error::new(
416                OVERFLOW_ERROR,
417                "Cannot convert infinity to BigInt",
418            ));
419        }
420        // |value| >= 2^63 is an integer: shift the 53-bit significand to its binary exponent.
421        let bits = value.to_bits();
422        let exponent = ((bits >> 52) & 0x7ff) as i64 - 1075;
423        let significand = ((bits & ((1u64 << 52) - 1)) | (1u64 << 52)) as i64;
424        let magnitude = Self::from_i64(significand) << exponent;
425        Ok(if value < 0.0 { -magnitude } else { magnitude })
426    }
427}
428
429impl FromStr for BigInt {
430    type Err = Error;
431
432    /// Parse an optionally signed decimal integer; anything else raises `ValueError`.
433    fn from_str(text: &str) -> Result<Self> {
434        if let Ok(value) = text.parse::<i64>() {
435            return Ok(Self::from_i64(value));
436        }
437        let (negative, digits) = match text.as_bytes().first() {
438            Some(b'-') => (true, &text[1..]),
439            Some(b'+') => (false, &text[1..]),
440            _ => (false, text),
441        };
442        if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
443            return Err(Error::new(VALUE_ERROR, "Invalid decimal string for BigInt"));
444        }
445        // Accumulate 19-digit chunks: magnitude = magnitude * 10^len + chunk.
446        let mut magnitude = Vec::new();
447        for chunk in digits.as_bytes().chunks(19) {
448            let value = chunk
449                .iter()
450                .fold(0u64, |acc, &digit| acc * 10 + u64::from(digit - b'0'));
451            int_ops::mul_add_small(&mut magnitude, 10u64.pow(chunk.len() as u32), value);
452        }
453        let mut words: Vec<i64> = magnitude.into_iter().map(|word| word as i64).collect();
454        words.push(0);
455        if negative {
456            int_ops::negate_in_place(&mut words);
457        }
458        Ok(Self::from_words(&words))
459    }
460}
461
462impl Clone for BigInt {
463    #[inline]
464    fn clone(&self) -> Self {
465        if self.data.type_index == TypeIndex::kTVMFFIBigInt as i32 {
466            unsafe { unsafe_::inc_ref(self.data.data_union.v_obj) }
467        }
468        Self { data: self.data }
469    }
470}
471
472impl Drop for BigInt {
473    #[inline]
474    fn drop(&mut self) {
475        if self.data.type_index == TypeIndex::kTVMFFIBigInt as i32 {
476            unsafe { unsafe_::dec_ref(self.data.data_union.v_obj) }
477        }
478    }
479}
480
481impl PartialEq for BigInt {
482    /// Canonical words make equal values word-for-word identical.
483    #[inline]
484    fn eq(&self, other: &Self) -> bool {
485        self.words() == other.words()
486    }
487}
488
489impl Eq for BigInt {}
490
491impl PartialOrd for BigInt {
492    #[inline]
493    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
494        Some(self.cmp(other))
495    }
496}
497
498impl Ord for BigInt {
499    fn cmp(&self, other: &Self) -> Ordering {
500        let (a, b) = (self.words(), other.words());
501        let (negative_a, negative_b) = (int_ops::is_negative(a), int_ops::is_negative(b));
502        if negative_a != negative_b {
503            return if negative_a {
504                Ordering::Less
505            } else {
506                Ordering::Greater
507            };
508        }
509        // With equal signs, sign-extended words compare as unsigned from the top.
510        let extension = int_ops::extension(a);
511        (0..a.len().max(b.len()))
512            .rev()
513            .map(|i| int_ops::word_at(a, i, extension).cmp(&int_ops::word_at(b, i, extension)))
514            .find(|ordering| ordering.is_ne())
515            .unwrap_or(Ordering::Equal)
516    }
517}
518
519impl Hash for BigInt {
520    #[inline]
521    fn hash<H: Hasher>(&self, state: &mut H) {
522        self.words().hash(state);
523    }
524}
525
526impl Display for BigInt {
527    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
528        if let Some(value) = self.to_i64() {
529            return Display::fmt(&value, f);
530        }
531        let words = self.words();
532        let negative = words[words.len() - 1] < 0;
533        let mut magnitude = words.to_vec();
534        if negative {
535            int_ops::negate_in_place(&mut magnitude);
536        }
537        // Peel base-10^19 chunks, least significant first, by long division.
538        const CHUNK: u128 = 10_000_000_000_000_000_000;
539        let mut chunks = Vec::new();
540        while let Some(top) = magnitude.iter().rposition(|&word| word != 0) {
541            magnitude.truncate(top + 1);
542            let mut remainder = 0u128;
543            for word in magnitude.iter_mut().rev() {
544                let current = (remainder << 64) | u128::from(*word as u64);
545                *word = (current / CHUNK) as i64;
546                remainder = current % CHUNK;
547            }
548            chunks.push(remainder as u64);
549        }
550        let mut digits = String::new();
551        let mut chunks = chunks.iter().rev();
552        // A heap value is never zero, so the leading chunk always exists.
553        write!(digits, "{}", chunks.next().unwrap_or(&0))?;
554        for chunk in chunks {
555            write!(digits, "{chunk:019}")?;
556        }
557        f.pad_integral(!negative, "", &digits)
558    }
559}
560
561impl Debug for BigInt {
562    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
563        f.debug_struct("ffi.BigInt")
564            .field("data", &format_args!("{self}"))
565            .finish()
566    }
567}
568
569// ---- Arithmetic: an inline fast path, then the word fallbacks.
570#[inline]
571fn add_impl(a: &BigInt, b: &BigInt) -> BigInt {
572    if let (Some(x), Some(y)) = (a.to_i64(), b.to_i64())
573        && let Some(result) = x.checked_add(y)
574    {
575        return BigInt::from_i64(result);
576    }
577    int_ops::add(a.words(), b.words())
578}
579
580#[inline]
581fn sub_impl(a: &BigInt, b: &BigInt) -> BigInt {
582    if let (Some(x), Some(y)) = (a.to_i64(), b.to_i64())
583        && let Some(result) = x.checked_sub(y)
584    {
585        return BigInt::from_i64(result);
586    }
587    int_ops::sub(a.words(), b.words())
588}
589
590#[inline]
591fn mul_impl(a: &BigInt, b: &BigInt) -> BigInt {
592    if let (Some(x), Some(y)) = (a.to_i64(), b.to_i64())
593        && let Some(result) = x.checked_mul(y)
594    {
595        return BigInt::from_i64(result);
596    }
597    int_ops::mul(a.words(), b.words())
598}
599
600#[inline]
601fn div_impl(a: &BigInt, b: &BigInt) -> Result<BigInt> {
602    if let (Some(x), Some(y)) = (a.to_i64(), b.to_i64())
603        && let Some(result) = int_ops::trunc_div_i64(x, y)?
604    {
605        return Ok(BigInt::from_i64(result));
606    }
607    int_ops::trunc_div(a.words(), b.words())
608}
609
610#[inline]
611fn rem_impl(a: &BigInt, b: &BigInt) -> Result<BigInt> {
612    if let (Some(x), Some(y)) = (a.to_i64(), b.to_i64())
613        && let Some(result) = int_ops::trunc_mod_i64(x, y)?
614    {
615        return Ok(BigInt::from_i64(result));
616    }
617    int_ops::trunc_mod(a.words(), b.words())
618}
619
620#[inline]
621fn floor_div_impl(a: &BigInt, b: &BigInt) -> Result<BigInt> {
622    if let (Some(x), Some(y)) = (a.to_i64(), b.to_i64())
623        && let Some(result) = int_ops::floor_div_i64(x, y)?
624    {
625        return Ok(BigInt::from_i64(result));
626    }
627    int_ops::floor_div(a.words(), b.words())
628}
629
630#[inline]
631fn floor_mod_impl(a: &BigInt, b: &BigInt) -> Result<BigInt> {
632    if let (Some(x), Some(y)) = (a.to_i64(), b.to_i64())
633        && let Some(result) = int_ops::floor_mod_i64(x, y)?
634    {
635        return Ok(BigInt::from_i64(result));
636    }
637    int_ops::floor_mod(a.words(), b.words())
638}
639
640#[inline]
641fn shl_impl(a: &BigInt, b: &BigInt) -> Result<BigInt> {
642    if let (Some(x), Some(y)) = (a.to_i64(), b.to_i64())
643        && let Some(result) = int_ops::shl_i64(x, y)?
644    {
645        return Ok(BigInt::from_i64(result));
646    }
647    int_ops::shl(a.words(), b.words())
648}
649
650#[inline]
651fn shr_impl(a: &BigInt, b: &BigInt) -> Result<BigInt> {
652    if let (Some(x), Some(y)) = (a.to_i64(), b.to_i64()) {
653        return Ok(BigInt::from_i64(int_ops::shr_i64(x, y)?));
654    }
655    int_ops::shr(a.words(), b.words())
656}
657
658#[inline]
659fn and_impl(a: &BigInt, b: &BigInt) -> BigInt {
660    if let (Some(x), Some(y)) = (a.to_i64(), b.to_i64()) {
661        return BigInt::from_i64(x & y);
662    }
663    int_ops::and(a.words(), b.words())
664}
665
666#[inline]
667fn or_impl(a: &BigInt, b: &BigInt) -> BigInt {
668    if let (Some(x), Some(y)) = (a.to_i64(), b.to_i64()) {
669        return BigInt::from_i64(x | y);
670    }
671    int_ops::or(a.words(), b.words())
672}
673
674#[inline]
675fn xor_impl(a: &BigInt, b: &BigInt) -> BigInt {
676    if let (Some(x), Some(y)) = (a.to_i64(), b.to_i64()) {
677        return BigInt::from_i64(x ^ y);
678    }
679    int_ops::xor(a.words(), b.words())
680}
681
682#[inline]
683fn neg_impl(a: &BigInt) -> BigInt {
684    if let Some(negated) = a.to_i64().and_then(i64::checked_neg) {
685        return BigInt::from_i64(negated);
686    }
687    int_ops::negate(a.words())
688}
689
690#[inline]
691fn not_impl(a: &BigInt) -> BigInt {
692    if let Some(x) = a.to_i64() {
693        return BigInt::from_i64(!x);
694    }
695    int_ops::not(a.words())
696}
697
698/// The operator form of a fallible operation panics like the primitive one would.
699macro_rules! define_op_or_panic {
700    ($($name:ident => $imp:ident),* $(,)?) => {
701        $(
702            #[inline]
703            fn $name(a: &BigInt, b: &BigInt) -> BigInt {
704                $imp(a, b).unwrap_or_else(|error| panic!("{}", error.message()))
705            }
706        )*
707    };
708}
709
710define_op_or_panic!(
711    div_or_panic => div_impl,
712    rem_or_panic => rem_impl,
713    shl_or_panic => shl_impl,
714    shr_or_panic => shr_impl,
715);
716
717/// Forward an operator to its implementation for owned and borrowed operands,
718/// with `i64` accepted on either side.
719macro_rules! forward_binop {
720    ($Trait:ident::$method:ident, $Assign:ident::$assign:ident, $imp:ident) => {
721        impl $Trait<&BigInt> for &BigInt {
722            type Output = BigInt;
723            #[inline]
724            fn $method(self, rhs: &BigInt) -> BigInt {
725                $imp(self, rhs)
726            }
727        }
728        impl $Trait<BigInt> for &BigInt {
729            type Output = BigInt;
730            #[inline]
731            fn $method(self, rhs: BigInt) -> BigInt {
732                $imp(self, &rhs)
733            }
734        }
735        impl $Trait<&BigInt> for BigInt {
736            type Output = BigInt;
737            #[inline]
738            fn $method(self, rhs: &BigInt) -> BigInt {
739                $imp(&self, rhs)
740            }
741        }
742        impl $Trait<BigInt> for BigInt {
743            type Output = BigInt;
744            #[inline]
745            fn $method(self, rhs: BigInt) -> BigInt {
746                $imp(&self, &rhs)
747            }
748        }
749        impl $Trait<i64> for &BigInt {
750            type Output = BigInt;
751            #[inline]
752            fn $method(self, rhs: i64) -> BigInt {
753                $imp(self, &BigInt::from_i64(rhs))
754            }
755        }
756        impl $Trait<i64> for BigInt {
757            type Output = BigInt;
758            #[inline]
759            fn $method(self, rhs: i64) -> BigInt {
760                $imp(&self, &BigInt::from_i64(rhs))
761            }
762        }
763        impl $Trait<&BigInt> for i64 {
764            type Output = BigInt;
765            #[inline]
766            fn $method(self, rhs: &BigInt) -> BigInt {
767                $imp(&BigInt::from_i64(self), rhs)
768            }
769        }
770        impl $Trait<BigInt> for i64 {
771            type Output = BigInt;
772            #[inline]
773            fn $method(self, rhs: BigInt) -> BigInt {
774                $imp(&BigInt::from_i64(self), &rhs)
775            }
776        }
777        impl $Assign<&BigInt> for BigInt {
778            #[inline]
779            fn $assign(&mut self, rhs: &BigInt) {
780                *self = $imp(self, rhs);
781            }
782        }
783        impl $Assign<BigInt> for BigInt {
784            #[inline]
785            fn $assign(&mut self, rhs: BigInt) {
786                *self = $imp(self, &rhs);
787            }
788        }
789        impl $Assign<i64> for BigInt {
790            #[inline]
791            fn $assign(&mut self, rhs: i64) {
792                *self = $imp(self, &BigInt::from_i64(rhs));
793            }
794        }
795    };
796}
797
798forward_binop!(Add::add, AddAssign::add_assign, add_impl);
799forward_binop!(Sub::sub, SubAssign::sub_assign, sub_impl);
800forward_binop!(Mul::mul, MulAssign::mul_assign, mul_impl);
801forward_binop!(Div::div, DivAssign::div_assign, div_or_panic);
802forward_binop!(Rem::rem, RemAssign::rem_assign, rem_or_panic);
803forward_binop!(BitAnd::bitand, BitAndAssign::bitand_assign, and_impl);
804forward_binop!(BitOr::bitor, BitOrAssign::bitor_assign, or_impl);
805forward_binop!(BitXor::bitxor, BitXorAssign::bitxor_assign, xor_impl);
806forward_binop!(Shl::shl, ShlAssign::shl_assign, shl_or_panic);
807forward_binop!(Shr::shr, ShrAssign::shr_assign, shr_or_panic);
808
809impl Neg for &BigInt {
810    type Output = BigInt;
811    #[inline]
812    fn neg(self) -> BigInt {
813        neg_impl(self)
814    }
815}
816
817impl Neg for BigInt {
818    type Output = BigInt;
819    #[inline]
820    fn neg(self) -> BigInt {
821        neg_impl(&self)
822    }
823}
824
825impl Not for &BigInt {
826    type Output = BigInt;
827    #[inline]
828    fn not(self) -> BigInt {
829        not_impl(self)
830    }
831}
832
833impl Not for BigInt {
834    type Output = BigInt;
835    #[inline]
836    fn not(self) -> BigInt {
837        not_impl(&self)
838    }
839}
840
841// ---- AnyCompatible.
842unsafe impl AnyCompatible for BigInt {
843    fn type_str() -> std::string::String {
844        "BigInt".to_string()
845    }
846
847    // A big integer is an inline integer or a big integer object, never None.
848    #[inline]
849    unsafe fn is_undefined(field: *const Self) -> bool {
850        unsafe { (*std::ptr::addr_of!((*field).data.type_index)) == TypeIndex::kTVMFFINone as i32 }
851    }
852
853    fn type_schema() -> std::string::String {
854        crate::type_traits::type_schema(<BigIntObj as crate::ObjectCore>::TYPE_KEY, &[])
855    }
856
857    unsafe fn copy_to_any_view(this: &Self, data: &mut TVMFFIAny) {
858        *data = this.data;
859    }
860
861    unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
862        *data = src.data;
863        std::mem::forget(src);
864    }
865
866    unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
867        data.type_index == TypeIndex::kTVMFFIInt as i32
868            || data.type_index == TypeIndex::kTVMFFIBigInt as i32
869    }
870
871    unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
872        if data.type_index == TypeIndex::kTVMFFIBigInt as i32 {
873            unsafe { unsafe_::inc_ref(data.data_union.v_obj) }
874        }
875        Self { data: *data }
876    }
877
878    unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
879        Self { data: *data }
880    }
881
882    unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> std::result::Result<Self, ()> {
883        if unsafe { Self::check_any_strict(data) } {
884            Ok(unsafe { Self::copy_from_any_view_after_check(data) })
885        } else if data.type_index == TypeIndex::kTVMFFIBool as i32 {
886            Ok(unsafe { Self::from_i64(data.data_union.v_int64) })
887        } else {
888            Err(())
889        }
890    }
891}