ethnum/int/api.rs
1//! Module containing integer aritimetic methods closely following the Rust
2//! standard library API for `iN` types.
3
4use crate::{intrinsics, I256, U256};
5use core::{
6 mem::{self, MaybeUninit},
7 num::ParseIntError,
8};
9
10impl I256 {
11 /// The smallest value that can be represented by this integer type,
12 /// -2<sup>255</sup>.
13 ///
14 /// # Examples
15 ///
16 /// Basic usage:
17 ///
18 /// ```
19 /// # use ethnum::I256;
20 /// assert_eq!(
21 /// I256::MIN.to_string(),
22 /// "-57896044618658097711785492504343953926634992332820282019728792003956564819968",
23 /// );
24 /// ```
25 pub const MIN: Self = Self::from_words(i128::MIN, 0);
26
27 /// The largest value that can be represented by this integer type,
28 /// 2<sup>255</sup> - 1.
29 ///
30 /// # Examples
31 ///
32 /// Basic usage:
33 ///
34 /// ```
35 /// # use ethnum::I256;
36 /// assert_eq!(
37 /// I256::MAX.to_string(),
38 /// "57896044618658097711785492504343953926634992332820282019728792003956564819967",
39 /// );
40 /// ```
41 pub const MAX: Self = Self::from_words(i128::MAX, -1);
42
43 /// The size of this integer type in bits.
44 ///
45 /// # Examples
46 ///
47 /// ```
48 /// # use ethnum::I256;
49 /// assert_eq!(I256::BITS, 256);
50 /// ```
51 pub const BITS: u32 = 256;
52
53 /// Converts a string slice in a given base to an integer.
54 ///
55 /// The string is expected to be an optional `+` or `-` sign followed by
56 /// digits. Leading and trailing whitespace represent an error. Digits are a
57 /// subset of these characters, depending on `radix`:
58 ///
59 /// * `0-9`
60 /// * `a-z`
61 /// * `A-Z`
62 ///
63 /// # Panics
64 ///
65 /// This function panics if `radix` is not in the range from 2 to 36.
66 ///
67 /// # Examples
68 ///
69 /// Basic usage:
70 ///
71 /// ```
72 /// # use ethnum::I256;
73 /// assert_eq!(I256::from_str_radix("A", 16), Ok(I256::new(10)));
74 /// ```
75 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
76 crate::parse::from_str_radix(src, radix, None)
77 }
78
79 /// Returns the number of ones in the binary representation of `self`.
80 ///
81 /// # Examples
82 ///
83 /// Basic usage:
84 ///
85 /// ```
86 /// # use ethnum::I256;
87 /// let n = I256::new(0b100_0000);
88 ///
89 /// assert_eq!(n.count_ones(), 1);
90 /// ```
91 ///
92 #[doc(alias = "popcount")]
93 #[doc(alias = "popcnt")]
94 #[inline]
95 pub const fn count_ones(self) -> u32 {
96 let Self([a, b]) = self;
97 a.count_ones() + b.count_ones()
98 }
99
100 /// Returns the number of zeros in the binary representation of `self`.
101 ///
102 /// # Examples
103 ///
104 /// Basic usage:
105 ///
106 /// ```
107 /// # use ethnum::I256;
108 /// assert_eq!(I256::MAX.count_zeros(), 1);
109 /// ```
110 #[inline]
111 pub const fn count_zeros(self) -> u32 {
112 let Self([a, b]) = self;
113 a.count_zeros() + b.count_zeros()
114 }
115
116 /// Returns the number of leading zeros in the binary representation of
117 /// `self`.
118 ///
119 /// # Examples
120 ///
121 /// Basic usage:
122 ///
123 /// ```
124 /// # use ethnum::I256;
125 /// let n = I256::new(-1);
126 ///
127 /// assert_eq!(n.leading_zeros(), 0);
128 /// ```
129 #[inline(always)]
130 pub fn leading_zeros(self) -> u32 {
131 intrinsics::signed::ictlz(&self)
132 }
133
134 /// Returns the number of trailing zeros in the binary representation of
135 /// `self`.
136 ///
137 /// # Examples
138 ///
139 /// Basic usage:
140 ///
141 /// ```
142 /// # use ethnum::I256;
143 /// let n = I256::new(-4);
144 ///
145 /// assert_eq!(n.trailing_zeros(), 2);
146 /// ```
147 #[inline(always)]
148 pub fn trailing_zeros(self) -> u32 {
149 intrinsics::signed::icttz(&self)
150 }
151
152 /// Returns the number of leading ones in the binary representation of
153 /// `self`.
154 ///
155 /// # Examples
156 ///
157 /// Basic usage:
158 ///
159 /// ```
160 /// # use ethnum::I256;
161 /// let n = I256::new(-1);
162 ///
163 /// assert_eq!(n.leading_ones(), 256);
164 /// ```
165 #[inline]
166 pub fn leading_ones(self) -> u32 {
167 (!self).leading_zeros()
168 }
169
170 /// Returns the number of trailing ones in the binary representation of
171 /// `self`.
172 ///
173 /// # Examples
174 ///
175 /// Basic usage:
176 ///
177 /// ```
178 /// # use ethnum::I256;
179 /// let n = I256::new(3);
180 ///
181 /// assert_eq!(n.trailing_ones(), 2);
182 /// ```
183 #[inline]
184 pub fn trailing_ones(self) -> u32 {
185 (!self).trailing_zeros()
186 }
187
188 /// Shifts the bits to the left by a specified amount, `n`,
189 /// wrapping the truncated bits to the end of the resulting integer.
190 ///
191 /// Please note this isn't the same operation as the `<<` shifting operator!
192 ///
193 /// # Examples
194 ///
195 /// Basic usage:
196 ///
197 /// ```
198 /// # use ethnum::I256;
199 /// let n = I256::from_words(
200 /// 0x13f40000000000000000000000000000,
201 /// 0x00000000000000000000000000004f76,
202 /// );
203 /// let m = I256::new(0x4f7613f4);
204 ///
205 /// assert_eq!(n.rotate_left(16), m);
206 /// ```
207 #[must_use = "this returns the result of the operation, \
208 without modifying the original"]
209 #[inline(always)]
210 pub fn rotate_left(self, n: u32) -> Self {
211 let mut r = MaybeUninit::uninit();
212 intrinsics::signed::irol3(&mut r, &self, n);
213 unsafe { r.assume_init() }
214 }
215
216 /// Shifts the bits to the right by a specified amount, `n`,
217 /// wrapping the truncated bits to the beginning of the resulting
218 /// integer.
219 ///
220 /// Please note this isn't the same operation as the `>>` shifting operator!
221 ///
222 /// # Examples
223 ///
224 /// Basic usage:
225 ///
226 /// ```
227 /// # use ethnum::I256;
228 /// let n = I256::new(0x4f7613f4);
229 /// let m = I256::from_words(
230 /// 0x13f40000000000000000000000000000,
231 /// 0x00000000000000000000000000004f76,
232 /// );
233 ///
234 /// assert_eq!(n.rotate_right(16), m);
235 /// ```
236 #[must_use = "this returns the result of the operation, \
237 without modifying the original"]
238 #[inline(always)]
239 pub fn rotate_right(self, n: u32) -> Self {
240 let mut r = MaybeUninit::uninit();
241 intrinsics::signed::iror3(&mut r, &self, n);
242 unsafe { r.assume_init() }
243 }
244
245 /// Reverses the byte order of the integer.
246 ///
247 /// # Examples
248 ///
249 /// Basic usage:
250 ///
251 /// ```
252 /// # use ethnum::I256;
253 /// let n = I256::from_words(
254 /// 0x00010203_04050607_08090a0b_0c0d0e0f,
255 /// 0x10111213_14151617_18191a1b_1c1d1e1f,
256 /// );
257 ///
258 /// assert_eq!(
259 /// n.swap_bytes(),
260 /// I256::from_words(
261 /// 0x1f1e1d1c_1b1a1918_17161514_13121110,
262 /// 0x0f0e0d0c_0b0a0908_07060504_03020100,
263 /// ),
264 /// );
265 /// ```
266 #[inline]
267 pub const fn swap_bytes(self) -> Self {
268 let Self([a, b]) = self;
269 Self([b.swap_bytes(), a.swap_bytes()])
270 }
271
272 /// Reverses the order of bits in the integer. The least significant bit
273 /// becomes the most significant bit, second least-significant bit becomes
274 /// second most-significant bit, etc.
275 ///
276 /// # Examples
277 ///
278 /// Basic usage:
279 ///
280 /// ```
281 /// # use ethnum::I256;
282 /// let n = I256::from_words(
283 /// 0x00010203_04050607_08090a0b_0c0d0e0f,
284 /// 0x10111213_14151617_18191a1b_1c1d1e1f,
285 /// );
286 ///
287 /// assert_eq!(
288 /// n.reverse_bits(),
289 /// I256::from_words(
290 /// 0xf878b838_d8589818_e868a828_c8488808_u128 as _,
291 /// 0xf070b030_d0509010_e060a020_c0408000_u128 as _,
292 /// ),
293 /// );
294 /// ```
295 #[inline]
296 #[must_use]
297 pub const fn reverse_bits(self) -> Self {
298 let Self([a, b]) = self;
299 Self([b.reverse_bits(), a.reverse_bits()])
300 }
301
302 /// Converts an integer from big endian to the target's endianness.
303 ///
304 /// On big endian this is a no-op. On little endian the bytes are swapped.
305 ///
306 /// # Examples
307 ///
308 /// Basic usage:
309 ///
310 /// ```
311 /// # use ethnum::I256;
312 /// let n = I256::new(0x1A);
313 ///
314 /// if cfg!(target_endian = "big") {
315 /// assert_eq!(I256::from_be(n), n)
316 /// } else {
317 /// assert_eq!(I256::from_be(n), n.swap_bytes())
318 /// }
319 /// ```
320 #[inline(always)]
321 pub const fn from_be(x: Self) -> Self {
322 #[cfg(target_endian = "big")]
323 {
324 x
325 }
326 #[cfg(not(target_endian = "big"))]
327 {
328 x.swap_bytes()
329 }
330 }
331
332 /// Converts an integer from little endian to the target's endianness.
333 ///
334 /// On little endian this is a no-op. On big endian the bytes are swapped.
335 ///
336 /// # Examples
337 ///
338 /// Basic usage:
339 ///
340 /// ```
341 /// # use ethnum::I256;
342 /// let n = I256::new(0x1A);
343 ///
344 /// if cfg!(target_endian = "little") {
345 /// assert_eq!(I256::from_le(n), n)
346 /// } else {
347 /// assert_eq!(I256::from_le(n), n.swap_bytes())
348 /// }
349 /// ```
350 #[inline(always)]
351 pub const fn from_le(x: Self) -> Self {
352 #[cfg(target_endian = "little")]
353 {
354 x
355 }
356 #[cfg(not(target_endian = "little"))]
357 {
358 x.swap_bytes()
359 }
360 }
361
362 /// Converts `self` to big endian from the target's endianness.
363 ///
364 /// On big endian this is a no-op. On little endian the bytes are swapped.
365 ///
366 /// # Examples
367 ///
368 /// Basic usage:
369 ///
370 /// ```
371 /// # use ethnum::I256;
372 /// let n = I256::new(0x1A);
373 ///
374 /// if cfg!(target_endian = "big") {
375 /// assert_eq!(n.to_be(), n)
376 /// } else {
377 /// assert_eq!(n.to_be(), n.swap_bytes())
378 /// }
379 /// ```
380 #[inline(always)]
381 pub const fn to_be(self) -> Self {
382 // or not to be?
383 #[cfg(target_endian = "big")]
384 {
385 self
386 }
387 #[cfg(not(target_endian = "big"))]
388 {
389 self.swap_bytes()
390 }
391 }
392
393 /// Converts `self` to little endian from the target's endianness.
394 ///
395 /// On little endian this is a no-op. On big endian the bytes are swapped.
396 ///
397 /// # Examples
398 ///
399 /// Basic usage:
400 ///
401 /// ```
402 /// # use ethnum::I256;
403 /// let n = I256::new(0x1A);
404 ///
405 /// if cfg!(target_endian = "little") {
406 /// assert_eq!(n.to_le(), n)
407 /// } else {
408 /// assert_eq!(n.to_le(), n.swap_bytes())
409 /// }
410 /// ```
411 #[inline(always)]
412 pub const fn to_le(self) -> Self {
413 #[cfg(target_endian = "little")]
414 {
415 self
416 }
417 #[cfg(not(target_endian = "little"))]
418 {
419 self.swap_bytes()
420 }
421 }
422
423 /// Checked integer addition. Computes `self + rhs`, returning `None`
424 /// if overflow occurred.
425 ///
426 /// # Examples
427 ///
428 /// Basic usage:
429 ///
430 /// ```
431 /// # use ethnum::I256;
432 /// assert_eq!((I256::MAX - 2).checked_add(I256::new(1)), Some(I256::MAX - 1));
433 /// assert_eq!((I256::MAX - 2).checked_add(I256::new(3)), None);
434 /// ```
435 #[must_use = "this returns the result of the operation, \
436 without modifying the original"]
437 #[inline]
438 pub fn checked_add(self, rhs: Self) -> Option<Self> {
439 let (a, b) = self.overflowing_add(rhs);
440 if b {
441 None
442 } else {
443 Some(a)
444 }
445 }
446
447 /// Checked addition with an unsigned integer. Computes `self + rhs`,
448 /// returning `None` if overflow occurred.
449 ///
450 /// # Examples
451 ///
452 /// Basic usage:
453 ///
454 /// ```
455 /// # use ethnum::{I256, U256};
456 /// assert_eq!(I256::new(1).checked_add_unsigned(U256::new(2)), Some(I256::new(3)));
457 /// assert_eq!((I256::MAX - 2).checked_add_unsigned(U256::new(3)), None);
458 /// ```
459 #[must_use = "this returns the result of the operation, \
460 without modifying the original"]
461 #[inline]
462 pub fn checked_add_unsigned(self, rhs: U256) -> Option<Self> {
463 let (a, b) = self.overflowing_add_unsigned(rhs);
464 if b {
465 None
466 } else {
467 Some(a)
468 }
469 }
470
471 /// Checked integer subtraction. Computes `self - rhs`, returning `None` if
472 /// overflow occurred.
473 ///
474 /// # Examples
475 ///
476 /// Basic usage:
477 ///
478 /// ```
479 /// # use ethnum::I256;
480 /// assert_eq!((I256::MIN + 2).checked_sub(I256::new(1)), Some(I256::MIN + 1));
481 /// assert_eq!((I256::MIN + 2).checked_sub(I256::new(3)), None);
482 /// ```
483 #[must_use = "this returns the result of the operation, \
484 without modifying the original"]
485 #[inline]
486 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
487 let (a, b) = self.overflowing_sub(rhs);
488 if b {
489 None
490 } else {
491 Some(a)
492 }
493 }
494
495 /// Checked subtraction with an unsigned integer. Computes `self - rhs`,
496 /// returning `None` if overflow occurred.
497 ///
498 /// # Examples
499 ///
500 /// Basic usage:
501 ///
502 /// ```
503 /// # use ethnum::{I256, U256};
504 /// assert_eq!(I256::new(1).checked_sub_unsigned(U256::new(2)), Some(I256::new(-1)));
505 /// assert_eq!((I256::MIN + 2).checked_sub_unsigned(U256::new(3)), None);
506 /// ```
507 #[must_use = "this returns the result of the operation, \
508 without modifying the original"]
509 #[inline]
510 pub fn checked_sub_unsigned(self, rhs: U256) -> Option<Self> {
511 let (a, b) = self.overflowing_sub_unsigned(rhs);
512 if b {
513 None
514 } else {
515 Some(a)
516 }
517 }
518
519 /// Checked integer multiplication. Computes `self * rhs`, returning `None`
520 /// if overflow occurred.
521 ///
522 /// # Examples
523 ///
524 /// Basic usage:
525 ///
526 /// ```
527 /// # use ethnum::I256;
528 /// assert_eq!(I256::MAX.checked_mul(I256::new(1)), Some(I256::MAX));
529 /// assert_eq!(I256::MAX.checked_mul(I256::new(2)), None);
530 /// ```
531 #[must_use = "this returns the result of the operation, \
532 without modifying the original"]
533 #[inline]
534 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
535 let (a, b) = self.overflowing_mul(rhs);
536 if b {
537 None
538 } else {
539 Some(a)
540 }
541 }
542
543 /// Checked integer division. Computes `self / rhs`, returning `None` if
544 /// `rhs == 0` or the division results in overflow.
545 ///
546 /// # Examples
547 ///
548 /// Basic usage:
549 ///
550 /// ```
551 /// # use ethnum::I256;
552 /// assert_eq!((I256::MIN + 1).checked_div(I256::new(-1)), Some(I256::MAX));
553 /// assert_eq!(I256::MIN.checked_div(I256::new(-1)), None);
554 /// assert_eq!(I256::new(1).checked_div(I256::new(0)), None);
555 /// ```
556 #[must_use = "this returns the result of the operation, \
557 without modifying the original"]
558 #[inline]
559 pub fn checked_div(self, rhs: Self) -> Option<Self> {
560 if rhs == 0 || (self == Self::MIN && rhs == -1) {
561 None
562 } else {
563 let mut result = MaybeUninit::uninit();
564 intrinsics::signed::idiv3(&mut result, &self, &rhs);
565 Some(unsafe { result.assume_init() })
566 }
567 }
568
569 /// Checked Euclidean division. Computes `self.div_euclid(rhs)`,
570 /// returning `None` if `rhs == 0` or the division results in overflow.
571 ///
572 /// # Examples
573 ///
574 /// Basic usage:
575 ///
576 /// ```
577 /// # use ethnum::I256;
578 /// assert_eq!((I256::MIN + 1).checked_div_euclid(I256::new(-1)), Some(I256::MAX));
579 /// assert_eq!(I256::MIN.checked_div_euclid(I256::new(-1)), None);
580 /// assert_eq!(I256::new(1).checked_div_euclid(I256::new(0)), None);
581 /// ```
582 #[must_use = "this returns the result of the operation, \
583 without modifying the original"]
584 #[inline]
585 pub fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
586 if rhs == 0 || (self == Self::MIN && rhs == -1) {
587 None
588 } else {
589 Some(self.div_euclid(rhs))
590 }
591 }
592
593 /// Checked integer remainder. Computes `self % rhs`, returning `None` if
594 /// `rhs == 0` or the division results in overflow.
595 ///
596 /// # Examples
597 ///
598 /// Basic usage:
599 ///
600 /// ```
601 /// # use ethnum::I256;
602 /// assert_eq!(I256::new(5).checked_rem(I256::new(2)), Some(I256::new(1)));
603 /// assert_eq!(I256::new(5).checked_rem(I256::new(0)), None);
604 /// assert_eq!(I256::MIN.checked_rem(I256::new(-1)), None);
605 /// ```
606 #[must_use = "this returns the result of the operation, \
607 without modifying the original"]
608 #[inline]
609 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
610 if rhs == 0 || (self == Self::MIN && rhs == -1) {
611 None
612 } else {
613 let mut result = MaybeUninit::uninit();
614 intrinsics::signed::irem3(&mut result, &self, &rhs);
615 Some(unsafe { result.assume_init() })
616 }
617 }
618
619 /// Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning
620 /// `None` if `rhs == 0` or the division results in overflow.
621 ///
622 /// # Examples
623 ///
624 /// Basic usage:
625 ///
626 /// ```
627 /// # use ethnum::I256;
628 /// assert_eq!(I256::new(5).checked_rem_euclid(I256::new(2)), Some(I256::new(1)));
629 /// assert_eq!(I256::new(5).checked_rem_euclid(I256::new(0)), None);
630 /// assert_eq!(I256::MIN.checked_rem_euclid(I256::new(-1)), None);
631 /// ```
632 #[must_use = "this returns the result of the operation, \
633 without modifying the original"]
634 #[inline]
635 pub fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
636 if rhs == 0 || (self == Self::MIN && rhs == -1) {
637 None
638 } else {
639 Some(self.rem_euclid(rhs))
640 }
641 }
642
643 /// Checked negation. Computes `-self`, returning `None` if `self == MIN`.
644 ///
645 /// # Examples
646 ///
647 /// Basic usage:
648 ///
649 /// ```
650 /// # use ethnum::I256;
651 /// assert_eq!(I256::new(5).checked_neg(), Some(I256::new(-5)));
652 /// assert_eq!(I256::MIN.checked_neg(), None);
653 /// ```
654 #[inline]
655 pub fn checked_neg(self) -> Option<Self> {
656 let (a, b) = self.overflowing_neg();
657 if b {
658 None
659 } else {
660 Some(a)
661 }
662 }
663
664 /// Checked shift left. Computes `self << rhs`, returning `None` if `rhs`
665 /// is larger than or equal to the number of bits in `self`.
666 ///
667 /// # Examples
668 ///
669 /// Basic usage:
670 ///
671 /// ```
672 /// # use ethnum::I256;
673 /// assert_eq!(I256::new(0x1).checked_shl(4), Some(I256::new(0x10)));
674 /// assert_eq!(I256::new(0x1).checked_shl(257), None);
675 /// ```
676 #[must_use = "this returns the result of the operation, \
677 without modifying the original"]
678 #[inline]
679 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
680 let (a, b) = self.overflowing_shl(rhs);
681 if b {
682 None
683 } else {
684 Some(a)
685 }
686 }
687
688 /// Checked shift right. Computes `self >> rhs`, returning `None` if `rhs`
689 /// is larger than or equal to the number of bits in `self`.
690 ///
691 /// # Examples
692 ///
693 /// Basic usage:
694 ///
695 /// ```
696 /// # use ethnum::I256;
697 /// assert_eq!(I256::new(0x10).checked_shr(4), Some(I256::new(0x1)));
698 /// assert_eq!(I256::new(0x10).checked_shr(256), None);
699 /// ```
700 #[must_use = "this returns the result of the operation, \
701 without modifying the original"]
702 #[inline]
703 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
704 let (a, b) = self.overflowing_shr(rhs);
705 if b {
706 None
707 } else {
708 Some(a)
709 }
710 }
711
712 /// Checked absolute value. Computes `self.abs()`, returning `None` if
713 /// `self == MIN`.
714 ///
715 /// # Examples
716 ///
717 /// Basic usage:
718 ///
719 /// ```
720 /// # use ethnum::I256;
721 /// assert_eq!(I256::new(-5).checked_abs(), Some(I256::new(5)));
722 /// assert_eq!(I256::MIN.checked_abs(), None);
723 /// ```
724 #[inline]
725 pub fn checked_abs(self) -> Option<Self> {
726 if self.is_negative() {
727 self.checked_neg()
728 } else {
729 Some(self)
730 }
731 }
732
733 /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
734 /// overflow occurred.
735 ///
736 /// # Examples
737 ///
738 /// Basic usage:
739 ///
740 /// ```
741 /// # use ethnum::I256;
742 /// assert_eq!(I256::new(8).checked_pow(2), Some(I256::new(64)));
743 /// assert_eq!(I256::MAX.checked_pow(2), None);
744 /// ```
745 #[must_use = "this returns the result of the operation, \
746 without modifying the original"]
747 #[inline]
748 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
749 if exp == 0 {
750 return Some(Self::ONE);
751 }
752 let mut base = self;
753 let mut acc = Self::ONE;
754
755 while exp > 1 {
756 if (exp & 1) == 1 {
757 acc = acc.checked_mul(base)?;
758 }
759 exp /= 2;
760 base = base.checked_mul(base)?;
761 }
762 // since exp!=0, finally the exp must be 1.
763 // Deal with the final bit of the exponent separately, since
764 // squaring the base afterwards is not necessary and may cause a
765 // needless overflow.
766 acc.checked_mul(base)
767 }
768
769 /// Saturating integer addition. Computes `self + rhs`, saturating at the
770 /// numeric bounds instead of overflowing.
771 ///
772 /// # Examples
773 ///
774 /// Basic usage:
775 ///
776 /// ```
777 /// # use ethnum::I256;
778 /// assert_eq!(I256::new(100).saturating_add(I256::new(1)), 101);
779 /// assert_eq!(I256::MAX.saturating_add(I256::new(100)), I256::MAX);
780 /// assert_eq!(I256::MIN.saturating_add(I256::new(-1)), I256::MIN);
781 /// ```
782 #[must_use = "this returns the result of the operation, \
783 without modifying the original"]
784 #[inline]
785 pub fn saturating_add(self, rhs: Self) -> Self {
786 match self.checked_add(rhs) {
787 Some(x) => x,
788 None => {
789 if rhs > 0 {
790 Self::MAX
791 } else {
792 Self::MIN
793 }
794 }
795 }
796 }
797
798 /// Saturating addition with an unsigned integer. Computes `self + rhs`,
799 /// saturating at the numeric bounds instead of overflowing.
800 ///
801 /// # Examples
802 ///
803 /// Basic usage:
804 ///
805 /// ```
806 /// # use ethnum::{I256, U256};
807 /// assert_eq!(I256::new(1).saturating_add_unsigned(U256::new(2)), 3);
808 /// assert_eq!(I256::MAX.saturating_add_unsigned(U256::new(100)), I256::MAX);
809 /// ```
810 #[must_use = "this returns the result of the operation, \
811 without modifying the original"]
812 #[inline]
813 pub fn saturating_add_unsigned(self, rhs: U256) -> Self {
814 // Overflow can only happen at the upper bound
815 match self.checked_add_unsigned(rhs) {
816 Some(x) => x,
817 None => Self::MAX,
818 }
819 }
820
821 /// Saturating integer subtraction. Computes `self - rhs`, saturating at the
822 /// numeric bounds instead of overflowing.
823 ///
824 /// # Examples
825 ///
826 /// Basic usage:
827 ///
828 /// ```
829 /// # use ethnum::I256;
830 /// assert_eq!(I256::new(100).saturating_sub(I256::new(127)), -27);
831 /// assert_eq!(I256::MIN.saturating_sub(I256::new(100)), I256::MIN);
832 /// assert_eq!(I256::MAX.saturating_sub(I256::new(-1)), I256::MAX);
833 /// ```
834 #[must_use = "this returns the result of the operation, \
835 without modifying the original"]
836 #[inline]
837 pub fn saturating_sub(self, rhs: Self) -> Self {
838 match self.checked_sub(rhs) {
839 Some(x) => x,
840 None => {
841 if rhs > 0 {
842 Self::MIN
843 } else {
844 Self::MAX
845 }
846 }
847 }
848 }
849
850 /// Saturating subtraction with an unsigned integer. Computes `self - rhs`,
851 /// saturating at the numeric bounds instead of overflowing.
852 ///
853 /// # Examples
854 ///
855 /// Basic usage:
856 ///
857 /// ```
858 /// # use ethnum::{I256, U256};
859 /// assert_eq!(I256::new(100).saturating_sub_unsigned(U256::new(127)), -27);
860 /// assert_eq!(I256::MIN.saturating_sub_unsigned(U256::new(100)), I256::MIN);
861 /// ```
862 #[must_use = "this returns the result of the operation, \
863 without modifying the original"]
864 #[inline]
865 pub fn saturating_sub_unsigned(self, rhs: U256) -> Self {
866 // Overflow can only happen at the lower bound
867 match self.checked_sub_unsigned(rhs) {
868 Some(x) => x,
869 None => Self::MIN,
870 }
871 }
872
873 /// Saturating integer negation. Computes `-self`, returning `MAX` if
874 /// `self == MIN` instead of overflowing.
875 ///
876 /// # Examples
877 ///
878 /// Basic usage:
879 ///
880 /// ```
881 /// # use ethnum::I256;
882 /// assert_eq!(I256::new(100).saturating_neg(), -100);
883 /// assert_eq!(I256::new(-100).saturating_neg(), 100);
884 /// assert_eq!(I256::MIN.saturating_neg(), I256::MAX);
885 /// assert_eq!(I256::MAX.saturating_neg(), I256::MIN + 1);
886 /// ```
887 #[inline(always)]
888 pub fn saturating_neg(self) -> Self {
889 I256::ZERO.saturating_sub(self)
890 }
891
892 /// Saturating absolute value. Computes `self.abs()`, returning `MAX` if
893 /// `self == MIN` instead of overflowing.
894 ///
895 /// # Examples
896 ///
897 /// Basic usage:
898 ///
899 /// ```
900 /// # use ethnum::I256;
901 /// assert_eq!(I256::new(100).saturating_abs(), 100);
902 /// assert_eq!(I256::new(-100).saturating_abs(), 100);
903 /// assert_eq!(I256::MIN.saturating_abs(), I256::MAX);
904 /// assert_eq!((I256::MIN + 1).saturating_abs(), I256::MAX);
905 /// ```
906 #[inline]
907 pub fn saturating_abs(self) -> Self {
908 if self.is_negative() {
909 self.saturating_neg()
910 } else {
911 self
912 }
913 }
914
915 /// Saturating integer multiplication. Computes `self * rhs`, saturating at
916 /// the numeric bounds instead of overflowing.
917 ///
918 /// # Examples
919 ///
920 /// Basic usage:
921 ///
922 /// ```
923 /// # use ethnum::I256;
924 /// assert_eq!(I256::new(10).saturating_mul(I256::new(12)), 120);
925 /// assert_eq!(I256::MAX.saturating_mul(I256::new(10)), I256::MAX);
926 /// assert_eq!(I256::MIN.saturating_mul(I256::new(10)), I256::MIN);
927 /// ```
928 #[must_use = "this returns the result of the operation, \
929 without modifying the original"]
930 #[inline]
931 pub fn saturating_mul(self, rhs: Self) -> Self {
932 match self.checked_mul(rhs) {
933 Some(x) => x,
934 None => {
935 if (self < 0) == (rhs < 0) {
936 Self::MAX
937 } else {
938 Self::MIN
939 }
940 }
941 }
942 }
943
944 /// Saturating integer division. Computes `self / rhs`, saturating at the
945 /// numeric bounds instead of overflowing.
946 ///
947 /// # Examples
948 ///
949 /// Basic usage:
950 ///
951 /// ```
952 /// # use ethnum::I256;
953 /// assert_eq!(I256::new(5).saturating_div(I256::new(2)), 2);
954 /// assert_eq!(I256::MAX.saturating_div(I256::new(-1)), I256::MIN + 1);
955 /// assert_eq!(I256::MIN.saturating_div(I256::new(-1)), I256::MAX);
956 /// ```
957 ///
958 /// ```should_panic
959 /// # use ethnum::I256;;
960 /// let _ = I256::new(1).saturating_div(I256::new(0));
961 /// ```
962 #[must_use = "this returns the result of the operation, \
963 without modifying the original"]
964 #[inline]
965 pub fn saturating_div(self, rhs: Self) -> Self {
966 match self.overflowing_div(rhs) {
967 (result, false) => result,
968 (_result, true) => Self::MAX, // MIN / -1 is the only possible saturating overflow
969 }
970 }
971
972 /// Saturating integer exponentiation. Computes `self.pow(exp)`,
973 /// saturating at the numeric bounds instead of overflowing.
974 ///
975 /// # Examples
976 ///
977 /// Basic usage:
978 ///
979 /// ```
980 /// # use ethnum::I256;
981 /// assert_eq!(I256::new(-4).saturating_pow(3), -64);
982 /// assert_eq!(I256::MIN.saturating_pow(2), I256::MAX);
983 /// assert_eq!(I256::MIN.saturating_pow(3), I256::MIN);
984 /// ```
985 #[must_use = "this returns the result of the operation, \
986 without modifying the original"]
987 #[inline]
988 pub fn saturating_pow(self, exp: u32) -> Self {
989 match self.checked_pow(exp) {
990 Some(x) => x,
991 None if self < 0 && exp % 2 == 1 => Self::MIN,
992 None => Self::MAX,
993 }
994 }
995
996 /// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at
997 /// the boundary of the type.
998 ///
999 /// # Examples
1000 ///
1001 /// Basic usage:
1002 ///
1003 /// ```
1004 /// # use ethnum::I256;
1005 /// assert_eq!(I256::new(100).wrapping_add(I256::new(27)), 127);
1006 /// assert_eq!(I256::MAX.wrapping_add(I256::new(2)), I256::MIN + 1);
1007 /// ```
1008 #[must_use = "this returns the result of the operation, \
1009 without modifying the original"]
1010 #[inline(always)]
1011 pub fn wrapping_add(self, rhs: Self) -> Self {
1012 let mut result = MaybeUninit::uninit();
1013 intrinsics::signed::iadd3(&mut result, &self, &rhs);
1014 unsafe { result.assume_init() }
1015 }
1016
1017 /// Wrapping (modular) addition with an unsigned integer. Computes
1018 /// `self + rhs`, wrapping around at the boundary of the type.
1019 ///
1020 /// # Examples
1021 ///
1022 /// Basic usage:
1023 ///
1024 /// ```
1025 /// # use ethnum::{I256, U256};
1026 /// assert_eq!(I256::new(100).wrapping_add_unsigned(U256::new(27)), 127);
1027 /// assert_eq!(I256::MAX.wrapping_add_unsigned(U256::new(2)), I256::MIN + 1);
1028 /// ```
1029 #[must_use = "this returns the result of the operation, \
1030 without modifying the original"]
1031 #[inline(always)]
1032 pub fn wrapping_add_unsigned(self, rhs: U256) -> Self {
1033 self.wrapping_add(rhs.as_i256())
1034 }
1035
1036 /// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around
1037 /// at the boundary of the type.
1038 ///
1039 /// # Examples
1040 ///
1041 /// Basic usage:
1042 ///
1043 /// ```
1044 /// # use ethnum::I256;
1045 /// assert_eq!(I256::new(0).wrapping_sub(I256::new(127)), -127);
1046 /// assert_eq!(I256::new(-2).wrapping_sub(I256::MAX), I256::MAX);
1047 /// ```
1048 #[must_use = "this returns the result of the operation, \
1049 without modifying the original"]
1050 #[inline(always)]
1051 pub fn wrapping_sub(self, rhs: Self) -> Self {
1052 let mut result = MaybeUninit::uninit();
1053 intrinsics::signed::isub3(&mut result, &self, &rhs);
1054 unsafe { result.assume_init() }
1055 }
1056
1057 /// Wrapping (modular) subtraction with an unsigned integer. Computes
1058 /// `self - rhs`, wrapping around at the boundary of the type.
1059 ///
1060 /// # Examples
1061 ///
1062 /// Basic usage:
1063 ///
1064 /// ```
1065 /// # use ethnum::{I256, U256};
1066 /// assert_eq!(I256::new(0).wrapping_sub_unsigned(U256::new(127)), -127);
1067 /// assert_eq!(I256::new(-2).wrapping_sub_unsigned(U256::MAX), -1);
1068 /// ```
1069 #[must_use = "this returns the result of the operation, \
1070 without modifying the original"]
1071 #[inline(always)]
1072 pub fn wrapping_sub_unsigned(self, rhs: U256) -> Self {
1073 self.wrapping_sub(rhs.as_i256())
1074 }
1075
1076 /// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping
1077 /// around at the boundary of the type.
1078 ///
1079 /// # Examples
1080 ///
1081 /// Basic usage:
1082 ///
1083 /// ```
1084 /// # use ethnum::I256;
1085 /// assert_eq!(I256::new(10).wrapping_mul(I256::new(12)), 120);
1086 /// assert_eq!(I256::MAX.wrapping_mul(I256::new(2)), -2);
1087 /// ```
1088 #[must_use = "this returns the result of the operation, \
1089 without modifying the original"]
1090 #[inline(always)]
1091 pub fn wrapping_mul(self, rhs: Self) -> Self {
1092 let mut result = MaybeUninit::uninit();
1093 intrinsics::signed::imul3(&mut result, &self, &rhs);
1094 unsafe { result.assume_init() }
1095 }
1096
1097 /// Wrapping (modular) division. Computes `self / rhs`, wrapping around at
1098 /// the boundary of the type.
1099 ///
1100 /// The only case where such wrapping can occur is when one divides
1101 /// `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1102 /// for the type); this is equivalent to `-MIN`, a positive value that is
1103 /// too large to represent in the type. In such a case, this function
1104 /// returns `MIN` itself.
1105 ///
1106 /// # Panics
1107 ///
1108 /// This function will panic if `rhs` is 0.
1109 ///
1110 /// # Examples
1111 ///
1112 /// Basic usage:
1113 ///
1114 /// ```
1115 /// # use ethnum::I256;
1116 /// assert_eq!(I256::new(100).wrapping_div(I256::new(10)), 10);
1117 /// assert_eq!(I256::MIN.wrapping_div(I256::new(-1)), I256::MIN);
1118 /// ```
1119 #[must_use = "this returns the result of the operation, \
1120 without modifying the original"]
1121 #[inline]
1122 pub fn wrapping_div(self, rhs: Self) -> Self {
1123 self.overflowing_div(rhs).0
1124 }
1125
1126 /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
1127 /// wrapping around at the boundary of the type.
1128 ///
1129 /// Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is
1130 /// the negative minimal value for the type). This is equivalent to `-MIN`,
1131 /// a positive value that is too large to represent in the type. In this
1132 /// case, this method returns `MIN` itself.
1133 ///
1134 /// # Panics
1135 ///
1136 /// This function will panic if `rhs` is 0.
1137 ///
1138 /// # Examples
1139 ///
1140 /// Basic usage:
1141 ///
1142 /// ```
1143 /// # use ethnum::I256;
1144 /// assert_eq!(I256::new(100).wrapping_div_euclid(I256::new(10)), 10);
1145 /// assert_eq!(I256::MIN.wrapping_div_euclid(I256::new(-1)), I256::MIN);
1146 /// ```
1147 #[must_use = "this returns the result of the operation, \
1148 without modifying the original"]
1149 #[inline]
1150 pub fn wrapping_div_euclid(self, rhs: Self) -> Self {
1151 self.overflowing_div_euclid(rhs).0
1152 }
1153
1154 /// Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at
1155 /// the boundary of the type.
1156 ///
1157 /// Such wrap-around never actually occurs mathematically; implementation
1158 /// artifacts make `x % y` invalid for `MIN / -1` on a signed type (where
1159 /// MIN` is the negative minimal value). In such a case, this function
1160 /// returns `0`.
1161 ///
1162 /// # Panics
1163 ///
1164 /// This function will panic if `rhs` is 0.
1165 ///
1166 /// # Examples
1167 ///
1168 /// Basic usage:
1169 ///
1170 /// ```
1171 /// # use ethnum::I256;
1172 /// assert_eq!(I256::new(100).wrapping_rem(I256::new(10)), 0);
1173 /// assert_eq!(I256::MIN.wrapping_rem(I256::new(-1)), 0);
1174 /// ```
1175 #[must_use = "this returns the result of the operation, \
1176 without modifying the original"]
1177 #[inline]
1178 pub fn wrapping_rem(self, rhs: Self) -> Self {
1179 self.overflowing_rem(rhs).0
1180 }
1181
1182 /// Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping
1183 /// around at the boundary of the type.
1184 ///
1185 /// Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is
1186 /// the negative minimal value for the type). In this case, this method
1187 /// returns 0.
1188 ///
1189 /// # Panics
1190 ///
1191 /// This function will panic if `rhs` is 0.
1192 ///
1193 /// # Examples
1194 ///
1195 /// Basic usage:
1196 ///
1197 /// ```
1198 /// # use ethnum::I256;
1199 /// assert_eq!(I256::new(100).wrapping_rem_euclid(I256::new(10)), 0);
1200 /// assert_eq!(I256::MIN.wrapping_rem_euclid(I256::new(-1)), 0);
1201 /// ```
1202 #[must_use = "this returns the result of the operation, \
1203 without modifying the original"]
1204 #[inline]
1205 pub fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1206 self.overflowing_rem_euclid(rhs).0
1207 }
1208
1209 /// Wrapping (modular) negation. Computes `-self`, wrapping around at the
1210 /// boundary of the type.
1211 ///
1212 /// The only case where such wrapping can occur is when one negates `MIN` on
1213 /// a signed type (where `MIN` is the negative minimal value for the type);
1214 /// this is a positive value that is too large to represent in the type. In
1215 /// such a case, this function returns `MIN` itself.
1216 ///
1217 /// # Examples
1218 ///
1219 /// Basic usage:
1220 ///
1221 /// ```
1222 /// # use ethnum::I256;
1223 /// assert_eq!(I256::new(100).wrapping_neg(), -100);
1224 /// assert_eq!(I256::MIN.wrapping_neg(), I256::MIN);
1225 /// ```
1226 #[inline(always)]
1227 pub fn wrapping_neg(self) -> Self {
1228 Self::ZERO.wrapping_sub(self)
1229 }
1230
1231 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask`
1232 /// removes any high-order bits of `rhs` that would cause the shift to
1233 /// exceed the bitwidth of the type.
1234 ///
1235 /// Note that this is *not* the same as a rotate-left; the RHS of a wrapping
1236 /// shift-left is restricted to the range of the type, rather than the bits
1237 /// shifted out of the LHS being returned to the other end. The primitive
1238 /// integer types all implement a [`rotate_left`](Self::rotate_left)
1239 /// function, which may be what you want instead.
1240 ///
1241 /// # Examples
1242 ///
1243 /// Basic usage:
1244 ///
1245 /// ```
1246 /// # use ethnum::I256;
1247 /// assert_eq!(I256::new(-1).wrapping_shl(7), -128);
1248 /// assert_eq!(I256::new(-1).wrapping_shl(128), I256::from_words(-1, 0));
1249 /// assert_eq!(I256::new(-1).wrapping_shl(256), -1);
1250 /// ```
1251 #[must_use = "this returns the result of the operation, \
1252 without modifying the original"]
1253 #[inline(always)]
1254 pub fn wrapping_shl(self, rhs: u32) -> Self {
1255 let mut result = MaybeUninit::uninit();
1256 intrinsics::signed::ishl3(&mut result, &self, rhs & 0xff);
1257 unsafe { result.assume_init() }
1258 }
1259
1260 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1261 /// removes any high-order bits of `rhs` that would cause the shift to
1262 /// exceed the bitwidth of the type.
1263 ///
1264 /// Note that this is *not* the same as a rotate-right; the RHS of a
1265 /// wrapping shift-right is restricted to the range of the type, rather than
1266 /// the bits shifted out of the LHS being returned to the other end. The
1267 /// primitive integer types all implement a
1268 /// [`rotate_right`](Self::rotate_right) function, which may be what you
1269 /// want instead.
1270 ///
1271 /// # Examples
1272 ///
1273 /// Basic usage:
1274 ///
1275 /// ```
1276 /// # use ethnum::I256;
1277 /// assert_eq!(I256::new(-128).wrapping_shr(7), -1);
1278 /// assert_eq!((-128i16).wrapping_shr(64), -128);
1279 /// ```
1280 #[must_use = "this returns the result of the operation, \
1281 without modifying the original"]
1282 #[inline(always)]
1283 pub fn wrapping_shr(self, rhs: u32) -> Self {
1284 let mut result = MaybeUninit::uninit();
1285 intrinsics::signed::isar3(&mut result, &self, rhs & 0xff);
1286 unsafe { result.assume_init() }
1287 }
1288
1289 /// Wrapping (modular) absolute value. Computes `self.abs()`, wrapping
1290 /// around at the boundary of the type.
1291 ///
1292 /// The only case where such wrapping can occur is when one takes the
1293 /// absolute value of the negative minimal value for the type; this is a
1294 /// positive value that is too large to represent in the type. In such a
1295 /// case, this function returns `MIN` itself.
1296 ///
1297 /// # Examples
1298 ///
1299 /// Basic usage:
1300 ///
1301 /// ```
1302 /// # use ethnum::{I256, U256};
1303 /// assert_eq!(I256::new(100).wrapping_abs(), 100);
1304 /// assert_eq!(I256::new(-100).wrapping_abs(), 100);
1305 /// assert_eq!(I256::MIN.wrapping_abs(), I256::MIN);
1306 /// assert_eq!(
1307 /// I256::MIN.wrapping_abs().as_u256(),
1308 /// U256::from_words(
1309 /// 0x80000000000000000000000000000000,
1310 /// 0x00000000000000000000000000000000,
1311 /// ),
1312 /// );
1313 /// ```
1314 #[allow(unused_attributes)]
1315 #[inline]
1316 pub fn wrapping_abs(self) -> Self {
1317 if self.is_negative() {
1318 self.wrapping_neg()
1319 } else {
1320 self
1321 }
1322 }
1323
1324 /// Computes the absolute value of `self` without any wrapping
1325 /// or panicking.
1326 ///
1327 ///
1328 /// # Examples
1329 ///
1330 /// Basic usage:
1331 ///
1332 /// ```
1333 /// # use ethnum::{I256, U256};
1334 /// assert_eq!(I256::new(100).unsigned_abs(), 100);
1335 /// assert_eq!(I256::new(-100).unsigned_abs(), 100);
1336 /// assert_eq!(
1337 /// I256::MIN.unsigned_abs(),
1338 /// U256::from_words(
1339 /// 0x80000000000000000000000000000000,
1340 /// 0x00000000000000000000000000000000,
1341 /// ),
1342 /// );
1343 /// ```
1344 #[inline(always)]
1345 pub fn unsigned_abs(self) -> U256 {
1346 self.wrapping_abs().as_u256()
1347 }
1348
1349 /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1350 /// wrapping around at the boundary of the type.
1351 ///
1352 /// # Examples
1353 ///
1354 /// Basic usage:
1355 ///
1356 /// ```
1357 /// # use ethnum::I256;
1358 /// assert_eq!(I256::new(3).wrapping_pow(4), 81);
1359 /// assert_eq!(3i8.wrapping_pow(5), -13);
1360 /// assert_eq!(3i8.wrapping_pow(6), -39);
1361 /// ```
1362 #[must_use = "this returns the result of the operation, \
1363 without modifying the original"]
1364 #[inline]
1365 pub fn wrapping_pow(self, mut exp: u32) -> Self {
1366 if exp == 0 {
1367 return Self::ONE;
1368 }
1369 let mut base = self;
1370 let mut acc = Self::ONE;
1371
1372 while exp > 1 {
1373 if (exp & 1) == 1 {
1374 acc = acc.wrapping_mul(base);
1375 }
1376 exp /= 2;
1377 base = base.wrapping_mul(base);
1378 }
1379
1380 // since exp!=0, finally the exp must be 1.
1381 // Deal with the final bit of the exponent separately, since
1382 // squaring the base afterwards is not necessary and may cause a
1383 // needless overflow.
1384 acc.wrapping_mul(base)
1385 }
1386
1387 /// Calculates `self` + `rhs`
1388 ///
1389 /// Returns a tuple of the addition along with a boolean indicating whether
1390 /// an arithmetic overflow would occur. If an overflow would have occurred
1391 /// then the wrapped value is returned.
1392 ///
1393 /// # Examples
1394 ///
1395 /// Basic usage:
1396 ///
1397 /// ```
1398 /// # use ethnum::I256;
1399 /// assert_eq!(I256::new(5).overflowing_add(I256::new(2)), (I256::new(7), false));
1400 /// assert_eq!(I256::MAX.overflowing_add(I256::new(1)), (I256::MIN, true));
1401 /// ```
1402 #[must_use = "this returns the result of the operation, \
1403 without modifying the original"]
1404 #[inline(always)]
1405 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1406 let mut result = MaybeUninit::uninit();
1407 let overflow = intrinsics::signed::iaddc(&mut result, &self, &rhs);
1408 (unsafe { result.assume_init() }, overflow)
1409 }
1410
1411 /// Calculates `self` + `rhs` with an unsigned `rhs`
1412 ///
1413 /// Returns a tuple of the addition along with a boolean indicating
1414 /// whether an arithmetic overflow would occur. If an overflow would
1415 /// have occurred then the wrapped value is returned.
1416 ///
1417 /// # Examples
1418 ///
1419 /// Basic usage:
1420 ///
1421 /// ```
1422 /// # use ethnum::{I256, U256};
1423 /// assert_eq!(I256::new(1).overflowing_add_unsigned(U256::new(2)), (I256::new(3), false));
1424 /// assert_eq!((I256::MIN).overflowing_add_unsigned(U256::MAX), (I256::MAX, false));
1425 /// assert_eq!((I256::MAX - 2).overflowing_add_unsigned(U256::new(3)), (I256::MIN, true));
1426 /// ```
1427 #[must_use = "this returns the result of the operation, \
1428 without modifying the original"]
1429 #[inline]
1430 pub fn overflowing_add_unsigned(self, rhs: U256) -> (Self, bool) {
1431 let rhs = rhs.as_i256();
1432 let (res, overflowed) = self.overflowing_add(rhs);
1433 (res, overflowed ^ (rhs < 0))
1434 }
1435
1436 /// Calculates `self` - `rhs`
1437 ///
1438 /// Returns a tuple of the subtraction along with a boolean indicating
1439 /// whether an arithmetic overflow would occur. If an overflow would have
1440 /// occurred then the wrapped value is returned.
1441 ///
1442 /// # Examples
1443 ///
1444 /// Basic usage:
1445 ///
1446 /// ```
1447 /// # use ethnum::I256;
1448 /// assert_eq!(I256::new(5).overflowing_sub(I256::new(2)), (I256::new(3), false));
1449 /// assert_eq!(I256::MIN.overflowing_sub(I256::new(1)), (I256::MAX, true));
1450 /// ```
1451 #[must_use = "this returns the result of the operation, \
1452 without modifying the original"]
1453 #[inline(always)]
1454 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1455 let mut result = MaybeUninit::uninit();
1456 let overflow = intrinsics::signed::isubc(&mut result, &self, &rhs);
1457 (unsafe { result.assume_init() }, overflow)
1458 }
1459
1460 /// Calculates `self` - `rhs` with an unsigned `rhs`
1461 ///
1462 /// Returns a tuple of the subtraction along with a boolean indicating
1463 /// whether an arithmetic overflow would occur. If an overflow would
1464 /// have occurred then the wrapped value is returned.
1465 ///
1466 /// # Examples
1467 ///
1468 /// Basic usage:
1469 ///
1470 /// ```
1471 /// # use ethnum::{I256, U256};
1472 /// assert_eq!(I256::new(1).overflowing_sub_unsigned(U256::new(2)), (I256::new(-1), false));
1473 /// assert_eq!((I256::MAX).overflowing_sub_unsigned(U256::MAX), (I256::MIN, false));
1474 /// assert_eq!((I256::MIN + 2).overflowing_sub_unsigned(U256::new(3)), (I256::MAX, true));
1475 /// ```
1476 #[must_use = "this returns the result of the operation, \
1477 without modifying the original"]
1478 #[inline]
1479 pub fn overflowing_sub_unsigned(self, rhs: U256) -> (Self, bool) {
1480 let rhs = rhs.as_i256();
1481 let (res, overflowed) = self.overflowing_sub(rhs);
1482 (res, overflowed ^ (rhs < 0))
1483 }
1484
1485 /// Computes the absolute difference between `self` and `other`.
1486 ///
1487 /// This function always returns the correct answer without overflow or
1488 /// panics by returning an unsigned integer.
1489 ///
1490 /// # Examples
1491 ///
1492 /// Basic usage:
1493 ///
1494 /// ```
1495 /// # use ethnum::{I256, U256};
1496 /// assert_eq!(I256::new(100).abs_diff(I256::new(80)), 20);
1497 /// assert_eq!(I256::new(100).abs_diff(I256::new(110)), 10);
1498 /// assert_eq!(I256::new(-100).abs_diff(I256::new(80)), 180);
1499 /// assert_eq!(I256::new(-100).abs_diff(I256::new(-120)), 20);
1500 /// assert_eq!(I256::MIN.abs_diff(I256::MAX), U256::MAX);
1501 /// assert_eq!(I256::MAX.abs_diff(I256::MIN), U256::MAX);
1502 /// ```
1503 #[must_use = "this returns the result of the operation, \
1504 without modifying the original"]
1505 #[inline]
1506 pub fn abs_diff(self, other: Self) -> U256 {
1507 if self < other {
1508 // Converting a non-negative x from signed to unsigned by using
1509 // `x as U` is left unchanged, but a negative x is converted
1510 // to value x + 2^N. Thus if `s` and `o` are binary variables
1511 // respectively indicating whether `self` and `other` are
1512 // negative, we are computing the mathematical value:
1513 //
1514 // (other + o*2^N) - (self + s*2^N) mod 2^N
1515 // other - self + (o-s)*2^N mod 2^N
1516 // other - self mod 2^N
1517 //
1518 // Finally, taking the mod 2^N of the mathematical value of
1519 // `other - self` does not change it as it already is
1520 // in the range [0, 2^N).
1521 other.as_u256().wrapping_sub(self.as_u256())
1522 } else {
1523 self.as_u256().wrapping_sub(other.as_u256())
1524 }
1525 }
1526
1527 /// Calculates the multiplication of `self` and `rhs`.
1528 ///
1529 /// Returns a tuple of the multiplication along with a boolean indicating
1530 /// whether an arithmetic overflow would occur. If an overflow would have
1531 /// occurred then the wrapped value is returned.
1532 ///
1533 /// # Examples
1534 ///
1535 /// Basic usage:
1536 ///
1537 /// ```
1538 /// # use ethnum::I256;
1539 /// assert_eq!(I256::new(5).overflowing_mul(I256::new(2)), (I256::new(10), false));
1540 /// assert_eq!(I256::MAX.overflowing_mul(I256::new(2)), (I256::new(-2), true));
1541 /// ```
1542 #[must_use = "this returns the result of the operation, \
1543 without modifying the original"]
1544 #[inline(always)]
1545 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1546 let mut result = MaybeUninit::uninit();
1547 let overflow = intrinsics::signed::imulc(&mut result, &self, &rhs);
1548 (unsafe { result.assume_init() }, overflow)
1549 }
1550
1551 /// Calculates the divisor when `self` is divided by `rhs`.
1552 ///
1553 /// Returns a tuple of the divisor along with a boolean indicating whether
1554 /// an arithmetic overflow would occur. If an overflow would occur then self
1555 /// is returned.
1556 ///
1557 /// # Panics
1558 ///
1559 /// This function will panic if `rhs` is 0.
1560 ///
1561 /// # Examples
1562 ///
1563 /// Basic usage:
1564 ///
1565 /// ```
1566 /// # use ethnum::I256;
1567 /// assert_eq!(I256::new(5).overflowing_div(I256::new(2)), (I256::new(2), false));
1568 /// assert_eq!(I256::MIN.overflowing_div(I256::new(-1)), (I256::MIN, true));
1569 /// ```
1570 #[inline]
1571 #[must_use = "this returns the result of the operation, \
1572 without modifying the original"]
1573 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1574 if self == Self::MIN && rhs == -1 {
1575 (self, true)
1576 } else {
1577 (self / rhs, false)
1578 }
1579 }
1580
1581 /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1582 ///
1583 /// Returns a tuple of the divisor along with a boolean indicating whether
1584 /// an arithmetic overflow would occur. If an overflow would occur then
1585 /// `self` is returned.
1586 ///
1587 /// # Panics
1588 ///
1589 /// This function will panic if `rhs` is 0.
1590 ///
1591 /// # Examples
1592 ///
1593 /// Basic usage:
1594 ///
1595 /// ```
1596 /// # use ethnum::I256;
1597 /// assert_eq!(I256::new(5).overflowing_div_euclid(I256::new(2)), (I256::new(2), false));
1598 /// assert_eq!(I256::MIN.overflowing_div_euclid(I256::new(-1)), (I256::MIN, true));
1599 /// ```
1600 #[inline]
1601 #[must_use = "this returns the result of the operation, \
1602 without modifying the original"]
1603 pub fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1604 if self == Self::MIN && rhs == -1 {
1605 (self, true)
1606 } else {
1607 (self.div_euclid(rhs), false)
1608 }
1609 }
1610
1611 /// Calculates the remainder when `self` is divided by `rhs`.
1612 ///
1613 /// Returns a tuple of the remainder after dividing along with a boolean
1614 /// indicating whether an arithmetic overflow would occur. If an overflow
1615 /// would occur then 0 is returned.
1616 ///
1617 /// # Panics
1618 ///
1619 /// This function will panic if `rhs` is 0.
1620 ///
1621 /// # Examples
1622 ///
1623 /// Basic usage:
1624 ///
1625 /// ```
1626 /// # use ethnum::I256;
1627 /// assert_eq!(I256::new(5).overflowing_rem(I256::new(2)), (I256::new(1), false));
1628 /// assert_eq!(I256::MIN.overflowing_rem(I256::new(-1)), (I256::new(0), true));
1629 /// ```
1630 #[inline]
1631 #[must_use = "this returns the result of the operation, \
1632 without modifying the original"]
1633 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1634 if self == Self::MIN && rhs == -1 {
1635 (Self::ZERO, true)
1636 } else {
1637 (self % rhs, false)
1638 }
1639 }
1640
1641 /// Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
1642 ///
1643 /// Returns a tuple of the remainder after dividing along with a boolean
1644 /// indicating whether an arithmetic overflow would occur. If an overflow
1645 /// would occur then 0 is returned.
1646 ///
1647 /// # Panics
1648 ///
1649 /// This function will panic if `rhs` is 0.
1650 ///
1651 /// # Examples
1652 ///
1653 /// Basic usage:
1654 ///
1655 /// ```
1656 /// # use ethnum::I256;
1657 /// assert_eq!(I256::new(5).overflowing_rem_euclid(I256::new(2)), (I256::new(1), false));
1658 /// assert_eq!(I256::MIN.overflowing_rem_euclid(I256::new(-1)), (I256::new(0), true));
1659 /// ```
1660 #[must_use = "this returns the result of the operation, \
1661 without modifying the original"]
1662 #[inline]
1663 pub fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1664 if self == Self::MIN && rhs == -1 {
1665 (Self::ZERO, true)
1666 } else {
1667 (self.rem_euclid(rhs), false)
1668 }
1669 }
1670
1671 /// Negates self, overflowing if this is equal to the minimum value.
1672 ///
1673 /// Returns a tuple of the negated version of self along with a boolean
1674 /// indicating whether an overflow happened. If `self` is the minimum value
1675 /// (e.g., `i32::MIN` for values of type `i32`), then the minimum value will
1676 /// be returned again and `true` will be returned for an overflow happening.
1677 ///
1678 /// # Examples
1679 ///
1680 /// Basic usage:
1681 ///
1682 /// ```
1683 /// # use ethnum::I256;
1684 /// assert_eq!(I256::new(2).overflowing_neg(), (I256::new(-2), false));
1685 /// assert_eq!(I256::MIN.overflowing_neg(), (I256::MIN, true));
1686 /// ```
1687 #[inline]
1688 pub fn overflowing_neg(self) -> (Self, bool) {
1689 if self == Self::MIN {
1690 (Self::MIN, true)
1691 } else {
1692 (-self, false)
1693 }
1694 }
1695
1696 /// Shifts self left by `rhs` bits.
1697 ///
1698 /// Returns a tuple of the shifted version of self along with a boolean
1699 /// indicating whether the shift value was larger than or equal to the
1700 /// number of bits. If the shift value is too large, then value is masked
1701 /// (N-1) where N is the number of bits, and this value is then used to
1702 /// perform the shift.
1703 ///
1704 /// # Examples
1705 ///
1706 /// Basic usage:
1707 ///
1708 /// ```
1709 /// # use ethnum::I256;
1710 /// assert_eq!(I256::new(1).overflowing_shl(4), (I256::new(0x10), false));
1711 /// assert_eq!(I256::new(1).overflowing_shl(260), (I256::new(0x10), true));
1712 /// ```
1713 #[must_use = "this returns the result of the operation, \
1714 without modifying the original"]
1715 #[inline]
1716 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1717 (self.wrapping_shl(rhs), (rhs > 255))
1718 }
1719
1720 /// Shifts self right by `rhs` bits.
1721 ///
1722 /// Returns a tuple of the shifted version of self along with a boolean
1723 /// indicating whether the shift value was larger than or equal to the
1724 /// number of bits. If the shift value is too large, then value is masked
1725 /// (N-1) where N is the number of bits, and this value is then used to
1726 /// perform the shift.
1727 ///
1728 /// # Examples
1729 ///
1730 /// Basic usage:
1731 ///
1732 /// ```
1733 /// # use ethnum::I256;
1734 /// assert_eq!(I256::new(0x10).overflowing_shr(4), (I256::new(0x1), false));
1735 /// assert_eq!(I256::new(0x10).overflowing_shr(260), (I256::new(0x1), true));
1736 /// ```
1737 #[must_use = "this returns the result of the operation, \
1738 without modifying the original"]
1739 #[inline]
1740 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1741 (self.wrapping_shr(rhs), (rhs > 255))
1742 }
1743
1744 /// Computes the absolute value of `self`.
1745 ///
1746 /// Returns a tuple of the absolute version of self along with a boolean
1747 /// indicating whether an overflow happened. If self is the minimum value
1748 /// (e.g., I256::MIN for values of type I256), then the minimum value will
1749 /// be returned again and true will be returned for an overflow happening.
1750 ///
1751 /// # Examples
1752 ///
1753 /// Basic usage:
1754 ///
1755 /// ```
1756 /// # use ethnum::I256;
1757 /// assert_eq!(I256::new(10).overflowing_abs(), (I256::new(10), false));
1758 /// assert_eq!(I256::new(-10).overflowing_abs(), (I256::new(10), false));
1759 /// assert_eq!(I256::MIN.overflowing_abs(), (I256::MIN, true));
1760 /// ```
1761 #[inline]
1762 pub fn overflowing_abs(self) -> (Self, bool) {
1763 (self.wrapping_abs(), self == Self::MIN)
1764 }
1765
1766 /// Raises self to the power of `exp`, using exponentiation by squaring.
1767 ///
1768 /// Returns a tuple of the exponentiation along with a bool indicating
1769 /// whether an overflow happened.
1770 ///
1771 /// # Examples
1772 ///
1773 /// Basic usage:
1774 ///
1775 /// ```
1776 /// # use ethnum::I256;
1777 /// assert_eq!(I256::new(3).overflowing_pow(4), (I256::new(81), false));
1778 /// assert_eq!(
1779 /// I256::new(10).overflowing_pow(77),
1780 /// (
1781 /// I256::from_words(
1782 /// -46408779215366586471190473126206792002,
1783 /// -113521875028918879454725857041952276480,
1784 /// ),
1785 /// true,
1786 /// )
1787 /// );
1788 /// ```
1789 #[must_use = "this returns the result of the operation, \
1790 without modifying the original"]
1791 #[inline]
1792 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1793 if exp == 0 {
1794 return (Self::ONE, false);
1795 }
1796 let mut base = self;
1797 let mut acc = Self::ONE;
1798 let mut overflown = false;
1799 // Scratch space for storing results of overflowing_mul.
1800 let mut r;
1801
1802 while exp > 1 {
1803 if (exp & 1) == 1 {
1804 r = acc.overflowing_mul(base);
1805 acc = r.0;
1806 overflown |= r.1;
1807 }
1808 exp /= 2;
1809 r = base.overflowing_mul(base);
1810 base = r.0;
1811 overflown |= r.1;
1812 }
1813
1814 // since exp!=0, finally the exp must be 1.
1815 // Deal with the final bit of the exponent separately, since
1816 // squaring the base afterwards is not necessary and may cause a
1817 // needless overflow.
1818 r = acc.overflowing_mul(base);
1819 r.1 |= overflown;
1820 r
1821 }
1822
1823 /// Raises self to the power of `exp`, using exponentiation by squaring.
1824 ///
1825 /// # Examples
1826 ///
1827 /// Basic usage:
1828 ///
1829 /// ```
1830 /// # use ethnum::I256;
1831 ///
1832 /// assert_eq!(I256::new(2).pow(5), 32);
1833 /// ```
1834 #[must_use = "this returns the result of the operation, \
1835 without modifying the original"]
1836 #[inline]
1837 pub fn pow(self, mut exp: u32) -> Self {
1838 if exp == 0 {
1839 return Self::ONE;
1840 }
1841 let mut base = self;
1842 let mut acc = Self::ONE;
1843
1844 while exp > 1 {
1845 if (exp & 1) == 1 {
1846 acc *= base;
1847 }
1848 exp /= 2;
1849 base = base * base;
1850 }
1851
1852 // since exp!=0, finally the exp must be 1.
1853 // Deal with the final bit of the exponent separately, since
1854 // squaring the base afterwards is not necessary and may cause a
1855 // needless overflow.
1856 acc * base
1857 }
1858
1859 /// Calculates the quotient of Euclidean division of `self` by `rhs`.
1860 ///
1861 /// This computes the integer `q` such that `self = q * rhs + r`, with
1862 /// `r = self.rem_euclid(rhs)` and `0 <= r < abs(rhs)`.
1863 ///
1864 /// In other words, the result is `self / rhs` rounded to the integer `q`
1865 /// such that `self >= q * rhs`.
1866 /// If `self > 0`, this is equal to round towards zero (the default in
1867 /// Rust); if `self < 0`, this is equal to round towards +/- infinity.
1868 ///
1869 /// # Panics
1870 ///
1871 /// This function will panic if `rhs` is 0 or the division results in
1872 /// overflow.
1873 ///
1874 /// # Examples
1875 ///
1876 /// Basic usage:
1877 ///
1878 /// ```
1879 /// # use ethnum::I256;
1880 /// let a = I256::new(7);
1881 /// let b = I256::new(4);
1882 ///
1883 /// assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
1884 /// assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
1885 /// assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
1886 /// assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
1887 /// ```
1888 #[must_use = "this returns the result of the operation, \
1889 without modifying the original"]
1890 #[inline]
1891 pub fn div_euclid(self, rhs: Self) -> Self {
1892 let q = self / rhs;
1893 if self % rhs < 0 {
1894 return if rhs > 0 { q - 1 } else { q + 1 };
1895 }
1896 q
1897 }
1898
1899 /// Calculates the least nonnegative remainder of `self (mod rhs)`.
1900 ///
1901 /// This is done as if by the Euclidean division algorithm -- given
1902 /// `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and
1903 /// `0 <= r < abs(rhs)`.
1904 ///
1905 /// # Panics
1906 ///
1907 /// This function will panic if `rhs` is 0 or the division results in
1908 /// overflow.
1909 ///
1910 /// # Examples
1911 ///
1912 /// Basic usage:
1913 ///
1914 /// ```
1915 /// # use ethnum::I256;
1916 /// let a = I256::new(7);
1917 /// let b = I256::new(4);
1918 ///
1919 /// assert_eq!(a.rem_euclid(b), 3);
1920 /// assert_eq!((-a).rem_euclid(b), 1);
1921 /// assert_eq!(a.rem_euclid(-b), 3);
1922 /// assert_eq!((-a).rem_euclid(-b), 1);
1923 /// ```
1924 #[must_use = "this returns the result of the operation, \
1925 without modifying the original"]
1926 #[inline]
1927 pub fn rem_euclid(self, rhs: Self) -> Self {
1928 let r = self % rhs;
1929 if r < 0 {
1930 if rhs < 0 {
1931 r - rhs
1932 } else {
1933 r + rhs
1934 }
1935 } else {
1936 r
1937 }
1938 }
1939
1940 /// Computes the absolute value of `self`.
1941 ///
1942 /// # Overflow behavior
1943 ///
1944 /// The absolute value of
1945 /// `I256::MIN`
1946 /// cannot be represented as an
1947 /// `I256`,
1948 /// and attempting to calculate it will cause an overflow. This means
1949 /// that code in debug mode will trigger a panic on this case and
1950 /// optimized code will return
1951 /// `I256::MIN`
1952 /// without a panic.
1953 ///
1954 /// # Examples
1955 ///
1956 /// Basic usage:
1957 ///
1958 /// ```
1959 /// # use ethnum::I256;
1960 /// assert_eq!(I256::new(10).abs(), 10);
1961 /// assert_eq!(I256::new(-10).abs(), 10);
1962 /// ```
1963 #[allow(unused_attributes)]
1964 #[inline]
1965 pub fn abs(self) -> Self {
1966 if self.is_negative() {
1967 -self
1968 } else {
1969 self
1970 }
1971 }
1972
1973 /// Returns a number representing sign of `self`.
1974 ///
1975 /// - `0` if the number is zero
1976 /// - `1` if the number is positive
1977 /// - `-1` if the number is negative
1978 ///
1979 /// # Examples
1980 ///
1981 /// Basic usage:
1982 ///
1983 /// ```
1984 /// # use ethnum::I256;
1985 /// assert_eq!(I256::new(10).signum(), 1);
1986 /// assert_eq!(I256::new(0).signum(), 0);
1987 /// assert_eq!(I256::new(-10).signum(), -1);
1988 /// ```
1989 #[inline(always)]
1990 pub const fn signum(self) -> Self {
1991 I256::new(self.signum128())
1992 }
1993
1994 /// Returns a number representing sign of `self` as a 128 bit signed integer.
1995 ///
1996 /// - `0` if the number is zero
1997 /// - `1` if the number is positive
1998 /// - `-1` if the number is negative
1999 ///
2000 /// # Examples
2001 ///
2002 /// Basic usage:
2003 ///
2004 /// ```
2005 /// # use ethnum::I256;
2006 /// assert_eq!(I256::new(10).signum128(), 1i128);
2007 /// assert_eq!(I256::new(0).signum128(), 0i128);
2008 /// assert_eq!(I256::new(-10).signum128(), -1i128);
2009 /// ```
2010 #[inline]
2011 pub const fn signum128(self) -> i128 {
2012 let (hi, lo) = self.into_words();
2013 hi.signum() | (lo != 0) as i128
2014 }
2015
2016 /// Returns `true` if `self` is positive and `false` if the number is zero
2017 /// or negative.
2018 ///
2019 /// # Examples
2020 ///
2021 /// Basic usage:
2022 ///
2023 /// ```
2024 /// # use ethnum::I256;
2025 /// assert!(I256::new(10).is_positive());
2026 /// assert!(!I256::new(-10).is_positive());
2027 /// ```
2028 #[inline]
2029 pub const fn is_positive(self) -> bool {
2030 self.signum128() > 0
2031 }
2032
2033 /// Returns `true` if `self` is negative and `false` if the number is zero
2034 /// or positive.
2035 ///
2036 /// # Examples
2037 ///
2038 /// Basic usage:
2039 ///
2040 /// ```
2041 /// # use ethnum::I256;
2042 /// assert!(I256::new(-10).is_negative());
2043 /// assert!(!I256::new(10).is_negative());
2044 /// ```
2045 #[inline(always)]
2046 pub const fn is_negative(self) -> bool {
2047 let (a, _) = self.into_words();
2048 a < 0
2049 }
2050
2051 /// Return the memory representation of this integer as a byte array in
2052 /// big-endian (network) byte order.
2053 ///
2054 /// # Examples
2055 ///
2056 /// ```
2057 /// # use ethnum::I256;
2058 /// let bytes = I256::from_words(
2059 /// 0x00010203_04050607_08090a0b_0c0d0e0f,
2060 /// 0x10111213_14151617_18191a1b_1c1d1e1f,
2061 /// );
2062 /// assert_eq!(
2063 /// bytes.to_be_bytes(),
2064 /// [
2065 /// 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
2066 /// 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
2067 /// ],
2068 /// );
2069 /// ```
2070 #[inline]
2071 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
2072 self.to_be().to_ne_bytes()
2073 }
2074
2075 /// Return the memory representation of this integer as a byte array in
2076 /// little-endian byte order.
2077 ///
2078 /// # Examples
2079 ///
2080 /// ```
2081 /// # use ethnum::I256;
2082 /// let bytes = I256::from_words(
2083 /// 0x00010203_04050607_08090a0b_0c0d0e0f,
2084 /// 0x10111213_14151617_18191a1b_1c1d1e1f,
2085 /// );
2086 /// assert_eq!(
2087 /// bytes.to_le_bytes(),
2088 /// [
2089 /// 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10,
2090 /// 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00,
2091 /// ],
2092 /// );
2093 /// ```
2094 #[inline]
2095 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
2096 self.to_le().to_ne_bytes()
2097 }
2098
2099 /// Return the memory representation of this integer as a byte array in
2100 /// native byte order.
2101 ///
2102 /// As the target platform's native endianness is used, portable code
2103 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
2104 /// instead.
2105 ///
2106 /// [`to_be_bytes`]: Self::to_be_bytes
2107 /// [`to_le_bytes`]: Self::to_le_bytes
2108 ///
2109 /// # Examples
2110 ///
2111 /// ```
2112 /// # use ethnum::I256;
2113 /// let bytes = I256::from_words(
2114 /// 0x00010203_04050607_08090a0b_0c0d0e0f,
2115 /// 0x10111213_14151617_18191a1b_1c1d1e1f,
2116 /// );
2117 /// assert_eq!(
2118 /// bytes.to_ne_bytes(),
2119 /// if cfg!(target_endian = "big") {
2120 /// [
2121 /// 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
2122 /// 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
2123 /// ]
2124 /// } else {
2125 /// [
2126 /// 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10,
2127 /// 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00,
2128 /// ]
2129 /// }
2130 /// );
2131 /// ```
2132 #[inline]
2133 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
2134 // SAFETY: integers are plain old datatypes so we can always transmute them to
2135 // arrays of bytes
2136 unsafe { mem::transmute(self) }
2137 }
2138
2139 /// Create an integer value from its representation as a byte array in
2140 /// big endian.
2141 ///
2142 /// # Examples
2143 ///
2144 /// ```
2145 /// # use ethnum::I256;
2146 /// let value = I256::from_be_bytes([
2147 /// 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
2148 /// 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
2149 /// ]);
2150 /// assert_eq!(
2151 /// value,
2152 /// I256::from_words(
2153 /// 0x00010203_04050607_08090a0b_0c0d0e0f,
2154 /// 0x10111213_14151617_18191a1b_1c1d1e1f,
2155 /// ),
2156 /// );
2157 /// ```
2158 ///
2159 /// When starting from a slice rather than an array, fallible conversion
2160 /// APIs can be used:
2161 ///
2162 /// ```
2163 /// # use ethnum::I256;
2164 /// fn read_be_i256(input: &mut &[u8]) -> I256 {
2165 /// let (int_bytes, rest) = input.split_at(std::mem::size_of::<I256>());
2166 /// *input = rest;
2167 /// I256::from_be_bytes(int_bytes.try_into().unwrap())
2168 /// }
2169 /// ```
2170 #[inline]
2171 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2172 Self::from_be(Self::from_ne_bytes(bytes))
2173 }
2174
2175 /// Create an integer value from its representation as a byte array in
2176 /// little endian.
2177 ///
2178 /// # Examples
2179 ///
2180 /// ```
2181 /// # use ethnum::I256;
2182 /// let value = I256::from_le_bytes([
2183 /// 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10,
2184 /// 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00,
2185 /// ]);
2186 /// assert_eq!(
2187 /// value,
2188 /// I256::from_words(
2189 /// 0x00010203_04050607_08090a0b_0c0d0e0f,
2190 /// 0x10111213_14151617_18191a1b_1c1d1e1f,
2191 /// ),
2192 /// );
2193 /// ```
2194 ///
2195 /// When starting from a slice rather than an array, fallible conversion
2196 /// APIs can be used:
2197 ///
2198 /// ```
2199 /// # use ethnum::I256;
2200 /// fn read_le_i256(input: &mut &[u8]) -> I256 {
2201 /// let (int_bytes, rest) = input.split_at(std::mem::size_of::<I256>());
2202 /// *input = rest;
2203 /// I256::from_le_bytes(int_bytes.try_into().unwrap())
2204 /// }
2205 /// ```
2206 #[inline]
2207 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2208 Self::from_le(Self::from_ne_bytes(bytes))
2209 }
2210
2211 /// Create an integer value from its memory representation as a byte
2212 /// array in native endianness.
2213 ///
2214 /// As the target platform's native endianness is used, portable code
2215 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
2216 /// appropriate instead.
2217 ///
2218 /// [`from_be_bytes`]: Self::from_be_bytes
2219 /// [`from_le_bytes`]: Self::from_le_bytes
2220 ///
2221 /// # Examples
2222 ///
2223 /// ```
2224 /// # use ethnum::I256;
2225 /// let value = I256::from_ne_bytes(if cfg!(target_endian = "big") {
2226 /// [
2227 /// 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
2228 /// 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
2229 /// ]
2230 /// } else {
2231 /// [
2232 /// 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10,
2233 /// 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00,
2234 /// ]
2235 /// });
2236 /// assert_eq!(
2237 /// value,
2238 /// I256::from_words(
2239 /// 0x00010203_04050607_08090a0b_0c0d0e0f,
2240 /// 0x10111213_14151617_18191a1b_1c1d1e1f,
2241 /// ),
2242 /// );
2243 /// ```
2244 ///
2245 /// When starting from a slice rather than an array, fallible conversion
2246 /// APIs can be used:
2247 ///
2248 /// ```
2249 /// # use ethnum::I256;
2250 /// fn read_ne_i256(input: &mut &[u8]) -> I256 {
2251 /// let (int_bytes, rest) = input.split_at(std::mem::size_of::<I256>());
2252 /// *input = rest;
2253 /// I256::from_ne_bytes(int_bytes.try_into().unwrap())
2254 /// }
2255 /// ```
2256 #[inline]
2257 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
2258 // SAFETY: integers are plain old datatypes so we can always transmute to them
2259 unsafe { mem::transmute(bytes) }
2260 }
2261}