arrow_buffer/bigint/
mod.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use crate::arith::derive_arith;
19use crate::bigint::div::div_rem;
20use num::cast::AsPrimitive;
21use num::{BigInt, FromPrimitive, ToPrimitive};
22use std::cmp::Ordering;
23use std::num::ParseIntError;
24use std::ops::{BitAnd, BitOr, BitXor, Neg, Shl, Shr};
25use std::str::FromStr;
26
27mod div;
28
29/// An opaque error similar to [`std::num::ParseIntError`]
30#[derive(Debug)]
31pub struct ParseI256Error {}
32
33impl From<ParseIntError> for ParseI256Error {
34    fn from(_: ParseIntError) -> Self {
35        Self {}
36    }
37}
38
39impl std::fmt::Display for ParseI256Error {
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41        write!(f, "Failed to parse as i256")
42    }
43}
44impl std::error::Error for ParseI256Error {}
45
46/// Error returned by i256::DivRem
47enum DivRemError {
48    /// Division by zero
49    DivideByZero,
50    /// Division overflow
51    DivideOverflow,
52}
53
54/// A signed 256-bit integer
55#[allow(non_camel_case_types)]
56#[derive(Copy, Clone, Default, Eq, PartialEq, Hash)]
57#[repr(C)]
58pub struct i256 {
59    low: u128,
60    high: i128,
61}
62
63impl std::fmt::Debug for i256 {
64    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65        write!(f, "{self}")
66    }
67}
68
69impl std::fmt::Display for i256 {
70    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
71        write!(f, "{}", BigInt::from_signed_bytes_le(&self.to_le_bytes()))
72    }
73}
74
75impl FromStr for i256 {
76    type Err = ParseI256Error;
77
78    fn from_str(s: &str) -> Result<Self, Self::Err> {
79        // i128 can store up to 38 decimal digits
80        if s.len() <= 38 {
81            return Ok(Self::from_i128(i128::from_str(s)?));
82        }
83
84        let (negative, s) = match s.as_bytes()[0] {
85            b'-' => (true, &s[1..]),
86            b'+' => (false, &s[1..]),
87            _ => (false, s),
88        };
89
90        // Trim leading 0s
91        let s = s.trim_start_matches('0');
92        if s.is_empty() {
93            return Ok(i256::ZERO);
94        }
95
96        if !s.as_bytes()[0].is_ascii_digit() {
97            // Ensures no duplicate sign
98            return Err(ParseI256Error {});
99        }
100
101        parse_impl(s, negative)
102    }
103}
104
105impl From<i8> for i256 {
106    fn from(value: i8) -> Self {
107        Self::from_i128(value.into())
108    }
109}
110
111impl From<i16> for i256 {
112    fn from(value: i16) -> Self {
113        Self::from_i128(value.into())
114    }
115}
116
117impl From<i32> for i256 {
118    fn from(value: i32) -> Self {
119        Self::from_i128(value.into())
120    }
121}
122
123impl From<i64> for i256 {
124    fn from(value: i64) -> Self {
125        Self::from_i128(value.into())
126    }
127}
128
129/// Parse `s` with any sign and leading 0s removed
130fn parse_impl(s: &str, negative: bool) -> Result<i256, ParseI256Error> {
131    if s.len() <= 38 {
132        let low = i128::from_str(s)?;
133        return Ok(match negative {
134            true => i256::from_parts(low.neg() as _, -1),
135            false => i256::from_parts(low as _, 0),
136        });
137    }
138
139    let split = s.len() - 38;
140    if !s.as_bytes()[split].is_ascii_digit() {
141        // Ensures not splitting codepoint and no sign
142        return Err(ParseI256Error {});
143    }
144    let (hs, ls) = s.split_at(split);
145
146    let mut low = i128::from_str(ls)?;
147    let high = parse_impl(hs, negative)?;
148
149    if negative {
150        low = -low;
151    }
152
153    let low = i256::from_i128(low);
154
155    high.checked_mul(i256::from_i128(10_i128.pow(38)))
156        .and_then(|high| high.checked_add(low))
157        .ok_or(ParseI256Error {})
158}
159
160impl PartialOrd for i256 {
161    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
162        Some(self.cmp(other))
163    }
164}
165
166impl Ord for i256 {
167    fn cmp(&self, other: &Self) -> Ordering {
168        // This is 25x faster than using a variable length encoding such
169        // as BigInt as it avoids allocation and branching
170        self.high.cmp(&other.high).then(self.low.cmp(&other.low))
171    }
172}
173
174impl i256 {
175    /// The additive identity for this integer type, i.e. `0`.
176    pub const ZERO: Self = i256 { low: 0, high: 0 };
177
178    /// The multiplicative identity for this integer type, i.e. `1`.
179    pub const ONE: Self = i256 { low: 1, high: 0 };
180
181    /// The multiplicative inverse for this integer type, i.e. `-1`.
182    pub const MINUS_ONE: Self = i256 {
183        low: u128::MAX,
184        high: -1,
185    };
186
187    /// The maximum value that can be represented by this integer type
188    pub const MAX: Self = i256 {
189        low: u128::MAX,
190        high: i128::MAX,
191    };
192
193    /// The minimum value that can be represented by this integer type
194    pub const MIN: Self = i256 {
195        low: u128::MIN,
196        high: i128::MIN,
197    };
198
199    /// Create an integer value from its representation as a byte array in little-endian.
200    #[inline]
201    pub const fn from_le_bytes(b: [u8; 32]) -> Self {
202        let (low, high) = split_array(b);
203        Self {
204            high: i128::from_le_bytes(high),
205            low: u128::from_le_bytes(low),
206        }
207    }
208
209    /// Create an integer value from its representation as a byte array in big-endian.
210    #[inline]
211    pub const fn from_be_bytes(b: [u8; 32]) -> Self {
212        let (high, low) = split_array(b);
213        Self {
214            high: i128::from_be_bytes(high),
215            low: u128::from_be_bytes(low),
216        }
217    }
218
219    /// Create an `i256` value from a 128-bit value.
220    pub const fn from_i128(v: i128) -> Self {
221        Self::from_parts(v as u128, v >> 127)
222    }
223
224    /// Create an integer value from its representation as string.
225    #[inline]
226    pub fn from_string(value_str: &str) -> Option<Self> {
227        value_str.parse().ok()
228    }
229
230    /// Create an optional i256 from the provided `f64`. Returning `None`
231    /// if overflow occurred
232    pub fn from_f64(v: f64) -> Option<Self> {
233        BigInt::from_f64(v).and_then(|i| {
234            let (integer, overflow) = i256::from_bigint_with_overflow(i);
235            if overflow {
236                None
237            } else {
238                Some(integer)
239            }
240        })
241    }
242
243    /// Create an i256 from the provided low u128 and high i128
244    #[inline]
245    pub const fn from_parts(low: u128, high: i128) -> Self {
246        Self { low, high }
247    }
248
249    /// Returns this `i256` as a low u128 and high i128
250    pub const fn to_parts(self) -> (u128, i128) {
251        (self.low, self.high)
252    }
253
254    /// Converts this `i256` into an `i128` returning `None` if this would result
255    /// in truncation/overflow
256    pub fn to_i128(self) -> Option<i128> {
257        let as_i128 = self.low as i128;
258
259        let high_negative = self.high < 0;
260        let low_negative = as_i128 < 0;
261        let high_valid = self.high == -1 || self.high == 0;
262
263        (high_negative == low_negative && high_valid).then_some(self.low as i128)
264    }
265
266    /// Wraps this `i256` into an `i128`
267    pub fn as_i128(self) -> i128 {
268        self.low as i128
269    }
270
271    /// Return the memory representation of this integer as a byte array in little-endian byte order.
272    #[inline]
273    pub const fn to_le_bytes(self) -> [u8; 32] {
274        let low = self.low.to_le_bytes();
275        let high = self.high.to_le_bytes();
276        let mut t = [0; 32];
277        let mut i = 0;
278        while i != 16 {
279            t[i] = low[i];
280            t[i + 16] = high[i];
281            i += 1;
282        }
283        t
284    }
285
286    /// Return the memory representation of this integer as a byte array in big-endian byte order.
287    #[inline]
288    pub const fn to_be_bytes(self) -> [u8; 32] {
289        let low = self.low.to_be_bytes();
290        let high = self.high.to_be_bytes();
291        let mut t = [0; 32];
292        let mut i = 0;
293        while i != 16 {
294            t[i] = high[i];
295            t[i + 16] = low[i];
296            i += 1;
297        }
298        t
299    }
300
301    /// Create an i256 from the provided [`BigInt`] returning a bool indicating
302    /// if overflow occurred
303    fn from_bigint_with_overflow(v: BigInt) -> (Self, bool) {
304        let v_bytes = v.to_signed_bytes_le();
305        match v_bytes.len().cmp(&32) {
306            Ordering::Less => {
307                let mut bytes = if num::Signed::is_negative(&v) {
308                    [255_u8; 32]
309                } else {
310                    [0; 32]
311                };
312                bytes[0..v_bytes.len()].copy_from_slice(&v_bytes[..v_bytes.len()]);
313                (Self::from_le_bytes(bytes), false)
314            }
315            Ordering::Equal => (Self::from_le_bytes(v_bytes.try_into().unwrap()), false),
316            Ordering::Greater => (Self::from_le_bytes(v_bytes[..32].try_into().unwrap()), true),
317        }
318    }
319
320    /// Computes the absolute value of this i256
321    #[inline]
322    pub fn wrapping_abs(self) -> Self {
323        // -1 if negative, otherwise 0
324        let sa = self.high >> 127;
325        let sa = Self::from_parts(sa as u128, sa);
326
327        // Inverted if negative
328        Self::from_parts(self.low ^ sa.low, self.high ^ sa.high).wrapping_sub(sa)
329    }
330
331    /// Computes the absolute value of this i256 returning `None` if `Self == Self::MIN`
332    #[inline]
333    pub fn checked_abs(self) -> Option<Self> {
334        (self != Self::MIN).then(|| self.wrapping_abs())
335    }
336
337    /// Negates this i256
338    #[inline]
339    pub fn wrapping_neg(self) -> Self {
340        Self::from_parts(!self.low, !self.high).wrapping_add(i256::ONE)
341    }
342
343    /// Negates this i256 returning `None` if `Self == Self::MIN`
344    #[inline]
345    pub fn checked_neg(self) -> Option<Self> {
346        (self != Self::MIN).then(|| self.wrapping_neg())
347    }
348
349    /// Performs wrapping addition
350    #[inline]
351    pub fn wrapping_add(self, other: Self) -> Self {
352        let (low, carry) = self.low.overflowing_add(other.low);
353        let high = self.high.wrapping_add(other.high).wrapping_add(carry as _);
354        Self { low, high }
355    }
356
357    /// Performs checked addition
358    #[inline]
359    pub fn checked_add(self, other: Self) -> Option<Self> {
360        let r = self.wrapping_add(other);
361        ((other.is_negative() && r < self) || (!other.is_negative() && r >= self)).then_some(r)
362    }
363
364    /// Performs wrapping subtraction
365    #[inline]
366    pub fn wrapping_sub(self, other: Self) -> Self {
367        let (low, carry) = self.low.overflowing_sub(other.low);
368        let high = self.high.wrapping_sub(other.high).wrapping_sub(carry as _);
369        Self { low, high }
370    }
371
372    /// Performs checked subtraction
373    #[inline]
374    pub fn checked_sub(self, other: Self) -> Option<Self> {
375        let r = self.wrapping_sub(other);
376        ((other.is_negative() && r > self) || (!other.is_negative() && r <= self)).then_some(r)
377    }
378
379    /// Performs wrapping multiplication
380    #[inline]
381    pub fn wrapping_mul(self, other: Self) -> Self {
382        let (low, high) = mulx(self.low, other.low);
383
384        // Compute the high multiples, only impacting the high 128-bits
385        let hl = self.high.wrapping_mul(other.low as i128);
386        let lh = (self.low as i128).wrapping_mul(other.high);
387
388        Self {
389            low,
390            high: (high as i128).wrapping_add(hl).wrapping_add(lh),
391        }
392    }
393
394    /// Performs checked multiplication
395    #[inline]
396    pub fn checked_mul(self, other: Self) -> Option<Self> {
397        if self == i256::ZERO || other == i256::ZERO {
398            return Some(i256::ZERO);
399        }
400
401        // Shift sign bit down to construct mask of all set bits if negative
402        let l_sa = self.high >> 127;
403        let r_sa = other.high >> 127;
404        let out_sa = (l_sa ^ r_sa) as u128;
405
406        // Compute absolute values
407        let l_abs = self.wrapping_abs();
408        let r_abs = other.wrapping_abs();
409
410        // Overflow if both high parts are non-zero
411        if l_abs.high != 0 && r_abs.high != 0 {
412            return None;
413        }
414
415        // Perform checked multiplication on absolute values
416        let (low, high) = mulx(l_abs.low, r_abs.low);
417
418        // Compute the high multiples, only impacting the high 128-bits
419        let hl = (l_abs.high as u128).checked_mul(r_abs.low)?;
420        let lh = l_abs.low.checked_mul(r_abs.high as u128)?;
421
422        let high = high.checked_add(hl)?.checked_add(lh)?;
423
424        // Reverse absolute value, if necessary
425        let (low, c) = (low ^ out_sa).overflowing_sub(out_sa);
426        let high = (high ^ out_sa).wrapping_sub(out_sa).wrapping_sub(c as u128) as i128;
427
428        // Check for overflow in final conversion
429        (high.is_negative() == (self.is_negative() ^ other.is_negative()))
430            .then_some(Self { low, high })
431    }
432
433    /// Division operation, returns (quotient, remainder).
434    /// This basically implements [Long division]: `<https://en.wikipedia.org/wiki/Division_algorithm>`
435    #[inline]
436    fn div_rem(self, other: Self) -> Result<(Self, Self), DivRemError> {
437        if other == Self::ZERO {
438            return Err(DivRemError::DivideByZero);
439        }
440        if other == Self::MINUS_ONE && self == Self::MIN {
441            return Err(DivRemError::DivideOverflow);
442        }
443
444        let a = self.wrapping_abs();
445        let b = other.wrapping_abs();
446
447        let (div, rem) = div_rem(&a.as_digits(), &b.as_digits());
448        let div = Self::from_digits(div);
449        let rem = Self::from_digits(rem);
450
451        Ok((
452            if self.is_negative() == other.is_negative() {
453                div
454            } else {
455                div.wrapping_neg()
456            },
457            if self.is_negative() {
458                rem.wrapping_neg()
459            } else {
460                rem
461            },
462        ))
463    }
464
465    /// Interpret this [`i256`] as 4 `u64` digits, least significant first
466    fn as_digits(self) -> [u64; 4] {
467        [
468            self.low as u64,
469            (self.low >> 64) as u64,
470            self.high as u64,
471            (self.high as u128 >> 64) as u64,
472        ]
473    }
474
475    /// Interpret 4 `u64` digits, least significant first, as a [`i256`]
476    fn from_digits(digits: [u64; 4]) -> Self {
477        Self::from_parts(
478            digits[0] as u128 | ((digits[1] as u128) << 64),
479            digits[2] as i128 | ((digits[3] as i128) << 64),
480        )
481    }
482
483    /// Performs wrapping division
484    #[inline]
485    pub fn wrapping_div(self, other: Self) -> Self {
486        match self.div_rem(other) {
487            Ok((v, _)) => v,
488            Err(DivRemError::DivideByZero) => panic!("attempt to divide by zero"),
489            Err(_) => Self::MIN,
490        }
491    }
492
493    /// Performs checked division
494    #[inline]
495    pub fn checked_div(self, other: Self) -> Option<Self> {
496        self.div_rem(other).map(|(v, _)| v).ok()
497    }
498
499    /// Performs wrapping remainder
500    #[inline]
501    pub fn wrapping_rem(self, other: Self) -> Self {
502        match self.div_rem(other) {
503            Ok((_, v)) => v,
504            Err(DivRemError::DivideByZero) => panic!("attempt to divide by zero"),
505            Err(_) => Self::ZERO,
506        }
507    }
508
509    /// Performs checked remainder
510    #[inline]
511    pub fn checked_rem(self, other: Self) -> Option<Self> {
512        self.div_rem(other).map(|(_, v)| v).ok()
513    }
514
515    /// Performs checked exponentiation
516    #[inline]
517    pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
518        if exp == 0 {
519            return Some(i256::from_i128(1));
520        }
521
522        let mut base = self;
523        let mut acc: Self = i256::from_i128(1);
524
525        while exp > 1 {
526            if (exp & 1) == 1 {
527                acc = acc.checked_mul(base)?;
528            }
529            exp /= 2;
530            base = base.checked_mul(base)?;
531        }
532        // since exp!=0, finally the exp must be 1.
533        // Deal with the final bit of the exponent separately, since
534        // squaring the base afterwards is not necessary and may cause a
535        // needless overflow.
536        acc.checked_mul(base)
537    }
538
539    /// Performs wrapping exponentiation
540    #[inline]
541    pub fn wrapping_pow(self, mut exp: u32) -> Self {
542        if exp == 0 {
543            return i256::from_i128(1);
544        }
545
546        let mut base = self;
547        let mut acc: Self = i256::from_i128(1);
548
549        while exp > 1 {
550            if (exp & 1) == 1 {
551                acc = acc.wrapping_mul(base);
552            }
553            exp /= 2;
554            base = base.wrapping_mul(base);
555        }
556
557        // since exp!=0, finally the exp must be 1.
558        // Deal with the final bit of the exponent separately, since
559        // squaring the base afterwards is not necessary and may cause a
560        // needless overflow.
561        acc.wrapping_mul(base)
562    }
563
564    /// Returns a number [`i256`] representing sign of this [`i256`].
565    ///
566    /// 0 if the number is zero
567    /// 1 if the number is positive
568    /// -1 if the number is negative
569    pub const fn signum(self) -> Self {
570        if self.is_positive() {
571            i256::ONE
572        } else if self.is_negative() {
573            i256::MINUS_ONE
574        } else {
575            i256::ZERO
576        }
577    }
578
579    /// Returns `true` if this [`i256`] is negative
580    #[inline]
581    pub const fn is_negative(self) -> bool {
582        self.high.is_negative()
583    }
584
585    /// Returns `true` if this [`i256`] is positive
586    pub const fn is_positive(self) -> bool {
587        self.high.is_positive() || self.high == 0 && self.low != 0
588    }
589
590    fn leading_zeros(&self) -> u32 {
591        match self.high {
592            0 => u128::BITS + self.low.leading_zeros(),
593            _ => self.high.leading_zeros(),
594        }
595    }
596
597    fn redundant_leading_sign_bits_i256(n: i256) -> u8 {
598        let mask = n >> 255; // all ones or all zeros
599        ((n ^ mask).leading_zeros() - 1) as u8 // we only need one sign bit
600    }
601
602    fn i256_to_f64(input: i256) -> f64 {
603        let k = i256::redundant_leading_sign_bits_i256(input);
604        let n = input << k; // left-justify (no redundant sign bits)
605        let n = (n.high >> 64) as i64; // throw away the lower 192 bits
606        (n as f64) * f64::powi(2.0, 192 - (k as i32)) // convert to f64 and scale it, as we left-shift k bit previous, so we need to scale it by 2^(192-k)
607    }
608}
609
610/// Temporary workaround due to lack of stable const array slicing
611/// See <https://github.com/rust-lang/rust/issues/90091>
612const fn split_array<const N: usize, const M: usize>(vals: [u8; N]) -> ([u8; M], [u8; M]) {
613    let mut a = [0; M];
614    let mut b = [0; M];
615    let mut i = 0;
616    while i != M {
617        a[i] = vals[i];
618        b[i] = vals[i + M];
619        i += 1;
620    }
621    (a, b)
622}
623
624/// Performs an unsigned multiplication of `a * b` returning a tuple of
625/// `(low, high)` where `low` contains the lower 128-bits of the result
626/// and `high` the higher 128-bits
627///
628/// This mirrors the x86 mulx instruction but for 128-bit types
629#[inline]
630fn mulx(a: u128, b: u128) -> (u128, u128) {
631    let split = |a: u128| (a & (u64::MAX as u128), a >> 64);
632
633    const MASK: u128 = u64::MAX as _;
634
635    let (a_low, a_high) = split(a);
636    let (b_low, b_high) = split(b);
637
638    // Carry stores the upper 64-bits of low and lower 64-bits of high
639    let (mut low, mut carry) = split(a_low * b_low);
640    carry += a_high * b_low;
641
642    // Update low and high with corresponding parts of carry
643    low += carry << 64;
644    let mut high = carry >> 64;
645
646    // Update carry with overflow from low
647    carry = low >> 64;
648    low &= MASK;
649
650    // Perform multiply including overflow from low
651    carry += b_high * a_low;
652
653    // Update low and high with values from carry
654    low += carry << 64;
655    high += carry >> 64;
656
657    // Perform 4th multiplication
658    high += a_high * b_high;
659
660    (low, high)
661}
662
663derive_arith!(
664    i256,
665    Add,
666    AddAssign,
667    add,
668    add_assign,
669    wrapping_add,
670    checked_add
671);
672derive_arith!(
673    i256,
674    Sub,
675    SubAssign,
676    sub,
677    sub_assign,
678    wrapping_sub,
679    checked_sub
680);
681derive_arith!(
682    i256,
683    Mul,
684    MulAssign,
685    mul,
686    mul_assign,
687    wrapping_mul,
688    checked_mul
689);
690derive_arith!(
691    i256,
692    Div,
693    DivAssign,
694    div,
695    div_assign,
696    wrapping_div,
697    checked_div
698);
699derive_arith!(
700    i256,
701    Rem,
702    RemAssign,
703    rem,
704    rem_assign,
705    wrapping_rem,
706    checked_rem
707);
708
709impl Neg for i256 {
710    type Output = i256;
711
712    #[cfg(debug_assertions)]
713    fn neg(self) -> Self::Output {
714        self.checked_neg().expect("i256 overflow")
715    }
716
717    #[cfg(not(debug_assertions))]
718    fn neg(self) -> Self::Output {
719        self.wrapping_neg()
720    }
721}
722
723impl BitAnd for i256 {
724    type Output = i256;
725
726    #[inline]
727    fn bitand(self, rhs: Self) -> Self::Output {
728        Self {
729            low: self.low & rhs.low,
730            high: self.high & rhs.high,
731        }
732    }
733}
734
735impl BitOr for i256 {
736    type Output = i256;
737
738    #[inline]
739    fn bitor(self, rhs: Self) -> Self::Output {
740        Self {
741            low: self.low | rhs.low,
742            high: self.high | rhs.high,
743        }
744    }
745}
746
747impl BitXor for i256 {
748    type Output = i256;
749
750    #[inline]
751    fn bitxor(self, rhs: Self) -> Self::Output {
752        Self {
753            low: self.low ^ rhs.low,
754            high: self.high ^ rhs.high,
755        }
756    }
757}
758
759impl Shl<u8> for i256 {
760    type Output = i256;
761
762    #[inline]
763    fn shl(self, rhs: u8) -> Self::Output {
764        if rhs == 0 {
765            self
766        } else if rhs < 128 {
767            Self {
768                high: (self.high << rhs) | (self.low >> (128 - rhs)) as i128,
769                low: self.low << rhs,
770            }
771        } else {
772            Self {
773                high: (self.low << (rhs - 128)) as i128,
774                low: 0,
775            }
776        }
777    }
778}
779
780impl Shr<u8> for i256 {
781    type Output = i256;
782
783    #[inline]
784    fn shr(self, rhs: u8) -> Self::Output {
785        if rhs == 0 {
786            self
787        } else if rhs < 128 {
788            Self {
789                high: self.high >> rhs,
790                low: (self.low >> rhs) | ((self.high as u128) << (128 - rhs)),
791            }
792        } else {
793            Self {
794                high: self.high >> 127,
795                low: (self.high >> (rhs - 128)) as u128,
796            }
797        }
798    }
799}
800
801macro_rules! define_as_primitive {
802    ($native_ty:ty) => {
803        impl AsPrimitive<i256> for $native_ty {
804            fn as_(self) -> i256 {
805                i256::from_i128(self as i128)
806            }
807        }
808    };
809}
810
811define_as_primitive!(i8);
812define_as_primitive!(i16);
813define_as_primitive!(i32);
814define_as_primitive!(i64);
815define_as_primitive!(u8);
816define_as_primitive!(u16);
817define_as_primitive!(u32);
818define_as_primitive!(u64);
819
820impl ToPrimitive for i256 {
821    fn to_i64(&self) -> Option<i64> {
822        let as_i128 = self.low as i128;
823
824        let high_negative = self.high < 0;
825        let low_negative = as_i128 < 0;
826        let high_valid = self.high == -1 || self.high == 0;
827
828        if high_negative == low_negative && high_valid {
829            let (low_bytes, high_bytes) = split_array(u128::to_le_bytes(self.low));
830            let high = i64::from_le_bytes(high_bytes);
831            let low = i64::from_le_bytes(low_bytes);
832
833            let high_negative = high < 0;
834            let low_negative = low < 0;
835            let high_valid = self.high == -1 || self.high == 0;
836
837            (high_negative == low_negative && high_valid).then_some(low)
838        } else {
839            None
840        }
841    }
842
843    fn to_f64(&self) -> Option<f64> {
844        match *self {
845            Self::MIN => Some(-2_f64.powi(255)),
846            Self::ZERO => Some(0f64),
847            Self::ONE => Some(1f64),
848            n => Some(Self::i256_to_f64(n)),
849        }
850    }
851
852    fn to_u64(&self) -> Option<u64> {
853        let as_i128 = self.low as i128;
854
855        let high_negative = self.high < 0;
856        let low_negative = as_i128 < 0;
857        let high_valid = self.high == -1 || self.high == 0;
858
859        if high_negative == low_negative && high_valid {
860            self.low.to_u64()
861        } else {
862            None
863        }
864    }
865}
866
867#[cfg(all(test, not(miri)))] // llvm.x86.subborrow.64 not supported by MIRI
868mod tests {
869    use super::*;
870    use num::Signed;
871    use rand::{rng, Rng};
872
873    #[test]
874    fn test_signed_cmp() {
875        let a = i256::from_parts(i128::MAX as u128, 12);
876        let b = i256::from_parts(i128::MIN as u128, 12);
877        assert!(a < b);
878
879        let a = i256::from_parts(i128::MAX as u128, 12);
880        let b = i256::from_parts(i128::MIN as u128, -12);
881        assert!(a > b);
882    }
883
884    #[test]
885    fn test_to_i128() {
886        let vals = [
887            BigInt::from_i128(-1).unwrap(),
888            BigInt::from_i128(i128::MAX).unwrap(),
889            BigInt::from_i128(i128::MIN).unwrap(),
890            BigInt::from_u128(u128::MIN).unwrap(),
891            BigInt::from_u128(u128::MAX).unwrap(),
892        ];
893
894        for v in vals {
895            let (t, overflow) = i256::from_bigint_with_overflow(v.clone());
896            assert!(!overflow);
897            assert_eq!(t.to_i128(), v.to_i128(), "{v} vs {t}");
898        }
899    }
900
901    /// Tests operations against the two provided [`i256`]
902    fn test_ops(il: i256, ir: i256) {
903        let bl = BigInt::from_signed_bytes_le(&il.to_le_bytes());
904        let br = BigInt::from_signed_bytes_le(&ir.to_le_bytes());
905
906        // Comparison
907        assert_eq!(il.cmp(&ir), bl.cmp(&br), "{bl} cmp {br}");
908
909        // Conversions
910        assert_eq!(i256::from_le_bytes(il.to_le_bytes()), il);
911        assert_eq!(i256::from_be_bytes(il.to_be_bytes()), il);
912        assert_eq!(i256::from_le_bytes(ir.to_le_bytes()), ir);
913        assert_eq!(i256::from_be_bytes(ir.to_be_bytes()), ir);
914
915        // To i128
916        assert_eq!(il.to_i128(), bl.to_i128(), "{bl}");
917        assert_eq!(ir.to_i128(), br.to_i128(), "{br}");
918
919        // Absolute value
920        let (abs, overflow) = i256::from_bigint_with_overflow(bl.abs());
921        assert_eq!(il.wrapping_abs(), abs);
922        assert_eq!(il.checked_abs().is_none(), overflow);
923
924        let (abs, overflow) = i256::from_bigint_with_overflow(br.abs());
925        assert_eq!(ir.wrapping_abs(), abs);
926        assert_eq!(ir.checked_abs().is_none(), overflow);
927
928        // Negation
929        let (neg, overflow) = i256::from_bigint_with_overflow(bl.clone().neg());
930        assert_eq!(il.wrapping_neg(), neg);
931        assert_eq!(il.checked_neg().is_none(), overflow);
932
933        // Negation
934        let (neg, overflow) = i256::from_bigint_with_overflow(br.clone().neg());
935        assert_eq!(ir.wrapping_neg(), neg);
936        assert_eq!(ir.checked_neg().is_none(), overflow);
937
938        // Addition
939        let actual = il.wrapping_add(ir);
940        let (expected, overflow) = i256::from_bigint_with_overflow(bl.clone() + br.clone());
941        assert_eq!(actual, expected);
942
943        let checked = il.checked_add(ir);
944        match overflow {
945            true => assert!(checked.is_none()),
946            false => assert_eq!(checked, Some(actual)),
947        }
948
949        // Subtraction
950        let actual = il.wrapping_sub(ir);
951        let (expected, overflow) = i256::from_bigint_with_overflow(bl.clone() - br.clone());
952        assert_eq!(actual.to_string(), expected.to_string());
953
954        let checked = il.checked_sub(ir);
955        match overflow {
956            true => assert!(checked.is_none()),
957            false => assert_eq!(checked, Some(actual), "{bl} - {br} = {expected}"),
958        }
959
960        // Multiplication
961        let actual = il.wrapping_mul(ir);
962        let (expected, overflow) = i256::from_bigint_with_overflow(bl.clone() * br.clone());
963        assert_eq!(actual.to_string(), expected.to_string());
964
965        let checked = il.checked_mul(ir);
966        match overflow {
967            true => assert!(
968                checked.is_none(),
969                "{il} * {ir} = {actual} vs {bl} * {br} = {expected}"
970            ),
971            false => assert_eq!(
972                checked,
973                Some(actual),
974                "{il} * {ir} = {actual} vs {bl} * {br} = {expected}"
975            ),
976        }
977
978        // Division
979        if ir != i256::ZERO {
980            let actual = il.wrapping_div(ir);
981            let expected = bl.clone() / br.clone();
982            let checked = il.checked_div(ir);
983
984            if ir == i256::MINUS_ONE && il == i256::MIN {
985                // BigInt produces an integer over i256::MAX
986                assert_eq!(actual, i256::MIN);
987                assert!(checked.is_none());
988            } else {
989                assert_eq!(actual.to_string(), expected.to_string());
990                assert_eq!(checked.unwrap().to_string(), expected.to_string());
991            }
992        } else {
993            // `wrapping_div` panics on division by zero
994            assert!(il.checked_div(ir).is_none());
995        }
996
997        // Remainder
998        if ir != i256::ZERO {
999            let actual = il.wrapping_rem(ir);
1000            let expected = bl.clone() % br.clone();
1001            let checked = il.checked_rem(ir);
1002
1003            assert_eq!(actual.to_string(), expected.to_string(), "{il} % {ir}");
1004
1005            if ir == i256::MINUS_ONE && il == i256::MIN {
1006                assert!(checked.is_none());
1007            } else {
1008                assert_eq!(checked.unwrap().to_string(), expected.to_string());
1009            }
1010        } else {
1011            // `wrapping_rem` panics on division by zero
1012            assert!(il.checked_rem(ir).is_none());
1013        }
1014
1015        // Exponentiation
1016        for exp in vec![0, 1, 2, 3, 8, 100].into_iter() {
1017            let actual = il.wrapping_pow(exp);
1018            let (expected, overflow) = i256::from_bigint_with_overflow(bl.clone().pow(exp));
1019            assert_eq!(actual.to_string(), expected.to_string());
1020
1021            let checked = il.checked_pow(exp);
1022            match overflow {
1023                true => assert!(
1024                    checked.is_none(),
1025                    "{il} ^ {exp} = {actual} vs {bl} * {exp} = {expected}"
1026                ),
1027                false => assert_eq!(
1028                    checked,
1029                    Some(actual),
1030                    "{il} ^ {exp} = {actual} vs {bl} ^ {exp} = {expected}"
1031                ),
1032            }
1033        }
1034
1035        // Bit operations
1036        let actual = il & ir;
1037        let (expected, _) = i256::from_bigint_with_overflow(bl.clone() & br.clone());
1038        assert_eq!(actual.to_string(), expected.to_string());
1039
1040        let actual = il | ir;
1041        let (expected, _) = i256::from_bigint_with_overflow(bl.clone() | br.clone());
1042        assert_eq!(actual.to_string(), expected.to_string());
1043
1044        let actual = il ^ ir;
1045        let (expected, _) = i256::from_bigint_with_overflow(bl.clone() ^ br);
1046        assert_eq!(actual.to_string(), expected.to_string());
1047
1048        for shift in [0_u8, 1, 4, 126, 128, 129, 254, 255] {
1049            let actual = il << shift;
1050            let (expected, _) = i256::from_bigint_with_overflow(bl.clone() << shift);
1051            assert_eq!(actual.to_string(), expected.to_string());
1052
1053            let actual = il >> shift;
1054            let (expected, _) = i256::from_bigint_with_overflow(bl.clone() >> shift);
1055            assert_eq!(actual.to_string(), expected.to_string());
1056        }
1057    }
1058
1059    #[test]
1060    fn test_i256() {
1061        let candidates = [
1062            i256::ZERO,
1063            i256::ONE,
1064            i256::MINUS_ONE,
1065            i256::from_i128(2),
1066            i256::from_i128(-2),
1067            i256::from_parts(u128::MAX, 1),
1068            i256::from_parts(u128::MAX, -1),
1069            i256::from_parts(0, 1),
1070            i256::from_parts(0, -1),
1071            i256::from_parts(1, -1),
1072            i256::from_parts(1, 1),
1073            i256::from_parts(0, i128::MAX),
1074            i256::from_parts(0, i128::MIN),
1075            i256::from_parts(1, i128::MAX),
1076            i256::from_parts(1, i128::MIN),
1077            i256::from_parts(u128::MAX, i128::MIN),
1078            i256::from_parts(100, 32),
1079            i256::MIN,
1080            i256::MAX,
1081            i256::MIN >> 1,
1082            i256::MAX >> 1,
1083            i256::ONE << 127,
1084            i256::ONE << 128,
1085            i256::ONE << 129,
1086            i256::MINUS_ONE << 127,
1087            i256::MINUS_ONE << 128,
1088            i256::MINUS_ONE << 129,
1089        ];
1090
1091        for il in candidates {
1092            for ir in candidates {
1093                test_ops(il, ir)
1094            }
1095        }
1096    }
1097
1098    #[test]
1099    fn test_signed_ops() {
1100        // signum
1101        assert_eq!(i256::from_i128(1).signum(), i256::ONE);
1102        assert_eq!(i256::from_i128(0).signum(), i256::ZERO);
1103        assert_eq!(i256::from_i128(-0).signum(), i256::ZERO);
1104        assert_eq!(i256::from_i128(-1).signum(), i256::MINUS_ONE);
1105
1106        // is_positive
1107        assert!(i256::from_i128(1).is_positive());
1108        assert!(!i256::from_i128(0).is_positive());
1109        assert!(!i256::from_i128(-0).is_positive());
1110        assert!(!i256::from_i128(-1).is_positive());
1111
1112        // is_negative
1113        assert!(!i256::from_i128(1).is_negative());
1114        assert!(!i256::from_i128(0).is_negative());
1115        assert!(!i256::from_i128(-0).is_negative());
1116        assert!(i256::from_i128(-1).is_negative());
1117    }
1118
1119    #[test]
1120    #[cfg_attr(miri, ignore)]
1121    fn test_i256_fuzz() {
1122        let mut rng = rng();
1123
1124        for _ in 0..1000 {
1125            let mut l = [0_u8; 32];
1126            let len = rng.random_range(0..32);
1127            l.iter_mut().take(len).for_each(|x| *x = rng.random());
1128
1129            let mut r = [0_u8; 32];
1130            let len = rng.random_range(0..32);
1131            r.iter_mut().take(len).for_each(|x| *x = rng.random());
1132
1133            test_ops(i256::from_le_bytes(l), i256::from_le_bytes(r))
1134        }
1135    }
1136
1137    #[test]
1138    fn test_i256_to_primitive() {
1139        let a = i256::MAX;
1140        assert!(a.to_i64().is_none());
1141        assert!(a.to_u64().is_none());
1142
1143        let a = i256::from_i128(i128::MAX);
1144        assert!(a.to_i64().is_none());
1145        assert!(a.to_u64().is_none());
1146
1147        let a = i256::from_i128(i64::MAX as i128);
1148        assert_eq!(a.to_i64().unwrap(), i64::MAX);
1149        assert_eq!(a.to_u64().unwrap(), i64::MAX as u64);
1150
1151        let a = i256::from_i128(i64::MAX as i128 + 1);
1152        assert!(a.to_i64().is_none());
1153        assert_eq!(a.to_u64().unwrap(), i64::MAX as u64 + 1);
1154
1155        let a = i256::MIN;
1156        assert!(a.to_i64().is_none());
1157        assert!(a.to_u64().is_none());
1158
1159        let a = i256::from_i128(i128::MIN);
1160        assert!(a.to_i64().is_none());
1161        assert!(a.to_u64().is_none());
1162
1163        let a = i256::from_i128(i64::MIN as i128);
1164        assert_eq!(a.to_i64().unwrap(), i64::MIN);
1165        assert!(a.to_u64().is_none());
1166
1167        let a = i256::from_i128(i64::MIN as i128 - 1);
1168        assert!(a.to_i64().is_none());
1169        assert!(a.to_u64().is_none());
1170    }
1171
1172    #[test]
1173    fn test_i256_as_i128() {
1174        let a = i256::from_i128(i128::MAX).wrapping_add(i256::from_i128(1));
1175        let i128 = a.as_i128();
1176        assert_eq!(i128, i128::MIN);
1177
1178        let a = i256::from_i128(i128::MAX).wrapping_add(i256::from_i128(2));
1179        let i128 = a.as_i128();
1180        assert_eq!(i128, i128::MIN + 1);
1181
1182        let a = i256::from_i128(i128::MIN).wrapping_sub(i256::from_i128(1));
1183        let i128 = a.as_i128();
1184        assert_eq!(i128, i128::MAX);
1185
1186        let a = i256::from_i128(i128::MIN).wrapping_sub(i256::from_i128(2));
1187        let i128 = a.as_i128();
1188        assert_eq!(i128, i128::MAX - 1);
1189    }
1190
1191    #[test]
1192    fn test_string_roundtrip() {
1193        let roundtrip_cases = [
1194            i256::ZERO,
1195            i256::ONE,
1196            i256::MINUS_ONE,
1197            i256::from_i128(123456789),
1198            i256::from_i128(-123456789),
1199            i256::from_i128(i128::MIN),
1200            i256::from_i128(i128::MAX),
1201            i256::MIN,
1202            i256::MAX,
1203        ];
1204        for case in roundtrip_cases {
1205            let formatted = case.to_string();
1206            let back: i256 = formatted.parse().unwrap();
1207            assert_eq!(case, back);
1208        }
1209    }
1210
1211    #[test]
1212    fn test_from_string() {
1213        let cases = [
1214            (
1215                "000000000000000000000000000000000000000011",
1216                Some(i256::from_i128(11)),
1217            ),
1218            (
1219                "-000000000000000000000000000000000000000011",
1220                Some(i256::from_i128(-11)),
1221            ),
1222            (
1223                "-0000000000000000000000000000000000000000123456789",
1224                Some(i256::from_i128(-123456789)),
1225            ),
1226            ("-", None),
1227            ("+", None),
1228            ("--1", None),
1229            ("-+1", None),
1230            ("000000000000000000000000000000000000000", Some(i256::ZERO)),
1231            ("0000000000000000000000000000000000000000-11", None),
1232            ("11-1111111111111111111111111111111111111", None),
1233            (
1234                "115792089237316195423570985008687907853269984665640564039457584007913129639936",
1235                None,
1236            ),
1237        ];
1238        for (case, expected) in cases {
1239            assert_eq!(i256::from_string(case), expected)
1240        }
1241    }
1242
1243    #[allow(clippy::op_ref)]
1244    fn test_reference_op(il: i256, ir: i256) {
1245        let r1 = il + ir;
1246        let r2 = &il + ir;
1247        let r3 = il + &ir;
1248        let r4 = &il + &ir;
1249        assert_eq!(r1, r2);
1250        assert_eq!(r1, r3);
1251        assert_eq!(r1, r4);
1252
1253        let r1 = il - ir;
1254        let r2 = &il - ir;
1255        let r3 = il - &ir;
1256        let r4 = &il - &ir;
1257        assert_eq!(r1, r2);
1258        assert_eq!(r1, r3);
1259        assert_eq!(r1, r4);
1260
1261        let r1 = il * ir;
1262        let r2 = &il * ir;
1263        let r3 = il * &ir;
1264        let r4 = &il * &ir;
1265        assert_eq!(r1, r2);
1266        assert_eq!(r1, r3);
1267        assert_eq!(r1, r4);
1268
1269        let r1 = il / ir;
1270        let r2 = &il / ir;
1271        let r3 = il / &ir;
1272        let r4 = &il / &ir;
1273        assert_eq!(r1, r2);
1274        assert_eq!(r1, r3);
1275        assert_eq!(r1, r4);
1276    }
1277
1278    #[test]
1279    fn test_i256_reference_op() {
1280        let candidates = [
1281            i256::ONE,
1282            i256::MINUS_ONE,
1283            i256::from_i128(2),
1284            i256::from_i128(-2),
1285            i256::from_i128(3),
1286            i256::from_i128(-3),
1287        ];
1288
1289        for il in candidates {
1290            for ir in candidates {
1291                test_reference_op(il, ir)
1292            }
1293        }
1294    }
1295
1296    #[test]
1297    fn test_decimal256_to_f64_typical_values() {
1298        let v = i256::from_i128(42_i128);
1299        assert_eq!(v.to_f64().unwrap(), 42.0);
1300
1301        let v = i256::from_i128(-123456789012345678i128);
1302        assert_eq!(v.to_f64().unwrap(), -123456789012345678.0);
1303
1304        let v = i256::from_string("0").unwrap();
1305        assert_eq!(v.to_f64().unwrap(), 0.0);
1306
1307        let v = i256::from_string("1").unwrap();
1308        assert_eq!(v.to_f64().unwrap(), 1.0);
1309
1310        let mut rng = rng();
1311        for _ in 0..10 {
1312            let f64_value =
1313                (rng.random_range(i128::MIN..i128::MAX) as f64) * rng.random_range(0.0..1.0);
1314            let big = i256::from_f64(f64_value).unwrap();
1315            assert_eq!(big.to_f64().unwrap(), f64_value);
1316        }
1317    }
1318
1319    #[test]
1320    fn test_decimal256_to_f64_large_positive_value() {
1321        let max_f = f64::MAX;
1322        let big = i256::from_f64(max_f * 2.0).unwrap_or(i256::MAX);
1323        let out = big.to_f64().unwrap();
1324        assert!(out.is_finite() && out.is_sign_positive());
1325    }
1326
1327    #[test]
1328    fn test_decimal256_to_f64_large_negative_value() {
1329        let max_f = f64::MAX;
1330        let big_neg = i256::from_f64(-(max_f * 2.0)).unwrap_or(i256::MIN);
1331        let out = big_neg.to_f64().unwrap();
1332        assert!(out.is_finite() && out.is_sign_negative());
1333    }
1334}