ethnum/uint/api.rs
1//! Module containing integer aritimetic methods closely following the Rust
2//! standard library API for `uN` types.
3
4use super::U256;
5use crate::{intrinsics, I256};
6use core::{
7 mem::{self, MaybeUninit},
8 num::ParseIntError,
9};
10
11impl U256 {
12 /// The smallest value that can be represented by this integer type.
13 ///
14 /// # Examples
15 ///
16 /// Basic usage:
17 ///
18 /// ```
19 /// # use ethnum::U256;
20 /// assert_eq!(U256::MIN, U256::new(0));
21 /// ```
22 pub const MIN: Self = Self([0; 2]);
23
24 /// The largest value that can be represented by this integer type.
25 ///
26 /// # Examples
27 ///
28 /// Basic usage:
29 ///
30 /// ```
31 /// # use ethnum::U256;
32 /// assert_eq!(
33 /// U256::MAX.to_string(),
34 /// "115792089237316195423570985008687907853269984665640564039457584007913129639935",
35 /// );
36 /// ```
37 pub const MAX: Self = Self([!0; 2]);
38
39 /// The size of this integer type in bits.
40 ///
41 /// # Examples
42 ///
43 /// ```
44 /// # use ethnum::U256;
45 /// assert_eq!(U256::BITS, 256);
46 /// ```
47 pub const BITS: u32 = 256;
48
49 /// Converts a string slice in a given base to an integer.
50 ///
51 /// The string is expected to be an optional `+` sign followed by digits.
52 /// Leading and trailing whitespace represent an error. Digits are a subset
53 /// of these characters, depending on `radix`:
54 ///
55 /// * `0-9`
56 /// * `a-z`
57 /// * `A-Z`
58 ///
59 /// # Panics
60 ///
61 /// This function panics if `radix` is not in the range from 2 to 36.
62 ///
63 /// # Examples
64 ///
65 /// Basic usage:
66 ///
67 /// ```
68 /// # use ethnum::U256;
69 /// assert_eq!(U256::from_str_radix("A", 16), Ok(U256::new(10)));
70 /// ```
71 #[inline]
72 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
73 crate::parse::from_str_radix(src, radix, None)
74 }
75
76 /// Returns the number of ones in the binary representation of `self`.
77 ///
78 /// # Examples
79 ///
80 /// Basic usage:
81 ///
82 /// ```
83 /// # use ethnum::U256;
84 /// let n = U256::new(0b01001100);
85 /// assert_eq!(n.count_ones(), 3);
86 /// ```
87 #[inline]
88 pub const fn count_ones(self) -> u32 {
89 let Self([a, b]) = self;
90 a.count_ones() + b.count_ones()
91 }
92
93 /// Returns the number of zeros in the binary representation of `self`.
94 ///
95 /// # Examples
96 ///
97 /// Basic usage:
98 ///
99 /// ```
100 /// # use ethnum::U256;
101 /// assert_eq!(U256::MIN.count_zeros(), 256);
102 /// assert_eq!(U256::MAX.count_zeros(), 0);
103 /// ```
104 #[inline]
105 pub const fn count_zeros(self) -> u32 {
106 let Self([a, b]) = self;
107 a.count_zeros() + b.count_zeros()
108 }
109
110 /// Returns the number of leading zeros in the binary representation of
111 /// `self`.
112 ///
113 /// # Examples
114 ///
115 /// Basic usage:
116 ///
117 /// ```
118 /// # use ethnum::U256;
119 /// let n = U256::MAX >> 2u32;
120 /// assert_eq!(n.leading_zeros(), 2);
121 /// ```
122 #[inline(always)]
123 pub fn leading_zeros(self) -> u32 {
124 intrinsics::signed::uctlz(&self)
125 }
126
127 /// Returns the number of trailing zeros in the binary representation of
128 /// `self`.
129 ///
130 /// # Examples
131 ///
132 /// Basic usage:
133 ///
134 /// ```
135 /// # use ethnum::U256;
136 /// let n = U256::new(0b0101000);
137 /// assert_eq!(n.trailing_zeros(), 3);
138 /// ```
139 #[inline(always)]
140 pub fn trailing_zeros(self) -> u32 {
141 intrinsics::signed::ucttz(&self)
142 }
143
144 /// Returns the number of leading ones in the binary representation of
145 /// `self`.
146 ///
147 /// # Examples
148 ///
149 /// Basic usage:
150 ///
151 /// ```
152 /// # use ethnum::U256;
153 /// let n = !(U256::MAX >> 2u32);
154 /// assert_eq!(n.leading_ones(), 2);
155 /// ```
156 #[inline]
157 pub fn leading_ones(self) -> u32 {
158 (!self).leading_zeros()
159 }
160
161 /// Returns the number of trailing ones in the binary representation of
162 /// `self`.
163 ///
164 /// # Examples
165 ///
166 /// Basic usage:
167 ///
168 /// ```
169 /// # use ethnum::U256;
170 /// let n = U256::new(0b1010111);
171 /// assert_eq!(n.trailing_ones(), 3);
172 /// ```
173 #[inline]
174 pub fn trailing_ones(self) -> u32 {
175 (!self).trailing_zeros()
176 }
177
178 /// Shifts the bits to the left by a specified amount, `n`, wrapping the
179 /// truncated bits to the end of the resulting integer.
180 ///
181 /// Please note this isn't the same operation as the `<<` shifting
182 /// operator!
183 ///
184 /// # Examples
185 ///
186 /// Basic usage:
187 ///
188 /// ```
189 /// # use ethnum::U256;
190 /// let n = U256::from_words(
191 /// 0x13f40000000000000000000000000000,
192 /// 0x00000000000000000000000000004f76,
193 /// );
194 /// let m = U256::new(0x4f7613f4);
195 /// assert_eq!(n.rotate_left(16), m);
196 /// ```
197 #[must_use = "this returns the result of the operation, \
198 without modifying the original"]
199 #[inline(always)]
200 pub fn rotate_left(self, n: u32) -> Self {
201 let mut r = MaybeUninit::uninit();
202 intrinsics::signed::urol3(&mut r, &self, n);
203 unsafe { r.assume_init() }
204 }
205
206 /// Shifts the bits to the right by a specified amount, `n`, wrapping the
207 /// truncated bits to the beginning of the resulting integer.
208 ///
209 /// Please note this isn't the same operation as the `>>` shifting operator!
210 ///
211 /// # Examples
212 ///
213 /// Basic usage:
214 ///
215 /// ```
216 /// # use ethnum::U256;
217 /// let n = U256::new(0x4f7613f4);
218 /// let m = U256::from_words(
219 /// 0x13f40000000000000000000000000000,
220 /// 0x00000000000000000000000000004f76,
221 /// );
222 ///
223 /// assert_eq!(n.rotate_right(16), m);
224 /// ```
225 #[must_use = "this returns the result of the operation, \
226 without modifying the original"]
227 #[inline(always)]
228 pub fn rotate_right(self, n: u32) -> Self {
229 let mut r = MaybeUninit::uninit();
230 intrinsics::signed::uror3(&mut r, &self, n);
231 unsafe { r.assume_init() }
232 }
233
234 /// Reverses the byte order of the integer.
235 ///
236 /// # Examples
237 ///
238 /// Basic usage:
239 ///
240 /// ```
241 /// # use ethnum::U256;
242 /// let n = U256::from_words(
243 /// 0x00010203_04050607_08090a0b_0c0d0e0f,
244 /// 0x10111213_14151617_18191a1b_1c1d1e1f,
245 /// );
246 /// assert_eq!(
247 /// n.swap_bytes(),
248 /// U256::from_words(
249 /// 0x1f1e1d1c_1b1a1918_17161514_13121110,
250 /// 0x0f0e0d0c_0b0a0908_07060504_03020100,
251 /// ),
252 /// );
253 /// ```
254 #[inline]
255 pub const fn swap_bytes(self) -> Self {
256 let Self([a, b]) = self;
257 Self([b.swap_bytes(), a.swap_bytes()])
258 }
259
260 /// Reverses the bit pattern of the integer.
261 ///
262 /// # Examples
263 ///
264 /// Basic usage:
265 ///
266 /// ```
267 /// # use ethnum::U256;
268 /// let n = U256::from_words(
269 /// 0x00010203_04050607_08090a0b_0c0d0e0f,
270 /// 0x10111213_14151617_18191a1b_1c1d1e1f,
271 /// );
272 /// assert_eq!(
273 /// n.reverse_bits(),
274 /// U256::from_words(
275 /// 0xf878b838_d8589818_e868a828_c8488808,
276 /// 0xf070b030_d0509010_e060a020_c0408000,
277 /// ),
278 /// );
279 /// ```
280 #[inline]
281 pub const fn reverse_bits(self) -> Self {
282 let Self([a, b]) = self;
283 Self([b.reverse_bits(), a.reverse_bits()])
284 }
285
286 /// Converts an integer from big endian to the target's endianness.
287 ///
288 /// On big endian this is a no-op. On little endian the bytes are swapped.
289 ///
290 /// # Examples
291 ///
292 /// Basic usage:
293 ///
294 /// ```
295 /// # use ethnum::U256;
296 /// let n = U256::new(0x1A);
297 /// if cfg!(target_endian = "big") {
298 /// assert_eq!(U256::from_be(n), n);
299 /// } else {
300 /// assert_eq!(U256::from_be(n), n.swap_bytes());
301 /// }
302 /// ```
303 #[inline(always)]
304 #[allow(clippy::wrong_self_convention)]
305 pub const fn from_be(x: Self) -> Self {
306 #[cfg(target_endian = "big")]
307 {
308 x
309 }
310 #[cfg(not(target_endian = "big"))]
311 {
312 x.swap_bytes()
313 }
314 }
315
316 /// Converts an integer from little endian to the target's endianness.
317 ///
318 /// On little endian this is a no-op. On big endian the bytes are swapped.
319 ///
320 /// # Examples
321 ///
322 /// Basic usage:
323 ///
324 /// ```
325 /// # use ethnum::U256;
326 /// let n = U256::new(0x1A);
327 /// if cfg!(target_endian = "little") {
328 /// assert_eq!(U256::from_le(n), n)
329 /// } else {
330 /// assert_eq!(U256::from_le(n), n.swap_bytes())
331 /// }
332 /// ```
333 #[inline(always)]
334 #[allow(clippy::wrong_self_convention)]
335 pub const fn from_le(x: Self) -> Self {
336 #[cfg(target_endian = "little")]
337 {
338 x
339 }
340 #[cfg(not(target_endian = "little"))]
341 {
342 x.swap_bytes()
343 }
344 }
345
346 /// Converts `self` to big endian from the target's endianness.
347 ///
348 /// On big endian this is a no-op. On little endian the bytes are swapped.
349 ///
350 /// # Examples
351 ///
352 /// Basic usage:
353 ///
354 /// ```
355 /// # use ethnum::U256;
356 /// let n = U256::new(0x1A);
357 /// if cfg!(target_endian = "big") {
358 /// assert_eq!(n.to_be(), n)
359 /// } else {
360 /// assert_eq!(n.to_be(), n.swap_bytes())
361 /// }
362 /// ```
363 #[inline(always)]
364 pub const fn to_be(self) -> Self {
365 #[cfg(target_endian = "big")]
366 {
367 self
368 }
369 #[cfg(not(target_endian = "big"))]
370 {
371 self.swap_bytes()
372 }
373 }
374
375 /// Converts `self` to little endian from the target's endianness.
376 ///
377 /// On little endian this is a no-op. On big endian the bytes are swapped.
378 ///
379 /// # Examples
380 ///
381 /// Basic usage:
382 ///
383 /// ```
384 /// # use ethnum::U256;
385 /// let n = U256::new(0x1A);
386 /// if cfg!(target_endian = "little") {
387 /// assert_eq!(n.to_le(), n)
388 /// } else {
389 /// assert_eq!(n.to_le(), n.swap_bytes())
390 /// }
391 /// ```
392 #[inline(always)]
393 pub const fn to_le(self) -> Self {
394 #[cfg(target_endian = "little")]
395 {
396 self
397 }
398 #[cfg(not(target_endian = "little"))]
399 {
400 self.swap_bytes()
401 }
402 }
403
404 /// Checked integer addition. Computes `self + rhs`, returning `None` if
405 /// overflow occurred.
406 ///
407 /// # Examples
408 ///
409 /// Basic usage:
410 ///
411 /// ```
412 /// # use ethnum::U256;
413 /// assert_eq!((U256::MAX - 2).checked_add(U256::new(1)), Some(U256::MAX - 1));
414 /// assert_eq!((U256::MAX - 2).checked_add(U256::new(3)), None);
415 /// ```
416 #[must_use = "this returns the result of the operation, \
417 without modifying the original"]
418 #[inline]
419 pub fn checked_add(self, rhs: Self) -> Option<Self> {
420 let (a, b) = self.overflowing_add(rhs);
421 if b {
422 None
423 } else {
424 Some(a)
425 }
426 }
427
428 /// Checked addition with a signed integer. Computes `self + rhs`,
429 /// returning `None` if overflow occurred.
430 ///
431 /// # Examples
432 ///
433 /// Basic usage:
434 ///
435 /// ```
436 /// # use ethnum::{I256, U256};
437 /// assert_eq!(U256::new(1).checked_add_signed(I256::new(2)), Some(U256::new(3)));
438 /// assert_eq!(U256::new(1).checked_add_signed(I256::new(-2)), None);
439 /// assert_eq!((U256::MAX - 2).checked_add_signed(I256::new(3)), None);
440 /// ```
441 #[must_use = "this returns the result of the operation, \
442 without modifying the original"]
443 #[inline]
444 pub fn checked_add_signed(self, rhs: I256) -> Option<Self> {
445 let (a, b) = self.overflowing_add_signed(rhs);
446 if b {
447 None
448 } else {
449 Some(a)
450 }
451 }
452
453 /// Checked integer subtraction. Computes `self - rhs`, returning `None` if
454 /// overflow occurred.
455 ///
456 /// # Examples
457 ///
458 /// Basic usage:
459 ///
460 /// ```
461 /// # use ethnum::U256;
462 /// assert_eq!(U256::new(1).checked_sub(U256::new(1)), Some(U256::ZERO));
463 /// assert_eq!(U256::new(0).checked_sub(U256::new(1)), None);
464 /// ```
465 #[must_use = "this returns the result of the operation, \
466 without modifying the original"]
467 #[inline]
468 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
469 let (a, b) = self.overflowing_sub(rhs);
470 if b {
471 None
472 } else {
473 Some(a)
474 }
475 }
476
477 /// Checked integer multiplication. Computes `self * rhs`, returning `None`
478 /// if overflow occurred.
479 ///
480 /// # Examples
481 ///
482 /// Basic usage:
483 ///
484 /// ```
485 /// # use ethnum::U256;
486 /// assert_eq!(U256::new(5).checked_mul(U256::new(1)), Some(U256::new(5)));
487 /// assert_eq!(U256::MAX.checked_mul(U256::new(2)), None);
488 /// ```
489 #[must_use = "this returns the result of the operation, \
490 without modifying the original"]
491 #[inline]
492 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
493 let (a, b) = self.overflowing_mul(rhs);
494 if b {
495 None
496 } else {
497 Some(a)
498 }
499 }
500
501 /// Checked integer division. Computes `self / rhs`, returning `None` if
502 /// `rhs == 0`.
503 ///
504 /// # Examples
505 ///
506 /// Basic usage:
507 ///
508 /// ```
509 /// # use ethnum::U256;
510 /// assert_eq!(U256::new(128).checked_div(U256::new(2)), Some(U256::new(64)));
511 /// assert_eq!(U256::new(1).checked_div(U256::new(0)), None);
512 /// ```
513 #[must_use = "this returns the result of the operation, \
514 without modifying the original"]
515 #[inline]
516 pub fn checked_div(self, rhs: Self) -> Option<Self> {
517 if rhs == U256::ZERO {
518 None
519 } else {
520 Some(self / rhs)
521 }
522 }
523
524 /// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning
525 /// `None` if `rhs == 0`.
526 ///
527 /// # Examples
528 ///
529 /// Basic usage:
530 ///
531 /// ```
532 /// # use ethnum::U256;
533 /// assert_eq!(U256::new(128).checked_div_euclid(U256::new(2)), Some(U256::new(64)));
534 /// assert_eq!(U256::new(1).checked_div_euclid(U256::new(0)), None);
535 /// ```
536 #[must_use = "this returns the result of the operation, \
537 without modifying the original"]
538 #[inline]
539 pub fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
540 if rhs == U256::ZERO {
541 None
542 } else {
543 Some(self.div_euclid(rhs))
544 }
545 }
546
547 /// Checked integer remainder. Computes `self % rhs`, returning `None` if
548 /// `rhs == 0`.
549 ///
550 /// # Examples
551 ///
552 /// Basic usage:
553 ///
554 /// ```
555 /// # use ethnum::U256;
556 /// assert_eq!(U256::new(5).checked_rem(U256::new(2)), Some(U256::new(1)));
557 /// assert_eq!(U256::new(5).checked_rem(U256::new(0)), None);
558 /// ```
559 #[must_use = "this returns the result of the operation, \
560 without modifying the original"]
561 #[inline]
562 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
563 if rhs == U256::ZERO {
564 None
565 } else {
566 Some(self % rhs)
567 }
568 }
569
570 /// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning
571 /// `None` if `rhs == 0`.
572 ///
573 /// # Examples
574 ///
575 /// Basic usage:
576 ///
577 /// ```
578 /// # use ethnum::U256;
579 /// assert_eq!(U256::new(5).checked_rem_euclid(U256::new(2)), Some(U256::new(1)));
580 /// assert_eq!(U256::new(5).checked_rem_euclid(U256::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_rem_euclid(self, rhs: Self) -> Option<Self> {
586 if rhs == U256::ZERO {
587 None
588 } else {
589 Some(self.rem_euclid(rhs))
590 }
591 }
592
593 /// Checked negation. Computes `-self`, returning `None` unless `self == 0`.
594 ///
595 /// Note that negating any positive integer will overflow.
596 ///
597 /// # Examples
598 ///
599 /// Basic usage:
600 ///
601 /// ```
602 /// # use ethnum::U256;
603 /// assert_eq!(U256::ZERO.checked_neg(), Some(U256::ZERO));
604 /// assert_eq!(U256::new(1).checked_neg(), None);
605 /// ```
606 #[inline]
607 pub fn checked_neg(self) -> Option<Self> {
608 let (a, b) = self.overflowing_neg();
609 if b {
610 None
611 } else {
612 Some(a)
613 }
614 }
615
616 /// Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is
617 /// larger than or equal to the number of bits in `self`.
618 ///
619 /// # Examples
620 ///
621 /// Basic usage:
622 ///
623 /// ```
624 /// # use ethnum::U256;
625 /// assert_eq!(U256::new(0x1).checked_shl(4), Some(U256::new(0x10)));
626 /// assert_eq!(U256::new(0x10).checked_shl(257), None);
627 /// ```
628 #[must_use = "this returns the result of the operation, \
629 without modifying the original"]
630 #[inline]
631 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
632 let (a, b) = self.overflowing_shl(rhs);
633 if b {
634 None
635 } else {
636 Some(a)
637 }
638 }
639
640 /// Checked shift right. Computes `self >> rhs`, returning `None` if `rhs`
641 /// is larger than or equal to the number of bits in `self`.
642 ///
643 /// # Examples
644 ///
645 /// Basic usage:
646 ///
647 /// ```
648 /// # use ethnum::U256;
649 /// assert_eq!(U256::new(0x10).checked_shr(4), Some(U256::new(0x1)));
650 /// assert_eq!(U256::new(0x10).checked_shr(257), None);
651 /// ```
652 #[must_use = "this returns the result of the operation, \
653 without modifying the original"]
654 #[inline]
655 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
656 let (a, b) = self.overflowing_shr(rhs);
657 if b {
658 None
659 } else {
660 Some(a)
661 }
662 }
663
664 /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
665 /// overflow occurred.
666 ///
667 /// # Examples
668 ///
669 /// Basic usage:
670 ///
671 /// ```
672 /// # use ethnum::U256;
673 /// assert_eq!(U256::new(2).checked_pow(5), Some(U256::new(32)));
674 /// assert_eq!(U256::MAX.checked_pow(2), None);
675 /// ```
676 #[must_use = "this returns the result of the operation, \
677 without modifying the original"]
678 #[inline]
679 pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
680 let mut base = self;
681 let mut acc = U256::ONE;
682
683 while exp > 1 {
684 if (exp & 1) == 1 {
685 acc = acc.checked_mul(base)?;
686 }
687 exp /= 2;
688 base = base.checked_mul(base)?;
689 }
690
691 // Deal with the final bit of the exponent separately, since
692 // squaring the base afterwards is not necessary and may cause a
693 // needless overflow.
694 if exp == 1 {
695 acc = acc.checked_mul(base)?;
696 }
697
698 Some(acc)
699 }
700
701 /// Saturating integer addition. Computes `self + rhs`, saturating at the
702 /// numeric bounds instead of overflowing.
703 ///
704 /// # Examples
705 ///
706 /// Basic usage:
707 ///
708 /// ```
709 /// # use ethnum::U256;
710 /// assert_eq!(U256::new(100).saturating_add(U256::new(1)), U256::new(101));
711 /// assert_eq!(U256::MAX.saturating_add(U256::new(127)), U256::MAX);
712 /// ```
713 #[must_use = "this returns the result of the operation, \
714 without modifying the original"]
715 #[inline]
716 pub fn saturating_add(self, rhs: Self) -> Self {
717 self.checked_add(rhs).unwrap_or(U256::MAX)
718 }
719
720 /// Saturating addition with a signed integer. Computes `self + rhs`,
721 /// saturating at the numeric bounds instead of overflowing.
722 ///
723 /// # Examples
724 ///
725 /// Basic usage:
726 ///
727 /// ```
728 /// # use ethnum::{I256, U256};
729 /// assert_eq!(U256::new(1).saturating_add_signed(I256::new(2)), U256::new(3));
730 /// assert_eq!(U256::new(1).saturating_add_signed(I256::new(-2)), U256::new(0));
731 /// assert_eq!((U256::MAX - 2).saturating_add_signed(I256::new(4)), U256::MAX);
732 /// ```
733 #[must_use = "this returns the result of the operation, \
734 without modifying the original"]
735 #[inline]
736 pub fn saturating_add_signed(self, rhs: I256) -> Self {
737 let (res, overflow) = self.overflowing_add(rhs.as_u256());
738 if overflow == (rhs < 0) {
739 res
740 } else if overflow {
741 Self::MAX
742 } else {
743 Self::ZERO
744 }
745 }
746
747 /// Saturating integer subtraction. Computes `self - rhs`, saturating at the
748 /// numeric bounds instead of overflowing.
749 ///
750 /// # Examples
751 ///
752 /// Basic usage:
753 ///
754 /// ```
755 /// # use ethnum::U256;
756 /// assert_eq!(U256::new(100).saturating_sub(U256::new(27)), U256::new(73));
757 /// assert_eq!(U256::new(13).saturating_sub(U256::new(127)), U256::new(0));
758 /// ```
759 #[must_use = "this returns the result of the operation, \
760 without modifying the original"]
761 #[inline]
762 pub fn saturating_sub(self, rhs: Self) -> Self {
763 self.checked_sub(rhs).unwrap_or(U256::MIN)
764 }
765
766 /// Saturating integer multiplication. Computes `self * rhs`, saturating at
767 /// the numeric bounds instead of overflowing.
768 ///
769 /// # Examples
770 ///
771 /// Basic usage:
772 ///
773 /// ```
774 /// # use ethnum::U256;
775 /// assert_eq!(U256::new(2).saturating_mul(U256::new(10)), U256::new(20));
776 /// assert_eq!((U256::MAX).saturating_mul(U256::new(10)), U256::MAX);
777 /// ```
778 #[must_use = "this returns the result of the operation, \
779 without modifying the original"]
780 #[inline]
781 pub fn saturating_mul(self, rhs: Self) -> Self {
782 match self.checked_mul(rhs) {
783 Some(x) => x,
784 None => Self::MAX,
785 }
786 }
787
788 /// Saturating integer division. Computes `self / rhs`, saturating at the
789 /// numeric bounds instead of overflowing.
790 ///
791 /// # Examples
792 ///
793 /// Basic usage:
794 ///
795 /// ```
796 /// # use ethnum::U256;
797 /// assert_eq!(U256::new(5).saturating_div(U256::new(2)), U256::new(2));
798 /// ```
799 ///
800 /// ```should_panic
801 /// # use ethnum::U256;
802 /// let _ = U256::new(1).saturating_div(U256::ZERO);
803 /// ```
804 #[must_use = "this returns the result of the operation, \
805 without modifying the original"]
806 #[inline(always)]
807 pub fn saturating_div(self, rhs: Self) -> Self {
808 // on unsigned types, there is no overflow in integer division
809 self.wrapping_div(rhs)
810 }
811
812 /// Saturating integer exponentiation. Computes `self.pow(exp)`, saturating
813 /// at the numeric bounds instead of overflowing.
814 ///
815 /// # Examples
816 ///
817 /// Basic usage:
818 ///
819 /// ```
820 /// # use ethnum::U256;
821 /// assert_eq!(U256::new(4).saturating_pow(3), U256::new(64));
822 /// assert_eq!(U256::MAX.saturating_pow(2), U256::MAX);
823 /// ```
824 #[must_use = "this returns the result of the operation, \
825 without modifying the original"]
826 #[inline]
827 pub fn saturating_pow(self, exp: u32) -> Self {
828 match self.checked_pow(exp) {
829 Some(x) => x,
830 None => Self::MAX,
831 }
832 }
833
834 /// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at
835 /// the boundary of the type.
836 ///
837 /// # Examples
838 ///
839 /// Basic usage:
840 ///
841 /// ```
842 /// # use ethnum::U256;
843 /// assert_eq!(U256::new(200).wrapping_add(U256::new(55)), U256::new(255));
844 /// assert_eq!(U256::new(200).wrapping_add(U256::MAX), U256::new(199));
845 /// ```
846 #[must_use = "this returns the result of the operation, \
847 without modifying the original"]
848 #[inline(always)]
849 pub fn wrapping_add(self, rhs: Self) -> Self {
850 let mut result = MaybeUninit::uninit();
851 intrinsics::signed::uadd3(&mut result, &self, &rhs);
852 unsafe { result.assume_init() }
853 }
854
855 /// Wrapping (modular) addition with a signed integer. Computes
856 /// `self + rhs`, wrapping around at the boundary of the type.
857 ///
858 /// # Examples
859 ///
860 /// Basic usage:
861 ///
862 /// ```
863 /// # use ethnum::{I256, U256};
864 /// assert_eq!(U256::new(1).wrapping_add_signed(I256::new(2)), U256::new(3));
865 /// assert_eq!(U256::new(1).wrapping_add_signed(I256::new(-2)), U256::MAX);
866 /// assert_eq!((U256::MAX - 2).wrapping_add_signed(I256::new(4)), U256::new(1));
867 /// ```
868 #[must_use = "this returns the result of the operation, \
869 without modifying the original"]
870 #[inline]
871 pub fn wrapping_add_signed(self, rhs: I256) -> Self {
872 self.wrapping_add(rhs.as_u256())
873 }
874
875 /// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around
876 /// at the boundary of the type.
877 ///
878 /// # Examples
879 ///
880 /// Basic usage:
881 ///
882 /// ```
883 /// # use ethnum::U256;
884 /// assert_eq!(U256::new(100).wrapping_sub(U256::new(100)), U256::new(0));
885 /// assert_eq!(U256::new(100).wrapping_sub(U256::MAX), U256::new(101));
886 /// ```
887 #[must_use = "this returns the result of the operation, \
888 without modifying the original"]
889 #[inline(always)]
890 pub fn wrapping_sub(self, rhs: Self) -> Self {
891 let mut result = MaybeUninit::uninit();
892 intrinsics::signed::usub3(&mut result, &self, &rhs);
893 unsafe { result.assume_init() }
894 }
895
896 /// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping
897 /// around at the boundary of the type.
898 ///
899 /// # Examples
900 ///
901 /// Basic usage:
902 ///
903 /// Please note that this example is shared between integer types.
904 /// Which explains why `u8` is used here.
905 ///
906 /// ```
907 /// # use ethnum::U256;
908 /// assert_eq!(U256::new(10).wrapping_mul(U256::new(12)), U256::new(120));
909 /// assert_eq!(U256::MAX.wrapping_mul(U256::new(2)), U256::MAX - 1);
910 /// ```
911 #[must_use = "this returns the result of the operation, \
912 without modifying the original"]
913 #[inline(always)]
914 pub fn wrapping_mul(self, rhs: Self) -> Self {
915 let mut result = MaybeUninit::uninit();
916 intrinsics::signed::umul3(&mut result, &self, &rhs);
917 unsafe { result.assume_init() }
918 }
919
920 /// Wrapping (modular) division. Computes `self / rhs`. Wrapped division on
921 /// unsigned types is just normal division. There's no way wrapping could
922 /// ever happen. This function exists, so that all operations are accounted
923 /// for in the wrapping operations.
924 ///
925 /// # Examples
926 ///
927 /// Basic usage:
928 ///
929 /// ```
930 /// # use ethnum::U256;
931 /// assert_eq!(U256::new(100).wrapping_div(U256::new(10)), U256::new(10));
932 /// ```
933 #[must_use = "this returns the result of the operation, \
934 without modifying the original"]
935 #[inline(always)]
936 pub fn wrapping_div(self, rhs: Self) -> Self {
937 self / rhs
938 }
939
940 /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`. Wrapped
941 /// division on unsigned types is just normal division. There's no way
942 /// wrapping could ever happen. This function exists, so that all operations
943 /// are accounted for in the wrapping operations. Since, for the positive
944 /// integers, all common definitions of division are equal, this is exactly
945 /// equal to `self.wrapping_div(rhs)`.
946 ///
947 /// # Examples
948 ///
949 /// Basic usage:
950 ///
951 /// ```
952 /// # use ethnum::U256;
953 /// assert_eq!(U256::new(100).wrapping_div_euclid(U256::new(10)), U256::new(10));
954 /// ```
955 #[must_use = "this returns the result of the operation, \
956 without modifying the original"]
957 #[inline(always)]
958 pub fn wrapping_div_euclid(self, rhs: Self) -> Self {
959 self / rhs
960 }
961
962 /// Wrapping (modular) remainder. Computes `self % rhs`. Wrapped remainder
963 /// calculation on unsigned types is just the regular remainder calculation.
964 /// There's no way wrapping could ever happen. This function exists, so that
965 /// all operations are accounted for in the wrapping operations.
966 ///
967 /// # Examples
968 ///
969 /// Basic usage:
970 ///
971 /// ```
972 /// # use ethnum::U256;
973 /// assert_eq!(U256::new(100).wrapping_rem(U256::new(10)), U256::new(0));
974 /// ```
975 #[must_use = "this returns the result of the operation, \
976 without modifying the original"]
977 #[inline(always)]
978 pub fn wrapping_rem(self, rhs: Self) -> Self {
979 self % rhs
980 }
981
982 /// Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`. Wrapped
983 /// modulo calculation on unsigned types is just the regular remainder
984 /// calculation. There's no way wrapping could ever happen. This function
985 /// exists, so that all operations are accounted for in the wrapping
986 /// operations. Since, for the positive integers, all common definitions of
987 /// division are equal, this is exactly equal to `self.wrapping_rem(rhs)`.
988 ///
989 /// # Examples
990 ///
991 /// Basic usage:
992 ///
993 /// ```
994 /// # use ethnum::U256;
995 /// assert_eq!(U256::new(100).wrapping_rem_euclid(U256::new(10)), U256::new(0));
996 /// ```
997 #[must_use = "this returns the result of the operation, \
998 without modifying the original"]
999 #[inline(always)]
1000 pub fn wrapping_rem_euclid(self, rhs: Self) -> Self {
1001 self % rhs
1002 }
1003
1004 /// Wrapping (modular) negation. Computes `-self`, wrapping around at the
1005 /// boundary of the type.
1006 ///
1007 /// Since unsigned types do not have negative equivalents all applications
1008 /// of this function will wrap (except for `-0`). For values smaller than
1009 /// the corresponding signed type's maximum the result is the same as
1010 /// casting the corresponding signed value. Any larger values are equivalent
1011 /// to `MAX + 1 - (val - MAX - 1)` where `MAX` is the corresponding signed
1012 /// type's maximum.
1013 ///
1014 /// # Examples
1015 ///
1016 /// Basic usage:
1017 ///
1018 /// Please note that this example is shared between integer types.
1019 /// Which explains why `i8` is used here.
1020 ///
1021 /// ```
1022 /// # use ethnum::{U256, AsU256};
1023 /// assert_eq!(U256::new(100).wrapping_neg(), (-100i128).as_u256());
1024 /// assert_eq!(
1025 /// U256::from_words(i128::MIN as _, 0).wrapping_neg(),
1026 /// U256::from_words(i128::MIN as _, 0),
1027 /// );
1028 /// ```
1029 #[must_use = "this returns the result of the operation, \
1030 without modifying the original"]
1031 #[inline]
1032 pub fn wrapping_neg(self) -> Self {
1033 self.overflowing_neg().0
1034 }
1035
1036 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask`
1037 /// removes any high-order bits of `rhs` that would cause the shift to
1038 /// exceed the bitwidth of the type.
1039 ///
1040 /// Note that this is *not* the same as a rotate-left; the RHS of a wrapping
1041 /// shift-left is restricted to the range of the type, rather than the bits
1042 /// shifted out of the LHS being returned to the other end. The primitive
1043 /// integer types all implement a `rotate_left` function, which maybe what
1044 /// you want instead.
1045 ///
1046 /// # Examples
1047 ///
1048 /// Basic usage:
1049 ///
1050 /// ```
1051 /// # use ethnum::U256;
1052 /// assert_eq!(U256::new(1).wrapping_shl(7), U256::new(128));
1053 /// assert_eq!(U256::new(1).wrapping_shl(128), U256::from_words(1, 0));
1054 /// assert_eq!(U256::new(1).wrapping_shl(256), U256::new(1));
1055 /// ```
1056 #[must_use = "this returns the result of the operation, \
1057 without modifying the original"]
1058 #[inline(always)]
1059 pub fn wrapping_shl(self, rhs: u32) -> Self {
1060 let mut result = MaybeUninit::uninit();
1061 intrinsics::signed::ushl3(&mut result, &self, rhs & 0xff);
1062 unsafe { result.assume_init() }
1063 }
1064
1065 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1066 /// removes any high-order bits of `rhs` that would cause the shift to
1067 /// exceed the bitwidth of the type.
1068 ///
1069 /// Note that this is *not* the same as a rotate-right; the RHS of a
1070 /// wrapping shift-right is restricted to the range of the type, rather than
1071 /// the bits shifted out of the LHS being returned to the other end. The
1072 /// primitive integer types all implement a `rotate_right` function, which
1073 /// may be what you want instead.
1074 ///
1075 /// # Examples
1076 ///
1077 /// Basic usage:
1078 ///
1079 /// ```
1080 /// # use ethnum::U256;
1081 /// assert_eq!(U256::new(128).wrapping_shr(7), U256::new(1));
1082 /// assert_eq!(U256::from_words(128, 0).wrapping_shr(128), U256::new(128));
1083 /// assert_eq!(U256::new(128).wrapping_shr(256), U256::new(128));
1084 /// ```
1085 #[must_use = "this returns the result of the operation, \
1086 without modifying the original"]
1087 #[inline(always)]
1088 pub fn wrapping_shr(self, rhs: u32) -> Self {
1089 let mut result = MaybeUninit::uninit();
1090 intrinsics::signed::ushr3(&mut result, &self, rhs & 0xff);
1091 unsafe { result.assume_init() }
1092 }
1093
1094 /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`, wrapping
1095 /// around at the boundary of the type.
1096 ///
1097 /// # Examples
1098 ///
1099 /// Basic usage:
1100 ///
1101 /// ```
1102 /// # use ethnum::U256;
1103 /// assert_eq!(U256::new(3).wrapping_pow(5), U256::new(243));
1104 /// assert_eq!(
1105 /// U256::new(1337).wrapping_pow(42),
1106 /// U256::from_words(
1107 /// 45367329835866155830012179193722278514,
1108 /// 159264946433345088039815329994094210673,
1109 /// ),
1110 /// );
1111 /// ```
1112 #[must_use = "this returns the result of the operation, \
1113 without modifying the original"]
1114 #[inline]
1115 pub fn wrapping_pow(self, mut exp: u32) -> Self {
1116 let mut base = self;
1117 let mut acc = U256::ONE;
1118
1119 while exp > 1 {
1120 if (exp & 1) == 1 {
1121 acc = acc.wrapping_mul(base);
1122 }
1123 exp /= 2;
1124 base = base.wrapping_mul(base);
1125 }
1126
1127 // Deal with the final bit of the exponent separately, since
1128 // squaring the base afterwards is not necessary and may cause a
1129 // needless overflow.
1130 if exp == 1 {
1131 acc = acc.wrapping_mul(base);
1132 }
1133
1134 acc
1135 }
1136
1137 /// Calculates `self` + `rhs`
1138 ///
1139 /// Returns a tuple of the addition along with a boolean indicating whether
1140 /// an arithmetic overflow would occur. If an overflow would have occurred
1141 /// then the wrapped value is returned.
1142 ///
1143 /// # Examples
1144 ///
1145 /// Basic usage
1146 ///
1147 /// ```
1148 /// # use ethnum::U256;
1149 /// assert_eq!(U256::new(5).overflowing_add(U256::new(2)), (U256::new(7), false));
1150 /// assert_eq!(U256::MAX.overflowing_add(U256::new(1)), (U256::new(0), true));
1151 /// ```
1152 #[must_use = "this returns the result of the operation, \
1153 without modifying the original"]
1154 #[inline(always)]
1155 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1156 let mut result = MaybeUninit::uninit();
1157 let overflow = intrinsics::signed::uaddc(&mut result, &self, &rhs);
1158 (unsafe { result.assume_init() }, overflow)
1159 }
1160
1161 /// Calculates `self` + `rhs` with a signed `rhs`
1162 ///
1163 /// Returns a tuple of the addition along with a boolean indicating
1164 /// whether an arithmetic overflow would occur. If an overflow would
1165 /// have occurred then the wrapped value is returned.
1166 ///
1167 /// # Examples
1168 ///
1169 /// Basic usage:
1170 ///
1171 /// ```
1172 /// # use ethnum::{I256, U256};
1173 /// assert_eq!(U256::new(1).overflowing_add_signed(I256::new(2)), (U256::new(3), false));
1174 /// assert_eq!(U256::new(1).overflowing_add_signed(I256::new(-2)), (U256::MAX, true));
1175 /// assert_eq!((U256::MAX - 2).overflowing_add_signed(I256::new(4)), (U256::new(1), true));
1176 /// ```
1177 #[must_use = "this returns the result of the operation, \
1178 without modifying the original"]
1179 #[inline]
1180 pub fn overflowing_add_signed(self, rhs: I256) -> (Self, bool) {
1181 let (res, overflowed) = self.overflowing_add(rhs.as_u256());
1182 (res, overflowed ^ (rhs < 0))
1183 }
1184
1185 /// Calculates `self` - `rhs`
1186 ///
1187 /// Returns a tuple of the subtraction along with a boolean indicating
1188 /// whether an arithmetic overflow would occur. If an overflow would have
1189 /// occurred then the wrapped value is returned.
1190 ///
1191 /// # Examples
1192 ///
1193 /// Basic usage
1194 ///
1195 /// ```
1196 /// # use ethnum::U256;
1197 /// assert_eq!(U256::new(5).overflowing_sub(U256::new(2)), (U256::new(3), false));
1198 /// assert_eq!(U256::new(0).overflowing_sub(U256::new(1)), (U256::MAX, true));
1199 /// ```
1200 #[must_use = "this returns the result of the operation, \
1201 without modifying the original"]
1202 #[inline(always)]
1203 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1204 let mut result = MaybeUninit::uninit();
1205 let overflow = intrinsics::signed::usubc(&mut result, &self, &rhs);
1206 (unsafe { result.assume_init() }, overflow)
1207 }
1208
1209 /// Computes the absolute difference between `self` and `other`.
1210 ///
1211 /// # Examples
1212 ///
1213 /// Basic usage:
1214 ///
1215 /// ```
1216 /// # use ethnum::U256;
1217 /// assert_eq!(U256::new(100).abs_diff(U256::new(80)), 20);
1218 /// assert_eq!(U256::new(100).abs_diff(U256::new(110)), 10);
1219 /// ```
1220 #[must_use = "this returns the result of the operation, \
1221 without modifying the original"]
1222 #[inline]
1223 pub fn abs_diff(self, other: Self) -> Self {
1224 if self < other {
1225 other - self
1226 } else {
1227 self - other
1228 }
1229 }
1230
1231 /// Calculates the multiplication of `self` and `rhs`.
1232 ///
1233 /// Returns a tuple of the multiplication along with a boolean indicating
1234 /// whether an arithmetic overflow would occur. If an overflow would have
1235 /// occurred then the wrapped value is returned.
1236 ///
1237 /// # Examples
1238 ///
1239 /// Basic usage:
1240 ///
1241 /// Please note that this example is shared between integer types.
1242 /// Which explains why `u32` is used here.
1243 ///
1244 /// ```
1245 /// # use ethnum::U256;
1246 /// assert_eq!(U256::new(5).overflowing_mul(U256::new(2)), (U256::new(10), false));
1247 /// assert_eq!(
1248 /// U256::MAX.overflowing_mul(U256::new(2)),
1249 /// (U256::MAX - 1, true),
1250 /// );
1251 /// ```
1252 #[must_use = "this returns the result of the operation, \
1253 without modifying the original"]
1254 #[inline(always)]
1255 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1256 let mut result = MaybeUninit::uninit();
1257 let overflow = intrinsics::signed::umulc(&mut result, &self, &rhs);
1258 (unsafe { result.assume_init() }, overflow)
1259 }
1260
1261 /// Calculates the divisor when `self` is divided by `rhs`.
1262 ///
1263 /// Returns a tuple of the divisor along with a boolean indicating whether
1264 /// an arithmetic overflow would occur. Note that for unsigned integers
1265 /// overflow never occurs, so the second value is always `false`.
1266 ///
1267 /// # Panics
1268 ///
1269 /// This function will panic if `rhs` is 0.
1270 ///
1271 /// # Examples
1272 ///
1273 /// Basic usage
1274 ///
1275 /// ```
1276 /// # use ethnum::U256;
1277 /// assert_eq!(U256::new(5).overflowing_div(U256::new(2)), (U256::new(2), false));
1278 /// ```
1279 #[must_use = "this returns the result of the operation, \
1280 without modifying the original"]
1281 #[inline(always)]
1282 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1283 (self / rhs, false)
1284 }
1285
1286 /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
1287 ///
1288 /// Returns a tuple of the divisor along with a boolean indicating whether
1289 /// an arithmetic overflow would occur. Note that for unsigned integers
1290 /// overflow never occurs, so the second value is always `false`. Since,
1291 /// for the positive integers, all common definitions of division are equal,
1292 /// this is exactly equal to `self.overflowing_div(rhs)`.
1293 ///
1294 /// # Panics
1295 ///
1296 /// This function will panic if `rhs` is 0.
1297 ///
1298 /// # Examples
1299 ///
1300 /// Basic usage
1301 ///
1302 /// ```
1303 /// # use ethnum::U256;
1304 /// assert_eq!(U256::new(5).overflowing_div_euclid(U256::new(2)), (U256::new(2), false));
1305 /// ```
1306 #[must_use = "this returns the result of the operation, \
1307 without modifying the original"]
1308 #[inline(always)]
1309 pub fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
1310 (self / rhs, false)
1311 }
1312
1313 /// Calculates the remainder when `self` is divided by `rhs`.
1314 ///
1315 /// Returns a tuple of the remainder after dividing along with a boolean
1316 /// indicating whether an arithmetic overflow would occur. Note that for
1317 /// unsigned integers overflow never occurs, so the second value is always
1318 /// `false`.
1319 ///
1320 /// # Panics
1321 ///
1322 /// This function will panic if `rhs` is 0.
1323 ///
1324 /// # Examples
1325 ///
1326 /// Basic usage
1327 ///
1328 /// ```
1329 /// # use ethnum::U256;
1330 /// assert_eq!(U256::new(5).overflowing_rem(U256::new(2)), (U256::new(1), false));
1331 /// ```
1332 #[must_use = "this returns the result of the operation, \
1333 without modifying the original"]
1334 #[inline(always)]
1335 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1336 (self % rhs, false)
1337 }
1338
1339 /// Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean
1340 /// division.
1341 ///
1342 /// Returns a tuple of the modulo after dividing along with a boolean
1343 /// indicating whether an arithmetic overflow would occur. Note that for
1344 /// unsigned integers overflow never occurs, so the second value is always
1345 /// `false`. Since, for the positive integers, all common definitions of
1346 /// division are equal, this operation is exactly equal to
1347 /// `self.overflowing_rem(rhs)`.
1348 ///
1349 /// # Panics
1350 ///
1351 /// This function will panic if `rhs` is 0.
1352 ///
1353 /// # Examples
1354 ///
1355 /// Basic usage
1356 ///
1357 /// ```
1358 /// # use ethnum::U256;
1359 /// assert_eq!(U256::new(5).overflowing_rem_euclid(U256::new(2)), (U256::new(1), false));
1360 /// ```
1361 #[must_use = "this returns the result of the operation, \
1362 without modifying the original"]
1363 #[inline(always)]
1364 pub fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
1365 (self % rhs, false)
1366 }
1367
1368 /// Negates self in an overflowing fashion.
1369 ///
1370 /// Returns `!self + 1` using wrapping operations to return the value that
1371 /// represents the negation of this unsigned value. Note that for positive
1372 /// unsigned values overflow always occurs, but negating 0 does not
1373 /// overflow.
1374 ///
1375 /// # Examples
1376 ///
1377 /// Basic usage
1378 ///
1379 /// ```
1380 /// # use ethnum::{U256, AsU256};
1381 /// assert_eq!(U256::new(0).overflowing_neg(), (U256::new(0), false));
1382 /// assert_eq!(U256::new(2).overflowing_neg(), ((-2i32).as_u256(), true));
1383 /// ```
1384 #[inline]
1385 pub fn overflowing_neg(self) -> (Self, bool) {
1386 ((!self).wrapping_add(U256::ONE), self != U256::ZERO)
1387 }
1388
1389 /// Shifts self left by `rhs` bits.
1390 ///
1391 /// Returns a tuple of the shifted version of self along with a boolean
1392 /// indicating whether the shift value was larger than or equal to the
1393 /// number of bits. If the shift value is too large, then value is masked
1394 /// (N-1) where N is the number of bits, and this value is then used to
1395 /// perform the shift.
1396 ///
1397 /// # Examples
1398 ///
1399 /// Basic usage
1400 ///
1401 /// ```
1402 /// # use ethnum::U256;
1403 /// assert_eq!(U256::new(0x1).overflowing_shl(4), (U256::new(0x10), false));
1404 /// assert_eq!(U256::new(0x1).overflowing_shl(260), (U256::new(0x10), true));
1405 /// ```
1406 #[must_use = "this returns the result of the operation, \
1407 without modifying the original"]
1408 #[inline(always)]
1409 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1410 (self.wrapping_shl(rhs), rhs > 255)
1411 }
1412
1413 /// Shifts self right by `rhs` bits.
1414 ///
1415 /// Returns a tuple of the shifted version of self along with a boolean
1416 /// indicating whether the shift value was larger than or equal to the
1417 /// number of bits. If the shift value is too large, then value is masked
1418 /// (N-1) where N is the number of bits, and this value is then used to
1419 /// perform the shift.
1420 ///
1421 /// # Examples
1422 ///
1423 /// Basic usage
1424 ///
1425 /// ```
1426 /// # use ethnum::U256;
1427 /// assert_eq!(U256::new(0x10).overflowing_shr(4), (U256::new(0x1), false));
1428 /// assert_eq!(U256::new(0x10).overflowing_shr(260), (U256::new(0x1), true));
1429 /// ```
1430 #[must_use = "this returns the result of the operation, \
1431 without modifying the original"]
1432 #[inline(always)]
1433 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1434 (self.wrapping_shr(rhs), rhs > 255)
1435 }
1436
1437 /// Raises self to the power of `exp`, using exponentiation by squaring.
1438 ///
1439 /// Returns a tuple of the exponentiation along with a bool indicating
1440 /// whether an overflow happened.
1441 ///
1442 /// # Examples
1443 ///
1444 /// Basic usage:
1445 ///
1446 /// ```
1447 /// # use ethnum::U256;
1448 /// assert_eq!(U256::new(3).overflowing_pow(5), (U256::new(243), false));
1449 /// assert_eq!(
1450 /// U256::new(1337).overflowing_pow(42),
1451 /// (
1452 /// U256::from_words(
1453 /// 45367329835866155830012179193722278514,
1454 /// 159264946433345088039815329994094210673,
1455 /// ),
1456 /// true,
1457 /// )
1458 /// );
1459 /// ```
1460 #[must_use = "this returns the result of the operation, \
1461 without modifying the original"]
1462 #[inline]
1463 pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1464 let mut base = self;
1465 let mut acc = U256::ONE;
1466 let mut overflown = false;
1467 // Scratch space for storing results of overflowing_mul.
1468 let mut r;
1469
1470 while exp > 1 {
1471 if (exp & 1) == 1 {
1472 r = acc.overflowing_mul(base);
1473 acc = r.0;
1474 overflown |= r.1;
1475 }
1476 exp /= 2;
1477 r = base.overflowing_mul(base);
1478 base = r.0;
1479 overflown |= r.1;
1480 }
1481
1482 // Deal with the final bit of the exponent separately, since
1483 // squaring the base afterwards is not necessary and may cause a
1484 // needless overflow.
1485 if exp == 1 {
1486 r = acc.overflowing_mul(base);
1487 acc = r.0;
1488 overflown |= r.1;
1489 }
1490
1491 (acc, overflown)
1492 }
1493
1494 /// Raises self to the power of `exp`, using exponentiation by squaring.
1495 ///
1496 /// # Examples
1497 ///
1498 /// Basic usage:
1499 ///
1500 /// ```
1501 /// # use ethnum::U256;
1502 /// assert_eq!(U256::new(2).pow(5), U256::new(32));
1503 /// ```
1504 #[must_use = "this returns the result of the operation, \
1505 without modifying the original"]
1506 #[inline]
1507 pub fn pow(self, mut exp: u32) -> Self {
1508 let mut base = self;
1509 let mut acc = U256::ONE;
1510
1511 while exp > 1 {
1512 if (exp & 1) == 1 {
1513 acc *= base;
1514 }
1515 exp /= 2;
1516 base = base * base;
1517 }
1518
1519 // Deal with the final bit of the exponent separately, since
1520 // squaring the base afterwards is not necessary and may cause a
1521 // needless overflow.
1522 if exp == 1 {
1523 acc *= base;
1524 }
1525
1526 acc
1527 }
1528
1529 /// Performs Euclidean division.
1530 ///
1531 /// Since, for the positive integers, all common definitions of division are
1532 /// equal, this is exactly equal to `self / rhs`.
1533 ///
1534 /// # Panics
1535 ///
1536 /// This function will panic if `rhs` is 0.
1537 ///
1538 /// # Examples
1539 ///
1540 /// Basic usage:
1541 ///
1542 /// ```
1543 /// # use ethnum::U256;
1544 /// assert_eq!(U256::new(7).div_euclid(U256::new(4)), U256::new(1));
1545 /// ```
1546 #[must_use = "this returns the result of the operation, \
1547 without modifying the original"]
1548 #[inline(always)]
1549 pub fn div_euclid(self, rhs: Self) -> Self {
1550 self / rhs
1551 }
1552
1553 /// Calculates the least remainder of `self (mod rhs)`.
1554 ///
1555 /// Since, for the positive integers, all common definitions of division are
1556 /// equal, this is exactly equal to `self % rhs`.
1557 ///
1558 /// # Panics
1559 ///
1560 /// This function will panic if `rhs` is 0.
1561 ///
1562 /// # Examples
1563 ///
1564 /// Basic usage:
1565 ///
1566 /// ```
1567 /// # use ethnum::U256;
1568 /// assert_eq!(U256::new(7).rem_euclid(U256::new(4)), U256::new(3));
1569 /// ```
1570 #[must_use = "this returns the result of the operation, \
1571 without modifying the original"]
1572 #[inline(always)]
1573 pub fn rem_euclid(self, rhs: Self) -> Self {
1574 self % rhs
1575 }
1576
1577 /// Returns `true` if and only if `self == 2^k` for some `k`.
1578 ///
1579 /// # Examples
1580 ///
1581 /// Basic usage:
1582 ///
1583 /// ```
1584 /// # use ethnum::U256;
1585 /// assert!(U256::new(16).is_power_of_two());
1586 /// assert!(!U256::new(10).is_power_of_two());
1587 /// ```
1588 #[inline]
1589 pub fn is_power_of_two(self) -> bool {
1590 self.count_ones() == 1
1591 }
1592
1593 /// Returns one less than next power of two. (For 8u8 next power of two is
1594 /// 8u8 and for 6u8 it is 8u8).
1595 ///
1596 /// 8u8.one_less_than_next_power_of_two() == 7
1597 /// 6u8.one_less_than_next_power_of_two() == 7
1598 ///
1599 /// This method cannot overflow, as in the `next_power_of_two` overflow
1600 /// cases it instead ends up returning the maximum value of the type, and
1601 /// can return 0 for 0.
1602 #[inline]
1603 fn one_less_than_next_power_of_two(self) -> Self {
1604 if self <= 1 {
1605 return U256::ZERO;
1606 }
1607
1608 let p = self - 1;
1609 let z = p.leading_zeros();
1610 U256::MAX >> z
1611 }
1612
1613 /// Returns the smallest power of two greater than or equal to `self`.
1614 ///
1615 /// When return value overflows (i.e., `self > (1 << (N-1))` for type `uN`),
1616 /// it panics in debug mode and return value is wrapped to 0 in release mode
1617 /// (the only situation in which method can return 0).
1618 ///
1619 /// # Examples
1620 ///
1621 /// Basic usage:
1622 ///
1623 /// ```
1624 /// # use ethnum::U256;
1625 /// assert_eq!(U256::new(2).next_power_of_two(), U256::new(2));
1626 /// assert_eq!(U256::new(3).next_power_of_two(), U256::new(4));
1627 /// ```
1628 #[inline]
1629 pub fn next_power_of_two(self) -> Self {
1630 self.one_less_than_next_power_of_two() + 1
1631 }
1632
1633 /// Returns the smallest power of two greater than or equal to `n`. If the
1634 /// next power of two is greater than the type's maximum value, `None` is
1635 /// returned, otherwise the power of two is wrapped in `Some`.
1636 ///
1637 /// # Examples
1638 ///
1639 /// Basic usage:
1640 ///
1641 /// ```
1642 /// # use ethnum::U256;
1643 /// assert_eq!(U256::new(2).checked_next_power_of_two(), Some(U256::new(2)));
1644 /// assert_eq!(U256::new(3).checked_next_power_of_two(), Some(U256::new(4)));
1645 /// assert_eq!(U256::MAX.checked_next_power_of_two(), None);
1646 /// ```
1647 #[inline]
1648 pub fn checked_next_power_of_two(self) -> Option<Self> {
1649 self.one_less_than_next_power_of_two()
1650 .checked_add(U256::ONE)
1651 }
1652
1653 /// Return the memory representation of this integer as a byte array in big
1654 /// endian (network) byte order.
1655 ///
1656 /// # Examples
1657 ///
1658 /// ```
1659 /// # use ethnum::U256;
1660 /// let bytes = U256::from_words(
1661 /// 0x00010203_04050607_08090a0b_0c0d0e0f,
1662 /// 0x10111213_14151617_18191a1b_1c1d1e1f,
1663 /// );
1664 /// assert_eq!(
1665 /// bytes.to_be_bytes(),
1666 /// [
1667 /// 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
1668 /// 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
1669 /// ],
1670 /// );
1671 /// ```
1672 #[inline]
1673 pub fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
1674 self.to_be().to_ne_bytes()
1675 }
1676
1677 /// Return the memory representation of this integer as a byte array in
1678 /// little endian byte order.
1679 ///
1680 /// # Examples
1681 ///
1682 /// ```
1683 /// # use ethnum::U256;
1684 /// let bytes = U256::from_words(
1685 /// 0x00010203_04050607_08090a0b_0c0d0e0f,
1686 /// 0x10111213_14151617_18191a1b_1c1d1e1f,
1687 /// );
1688 /// assert_eq!(
1689 /// bytes.to_le_bytes(),
1690 /// [
1691 /// 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10,
1692 /// 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00,
1693 /// ],
1694 /// );
1695 /// ```
1696 #[inline]
1697 pub fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
1698 self.to_le().to_ne_bytes()
1699 }
1700
1701 /// Return the memory representation of this integer as a byte array in
1702 /// native byte order.
1703 ///
1704 /// As the target platform's native endianness is used, portable code should
1705 /// use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, instead.
1706 ///
1707 /// [`to_be_bytes`]: #method.to_be_bytes
1708 /// [`to_le_bytes`]: #method.to_le_bytes
1709 ///
1710 /// # Examples
1711 ///
1712 /// ```
1713 /// # use ethnum::U256;
1714 /// let bytes = U256::from_words(
1715 /// 0x00010203_04050607_08090a0b_0c0d0e0f,
1716 /// 0x10111213_14151617_18191a1b_1c1d1e1f,
1717 /// );
1718 /// assert_eq!(
1719 /// bytes.to_ne_bytes(),
1720 /// if cfg!(target_endian = "big") {
1721 /// [
1722 /// 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
1723 /// 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
1724 /// ]
1725 /// } else {
1726 /// [
1727 /// 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10,
1728 /// 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00,
1729 /// ]
1730 /// }
1731 /// );
1732 /// ```
1733 #[inline]
1734 pub fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
1735 unsafe { mem::transmute(self) }
1736 }
1737
1738 /// Create an integer value from its representation as a byte array in big
1739 /// endian.
1740 ///
1741 /// # Examples
1742 ///
1743 /// ```
1744 /// # use ethnum::U256;
1745 /// let value = U256::from_be_bytes([
1746 /// 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
1747 /// 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
1748 /// ]);
1749 /// assert_eq!(
1750 /// value,
1751 /// U256::from_words(
1752 /// 0x00010203_04050607_08090a0b_0c0d0e0f,
1753 /// 0x10111213_14151617_18191a1b_1c1d1e1f,
1754 /// ),
1755 /// );
1756 /// ```
1757 ///
1758 /// When starting from a slice rather than an array, fallible conversion
1759 /// APIs can be used:
1760 ///
1761 /// ```
1762 /// # use ethnum::U256;
1763 /// use std::convert::TryInto;
1764 ///
1765 /// fn read_be_u256(input: &mut &[u8]) -> U256 {
1766 /// let (int_bytes, rest) = input.split_at(std::mem::size_of::<U256>());
1767 /// *input = rest;
1768 /// U256::from_be_bytes(int_bytes.try_into().unwrap())
1769 /// }
1770 /// ```
1771 #[inline]
1772 pub fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
1773 Self::from_be(Self::from_ne_bytes(bytes))
1774 }
1775
1776 /// Create an integer value from its representation as a byte array in
1777 /// little endian.
1778 ///
1779 /// # Examples
1780 ///
1781 /// ```
1782 /// # use ethnum::U256;
1783 /// let value = U256::from_le_bytes([
1784 /// 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10,
1785 /// 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00,
1786 /// ]);
1787 /// assert_eq!(
1788 /// value,
1789 /// U256::from_words(
1790 /// 0x00010203_04050607_08090a0b_0c0d0e0f,
1791 /// 0x10111213_14151617_18191a1b_1c1d1e1f,
1792 /// ),
1793 /// );
1794 /// ```
1795 ///
1796 /// When starting from a slice rather than an array, fallible conversion
1797 /// APIs can be used:
1798 ///
1799 /// ```
1800 /// # use ethnum::U256;
1801 /// use std::convert::TryInto;
1802 ///
1803 /// fn read_be_u256(input: &mut &[u8]) -> U256 {
1804 /// let (int_bytes, rest) = input.split_at(std::mem::size_of::<U256>());
1805 /// *input = rest;
1806 /// U256::from_le_bytes(int_bytes.try_into().unwrap())
1807 /// }
1808 /// ```
1809 #[inline]
1810 pub fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
1811 Self::from_le(Self::from_ne_bytes(bytes))
1812 }
1813
1814 /// Create an integer value from its memory representation as a byte array
1815 /// in native endianness.
1816 ///
1817 /// As the target platform's native endianness is used, portable code likely
1818 /// wants to use [`from_be_bytes`] or [`from_le_bytes`], as appropriate
1819 /// instead.
1820 ///
1821 /// [`from_be_bytes`]: #method.from_be_bytes
1822 /// [`from_le_bytes`]: #method.from_le_bytes
1823 ///
1824 /// # Examples
1825 ///
1826 /// ```
1827 /// # use ethnum::U256;
1828 /// let value = U256::from_ne_bytes(if cfg!(target_endian = "big") {
1829 /// [
1830 /// 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
1831 /// 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
1832 /// ]
1833 /// } else {
1834 /// [
1835 /// 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10,
1836 /// 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00,
1837 /// ]
1838 /// });
1839 /// assert_eq!(
1840 /// value,
1841 /// U256::from_words(
1842 /// 0x00010203_04050607_08090a0b_0c0d0e0f,
1843 /// 0x10111213_14151617_18191a1b_1c1d1e1f,
1844 /// ),
1845 /// );
1846 /// ```
1847 ///
1848 /// When starting from a slice rather than an array, fallible conversion
1849 /// APIs can be used:
1850 ///
1851 /// ```
1852 /// # use ethnum::U256;
1853 /// use std::convert::TryInto;
1854 ///
1855 /// fn read_be_u256(input: &mut &[u8]) -> U256 {
1856 /// let (int_bytes, rest) = input.split_at(std::mem::size_of::<U256>());
1857 /// *input = rest;
1858 /// U256::from_ne_bytes(int_bytes.try_into().unwrap())
1859 /// }
1860 /// ```
1861 #[inline]
1862 pub fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
1863 unsafe { mem::transmute(bytes) }
1864 }
1865}