1use 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#[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
46enum DivRemError {
48 DivideByZero,
50 DivideOverflow,
52}
53
54#[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 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 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 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
129fn 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 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 self.high.cmp(&other.high).then(self.low.cmp(&other.low))
171 }
172}
173
174impl i256 {
175 pub const ZERO: Self = i256 { low: 0, high: 0 };
177
178 pub const ONE: Self = i256 { low: 1, high: 0 };
180
181 pub const MINUS_ONE: Self = i256 {
183 low: u128::MAX,
184 high: -1,
185 };
186
187 pub const MAX: Self = i256 {
189 low: u128::MAX,
190 high: i128::MAX,
191 };
192
193 pub const MIN: Self = i256 {
195 low: u128::MIN,
196 high: i128::MIN,
197 };
198
199 #[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 #[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 pub const fn from_i128(v: i128) -> Self {
221 Self::from_parts(v as u128, v >> 127)
222 }
223
224 #[inline]
226 pub fn from_string(value_str: &str) -> Option<Self> {
227 value_str.parse().ok()
228 }
229
230 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 #[inline]
245 pub const fn from_parts(low: u128, high: i128) -> Self {
246 Self { low, high }
247 }
248
249 pub const fn to_parts(self) -> (u128, i128) {
251 (self.low, self.high)
252 }
253
254 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 pub fn as_i128(self) -> i128 {
268 self.low as i128
269 }
270
271 #[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 #[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 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 #[inline]
322 pub fn wrapping_abs(self) -> Self {
323 let sa = self.high >> 127;
325 let sa = Self::from_parts(sa as u128, sa);
326
327 Self::from_parts(self.low ^ sa.low, self.high ^ sa.high).wrapping_sub(sa)
329 }
330
331 #[inline]
333 pub fn checked_abs(self) -> Option<Self> {
334 (self != Self::MIN).then(|| self.wrapping_abs())
335 }
336
337 #[inline]
339 pub fn wrapping_neg(self) -> Self {
340 Self::from_parts(!self.low, !self.high).wrapping_add(i256::ONE)
341 }
342
343 #[inline]
345 pub fn checked_neg(self) -> Option<Self> {
346 (self != Self::MIN).then(|| self.wrapping_neg())
347 }
348
349 #[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 #[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 #[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 #[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 #[inline]
381 pub fn wrapping_mul(self, other: Self) -> Self {
382 let (low, high) = mulx(self.low, other.low);
383
384 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 #[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 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 let l_abs = self.wrapping_abs();
408 let r_abs = other.wrapping_abs();
409
410 if l_abs.high != 0 && r_abs.high != 0 {
412 return None;
413 }
414
415 let (low, high) = mulx(l_abs.low, r_abs.low);
417
418 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 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 (high.is_negative() == (self.is_negative() ^ other.is_negative()))
430 .then_some(Self { low, high })
431 }
432
433 #[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 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 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 #[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 #[inline]
495 pub fn checked_div(self, other: Self) -> Option<Self> {
496 self.div_rem(other).map(|(v, _)| v).ok()
497 }
498
499 #[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 #[inline]
511 pub fn checked_rem(self, other: Self) -> Option<Self> {
512 self.div_rem(other).map(|(_, v)| v).ok()
513 }
514
515 #[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 acc.checked_mul(base)
537 }
538
539 #[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 acc.wrapping_mul(base)
562 }
563
564 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 #[inline]
581 pub const fn is_negative(self) -> bool {
582 self.high.is_negative()
583 }
584
585 pub const fn is_positive(self) -> bool {
587 self.high.is_positive() || self.high == 0 && self.low != 0
588 }
589}
590
591const fn split_array<const N: usize, const M: usize>(vals: [u8; N]) -> ([u8; M], [u8; M]) {
594 let mut a = [0; M];
595 let mut b = [0; M];
596 let mut i = 0;
597 while i != M {
598 a[i] = vals[i];
599 b[i] = vals[i + M];
600 i += 1;
601 }
602 (a, b)
603}
604
605#[inline]
611fn mulx(a: u128, b: u128) -> (u128, u128) {
612 let split = |a: u128| (a & (u64::MAX as u128), a >> 64);
613
614 const MASK: u128 = u64::MAX as _;
615
616 let (a_low, a_high) = split(a);
617 let (b_low, b_high) = split(b);
618
619 let (mut low, mut carry) = split(a_low * b_low);
621 carry += a_high * b_low;
622
623 low += carry << 64;
625 let mut high = carry >> 64;
626
627 carry = low >> 64;
629 low &= MASK;
630
631 carry += b_high * a_low;
633
634 low += carry << 64;
636 high += carry >> 64;
637
638 high += a_high * b_high;
640
641 (low, high)
642}
643
644derive_arith!(
645 i256,
646 Add,
647 AddAssign,
648 add,
649 add_assign,
650 wrapping_add,
651 checked_add
652);
653derive_arith!(
654 i256,
655 Sub,
656 SubAssign,
657 sub,
658 sub_assign,
659 wrapping_sub,
660 checked_sub
661);
662derive_arith!(
663 i256,
664 Mul,
665 MulAssign,
666 mul,
667 mul_assign,
668 wrapping_mul,
669 checked_mul
670);
671derive_arith!(
672 i256,
673 Div,
674 DivAssign,
675 div,
676 div_assign,
677 wrapping_div,
678 checked_div
679);
680derive_arith!(
681 i256,
682 Rem,
683 RemAssign,
684 rem,
685 rem_assign,
686 wrapping_rem,
687 checked_rem
688);
689
690impl Neg for i256 {
691 type Output = i256;
692
693 #[cfg(debug_assertions)]
694 fn neg(self) -> Self::Output {
695 self.checked_neg().expect("i256 overflow")
696 }
697
698 #[cfg(not(debug_assertions))]
699 fn neg(self) -> Self::Output {
700 self.wrapping_neg()
701 }
702}
703
704impl BitAnd for i256 {
705 type Output = i256;
706
707 #[inline]
708 fn bitand(self, rhs: Self) -> Self::Output {
709 Self {
710 low: self.low & rhs.low,
711 high: self.high & rhs.high,
712 }
713 }
714}
715
716impl BitOr for i256 {
717 type Output = i256;
718
719 #[inline]
720 fn bitor(self, rhs: Self) -> Self::Output {
721 Self {
722 low: self.low | rhs.low,
723 high: self.high | rhs.high,
724 }
725 }
726}
727
728impl BitXor for i256 {
729 type Output = i256;
730
731 #[inline]
732 fn bitxor(self, rhs: Self) -> Self::Output {
733 Self {
734 low: self.low ^ rhs.low,
735 high: self.high ^ rhs.high,
736 }
737 }
738}
739
740impl Shl<u8> for i256 {
741 type Output = i256;
742
743 #[inline]
744 fn shl(self, rhs: u8) -> Self::Output {
745 if rhs == 0 {
746 self
747 } else if rhs < 128 {
748 Self {
749 high: self.high << rhs | (self.low >> (128 - rhs)) as i128,
750 low: self.low << rhs,
751 }
752 } else {
753 Self {
754 high: (self.low << (rhs - 128)) as i128,
755 low: 0,
756 }
757 }
758 }
759}
760
761impl Shr<u8> for i256 {
762 type Output = i256;
763
764 #[inline]
765 fn shr(self, rhs: u8) -> Self::Output {
766 if rhs == 0 {
767 self
768 } else if rhs < 128 {
769 Self {
770 high: self.high >> rhs,
771 low: self.low >> rhs | ((self.high as u128) << (128 - rhs)),
772 }
773 } else {
774 Self {
775 high: self.high >> 127,
776 low: (self.high >> (rhs - 128)) as u128,
777 }
778 }
779 }
780}
781
782macro_rules! define_as_primitive {
783 ($native_ty:ty) => {
784 impl AsPrimitive<i256> for $native_ty {
785 fn as_(self) -> i256 {
786 i256::from_i128(self as i128)
787 }
788 }
789 };
790}
791
792define_as_primitive!(i8);
793define_as_primitive!(i16);
794define_as_primitive!(i32);
795define_as_primitive!(i64);
796define_as_primitive!(u8);
797define_as_primitive!(u16);
798define_as_primitive!(u32);
799define_as_primitive!(u64);
800
801impl ToPrimitive for i256 {
802 fn to_i64(&self) -> Option<i64> {
803 let as_i128 = self.low as i128;
804
805 let high_negative = self.high < 0;
806 let low_negative = as_i128 < 0;
807 let high_valid = self.high == -1 || self.high == 0;
808
809 if high_negative == low_negative && high_valid {
810 let (low_bytes, high_bytes) = split_array(u128::to_le_bytes(self.low));
811 let high = i64::from_le_bytes(high_bytes);
812 let low = i64::from_le_bytes(low_bytes);
813
814 let high_negative = high < 0;
815 let low_negative = low < 0;
816 let high_valid = self.high == -1 || self.high == 0;
817
818 (high_negative == low_negative && high_valid).then_some(low)
819 } else {
820 None
821 }
822 }
823
824 fn to_u64(&self) -> Option<u64> {
825 let as_i128 = self.low as i128;
826
827 let high_negative = self.high < 0;
828 let low_negative = as_i128 < 0;
829 let high_valid = self.high == -1 || self.high == 0;
830
831 if high_negative == low_negative && high_valid {
832 self.low.to_u64()
833 } else {
834 None
835 }
836 }
837}
838
839#[cfg(all(test, not(miri)))] mod tests {
841 use super::*;
842 use num::Signed;
843 use rand::{thread_rng, Rng};
844
845 #[test]
846 fn test_signed_cmp() {
847 let a = i256::from_parts(i128::MAX as u128, 12);
848 let b = i256::from_parts(i128::MIN as u128, 12);
849 assert!(a < b);
850
851 let a = i256::from_parts(i128::MAX as u128, 12);
852 let b = i256::from_parts(i128::MIN as u128, -12);
853 assert!(a > b);
854 }
855
856 #[test]
857 fn test_to_i128() {
858 let vals = [
859 BigInt::from_i128(-1).unwrap(),
860 BigInt::from_i128(i128::MAX).unwrap(),
861 BigInt::from_i128(i128::MIN).unwrap(),
862 BigInt::from_u128(u128::MIN).unwrap(),
863 BigInt::from_u128(u128::MAX).unwrap(),
864 ];
865
866 for v in vals {
867 let (t, overflow) = i256::from_bigint_with_overflow(v.clone());
868 assert!(!overflow);
869 assert_eq!(t.to_i128(), v.to_i128(), "{v} vs {t}");
870 }
871 }
872
873 fn test_ops(il: i256, ir: i256) {
875 let bl = BigInt::from_signed_bytes_le(&il.to_le_bytes());
876 let br = BigInt::from_signed_bytes_le(&ir.to_le_bytes());
877
878 assert_eq!(il.cmp(&ir), bl.cmp(&br), "{bl} cmp {br}");
880
881 assert_eq!(i256::from_le_bytes(il.to_le_bytes()), il);
883 assert_eq!(i256::from_be_bytes(il.to_be_bytes()), il);
884 assert_eq!(i256::from_le_bytes(ir.to_le_bytes()), ir);
885 assert_eq!(i256::from_be_bytes(ir.to_be_bytes()), ir);
886
887 assert_eq!(il.to_i128(), bl.to_i128(), "{bl}");
889 assert_eq!(ir.to_i128(), br.to_i128(), "{br}");
890
891 let (abs, overflow) = i256::from_bigint_with_overflow(bl.abs());
893 assert_eq!(il.wrapping_abs(), abs);
894 assert_eq!(il.checked_abs().is_none(), overflow);
895
896 let (abs, overflow) = i256::from_bigint_with_overflow(br.abs());
897 assert_eq!(ir.wrapping_abs(), abs);
898 assert_eq!(ir.checked_abs().is_none(), overflow);
899
900 let (neg, overflow) = i256::from_bigint_with_overflow(bl.clone().neg());
902 assert_eq!(il.wrapping_neg(), neg);
903 assert_eq!(il.checked_neg().is_none(), overflow);
904
905 let (neg, overflow) = i256::from_bigint_with_overflow(br.clone().neg());
907 assert_eq!(ir.wrapping_neg(), neg);
908 assert_eq!(ir.checked_neg().is_none(), overflow);
909
910 let actual = il.wrapping_add(ir);
912 let (expected, overflow) = i256::from_bigint_with_overflow(bl.clone() + br.clone());
913 assert_eq!(actual, expected);
914
915 let checked = il.checked_add(ir);
916 match overflow {
917 true => assert!(checked.is_none()),
918 false => assert_eq!(checked, Some(actual)),
919 }
920
921 let actual = il.wrapping_sub(ir);
923 let (expected, overflow) = i256::from_bigint_with_overflow(bl.clone() - br.clone());
924 assert_eq!(actual.to_string(), expected.to_string());
925
926 let checked = il.checked_sub(ir);
927 match overflow {
928 true => assert!(checked.is_none()),
929 false => assert_eq!(checked, Some(actual), "{bl} - {br} = {expected}"),
930 }
931
932 let actual = il.wrapping_mul(ir);
934 let (expected, overflow) = i256::from_bigint_with_overflow(bl.clone() * br.clone());
935 assert_eq!(actual.to_string(), expected.to_string());
936
937 let checked = il.checked_mul(ir);
938 match overflow {
939 true => assert!(
940 checked.is_none(),
941 "{il} * {ir} = {actual} vs {bl} * {br} = {expected}"
942 ),
943 false => assert_eq!(
944 checked,
945 Some(actual),
946 "{il} * {ir} = {actual} vs {bl} * {br} = {expected}"
947 ),
948 }
949
950 if ir != i256::ZERO {
952 let actual = il.wrapping_div(ir);
953 let expected = bl.clone() / br.clone();
954 let checked = il.checked_div(ir);
955
956 if ir == i256::MINUS_ONE && il == i256::MIN {
957 assert_eq!(actual, i256::MIN);
959 assert!(checked.is_none());
960 } else {
961 assert_eq!(actual.to_string(), expected.to_string());
962 assert_eq!(checked.unwrap().to_string(), expected.to_string());
963 }
964 } else {
965 assert!(il.checked_div(ir).is_none());
967 }
968
969 if ir != i256::ZERO {
971 let actual = il.wrapping_rem(ir);
972 let expected = bl.clone() % br.clone();
973 let checked = il.checked_rem(ir);
974
975 assert_eq!(actual.to_string(), expected.to_string(), "{il} % {ir}");
976
977 if ir == i256::MINUS_ONE && il == i256::MIN {
978 assert!(checked.is_none());
979 } else {
980 assert_eq!(checked.unwrap().to_string(), expected.to_string());
981 }
982 } else {
983 assert!(il.checked_rem(ir).is_none());
985 }
986
987 for exp in vec![0, 1, 2, 3, 8, 100].into_iter() {
989 let actual = il.wrapping_pow(exp);
990 let (expected, overflow) = i256::from_bigint_with_overflow(bl.clone().pow(exp));
991 assert_eq!(actual.to_string(), expected.to_string());
992
993 let checked = il.checked_pow(exp);
994 match overflow {
995 true => assert!(
996 checked.is_none(),
997 "{il} ^ {exp} = {actual} vs {bl} * {exp} = {expected}"
998 ),
999 false => assert_eq!(
1000 checked,
1001 Some(actual),
1002 "{il} ^ {exp} = {actual} vs {bl} ^ {exp} = {expected}"
1003 ),
1004 }
1005 }
1006
1007 let actual = il & ir;
1009 let (expected, _) = i256::from_bigint_with_overflow(bl.clone() & br.clone());
1010 assert_eq!(actual.to_string(), expected.to_string());
1011
1012 let actual = il | ir;
1013 let (expected, _) = i256::from_bigint_with_overflow(bl.clone() | br.clone());
1014 assert_eq!(actual.to_string(), expected.to_string());
1015
1016 let actual = il ^ ir;
1017 let (expected, _) = i256::from_bigint_with_overflow(bl.clone() ^ br);
1018 assert_eq!(actual.to_string(), expected.to_string());
1019
1020 for shift in [0_u8, 1, 4, 126, 128, 129, 254, 255] {
1021 let actual = il << shift;
1022 let (expected, _) = i256::from_bigint_with_overflow(bl.clone() << shift);
1023 assert_eq!(actual.to_string(), expected.to_string());
1024
1025 let actual = il >> shift;
1026 let (expected, _) = i256::from_bigint_with_overflow(bl.clone() >> shift);
1027 assert_eq!(actual.to_string(), expected.to_string());
1028 }
1029 }
1030
1031 #[test]
1032 fn test_i256() {
1033 let candidates = [
1034 i256::ZERO,
1035 i256::ONE,
1036 i256::MINUS_ONE,
1037 i256::from_i128(2),
1038 i256::from_i128(-2),
1039 i256::from_parts(u128::MAX, 1),
1040 i256::from_parts(u128::MAX, -1),
1041 i256::from_parts(0, 1),
1042 i256::from_parts(0, -1),
1043 i256::from_parts(1, -1),
1044 i256::from_parts(1, 1),
1045 i256::from_parts(0, i128::MAX),
1046 i256::from_parts(0, i128::MIN),
1047 i256::from_parts(1, i128::MAX),
1048 i256::from_parts(1, i128::MIN),
1049 i256::from_parts(u128::MAX, i128::MIN),
1050 i256::from_parts(100, 32),
1051 i256::MIN,
1052 i256::MAX,
1053 i256::MIN >> 1,
1054 i256::MAX >> 1,
1055 i256::ONE << 127,
1056 i256::ONE << 128,
1057 i256::ONE << 129,
1058 i256::MINUS_ONE << 127,
1059 i256::MINUS_ONE << 128,
1060 i256::MINUS_ONE << 129,
1061 ];
1062
1063 for il in candidates {
1064 for ir in candidates {
1065 test_ops(il, ir)
1066 }
1067 }
1068 }
1069
1070 #[test]
1071 fn test_signed_ops() {
1072 assert_eq!(i256::from_i128(1).signum(), i256::ONE);
1074 assert_eq!(i256::from_i128(0).signum(), i256::ZERO);
1075 assert_eq!(i256::from_i128(-0).signum(), i256::ZERO);
1076 assert_eq!(i256::from_i128(-1).signum(), i256::MINUS_ONE);
1077
1078 assert!(i256::from_i128(1).is_positive());
1080 assert!(!i256::from_i128(0).is_positive());
1081 assert!(!i256::from_i128(-0).is_positive());
1082 assert!(!i256::from_i128(-1).is_positive());
1083
1084 assert!(!i256::from_i128(1).is_negative());
1086 assert!(!i256::from_i128(0).is_negative());
1087 assert!(!i256::from_i128(-0).is_negative());
1088 assert!(i256::from_i128(-1).is_negative());
1089 }
1090
1091 #[test]
1092 #[cfg_attr(miri, ignore)]
1093 fn test_i256_fuzz() {
1094 let mut rng = thread_rng();
1095
1096 for _ in 0..1000 {
1097 let mut l = [0_u8; 32];
1098 let len = rng.gen_range(0..32);
1099 l.iter_mut().take(len).for_each(|x| *x = rng.gen());
1100
1101 let mut r = [0_u8; 32];
1102 let len = rng.gen_range(0..32);
1103 r.iter_mut().take(len).for_each(|x| *x = rng.gen());
1104
1105 test_ops(i256::from_le_bytes(l), i256::from_le_bytes(r))
1106 }
1107 }
1108
1109 #[test]
1110 fn test_i256_to_primitive() {
1111 let a = i256::MAX;
1112 assert!(a.to_i64().is_none());
1113 assert!(a.to_u64().is_none());
1114
1115 let a = i256::from_i128(i128::MAX);
1116 assert!(a.to_i64().is_none());
1117 assert!(a.to_u64().is_none());
1118
1119 let a = i256::from_i128(i64::MAX as i128);
1120 assert_eq!(a.to_i64().unwrap(), i64::MAX);
1121 assert_eq!(a.to_u64().unwrap(), i64::MAX as u64);
1122
1123 let a = i256::from_i128(i64::MAX as i128 + 1);
1124 assert!(a.to_i64().is_none());
1125 assert_eq!(a.to_u64().unwrap(), i64::MAX as u64 + 1);
1126
1127 let a = i256::MIN;
1128 assert!(a.to_i64().is_none());
1129 assert!(a.to_u64().is_none());
1130
1131 let a = i256::from_i128(i128::MIN);
1132 assert!(a.to_i64().is_none());
1133 assert!(a.to_u64().is_none());
1134
1135 let a = i256::from_i128(i64::MIN as i128);
1136 assert_eq!(a.to_i64().unwrap(), i64::MIN);
1137 assert!(a.to_u64().is_none());
1138
1139 let a = i256::from_i128(i64::MIN as i128 - 1);
1140 assert!(a.to_i64().is_none());
1141 assert!(a.to_u64().is_none());
1142 }
1143
1144 #[test]
1145 fn test_i256_as_i128() {
1146 let a = i256::from_i128(i128::MAX).wrapping_add(i256::from_i128(1));
1147 let i128 = a.as_i128();
1148 assert_eq!(i128, i128::MIN);
1149
1150 let a = i256::from_i128(i128::MAX).wrapping_add(i256::from_i128(2));
1151 let i128 = a.as_i128();
1152 assert_eq!(i128, i128::MIN + 1);
1153
1154 let a = i256::from_i128(i128::MIN).wrapping_sub(i256::from_i128(1));
1155 let i128 = a.as_i128();
1156 assert_eq!(i128, i128::MAX);
1157
1158 let a = i256::from_i128(i128::MIN).wrapping_sub(i256::from_i128(2));
1159 let i128 = a.as_i128();
1160 assert_eq!(i128, i128::MAX - 1);
1161 }
1162
1163 #[test]
1164 fn test_string_roundtrip() {
1165 let roundtrip_cases = [
1166 i256::ZERO,
1167 i256::ONE,
1168 i256::MINUS_ONE,
1169 i256::from_i128(123456789),
1170 i256::from_i128(-123456789),
1171 i256::from_i128(i128::MIN),
1172 i256::from_i128(i128::MAX),
1173 i256::MIN,
1174 i256::MAX,
1175 ];
1176 for case in roundtrip_cases {
1177 let formatted = case.to_string();
1178 let back: i256 = formatted.parse().unwrap();
1179 assert_eq!(case, back);
1180 }
1181 }
1182
1183 #[test]
1184 fn test_from_string() {
1185 let cases = [
1186 (
1187 "000000000000000000000000000000000000000011",
1188 Some(i256::from_i128(11)),
1189 ),
1190 (
1191 "-000000000000000000000000000000000000000011",
1192 Some(i256::from_i128(-11)),
1193 ),
1194 (
1195 "-0000000000000000000000000000000000000000123456789",
1196 Some(i256::from_i128(-123456789)),
1197 ),
1198 ("-", None),
1199 ("+", None),
1200 ("--1", None),
1201 ("-+1", None),
1202 ("000000000000000000000000000000000000000", Some(i256::ZERO)),
1203 ("0000000000000000000000000000000000000000-11", None),
1204 ("11-1111111111111111111111111111111111111", None),
1205 (
1206 "115792089237316195423570985008687907853269984665640564039457584007913129639936",
1207 None,
1208 ),
1209 ];
1210 for (case, expected) in cases {
1211 assert_eq!(i256::from_string(case), expected)
1212 }
1213 }
1214
1215 #[allow(clippy::op_ref)]
1216 fn test_reference_op(il: i256, ir: i256) {
1217 let r1 = il + ir;
1218 let r2 = &il + ir;
1219 let r3 = il + &ir;
1220 let r4 = &il + &ir;
1221 assert_eq!(r1, r2);
1222 assert_eq!(r1, r3);
1223 assert_eq!(r1, r4);
1224
1225 let r1 = il - ir;
1226 let r2 = &il - ir;
1227 let r3 = il - &ir;
1228 let r4 = &il - &ir;
1229 assert_eq!(r1, r2);
1230 assert_eq!(r1, r3);
1231 assert_eq!(r1, r4);
1232
1233 let r1 = il * ir;
1234 let r2 = &il * ir;
1235 let r3 = il * &ir;
1236 let r4 = &il * &ir;
1237 assert_eq!(r1, r2);
1238 assert_eq!(r1, r3);
1239 assert_eq!(r1, r4);
1240
1241 let r1 = il / ir;
1242 let r2 = &il / ir;
1243 let r3 = il / &ir;
1244 let r4 = &il / &ir;
1245 assert_eq!(r1, r2);
1246 assert_eq!(r1, r3);
1247 assert_eq!(r1, r4);
1248 }
1249
1250 #[test]
1251 fn test_i256_reference_op() {
1252 let candidates = [
1253 i256::ONE,
1254 i256::MINUS_ONE,
1255 i256::from_i128(2),
1256 i256::from_i128(-2),
1257 i256::from_i128(3),
1258 i256::from_i128(-3),
1259 ];
1260
1261 for il in candidates {
1262 for ir in candidates {
1263 test_reference_op(il, ir)
1264 }
1265 }
1266 }
1267}