1use core::{str, mem};
33use core::ops::{Shr, Shl, BitAnd, BitOr, BitXor, Not, Div, Rem, Mul, Add, Sub};
34
35use byteorder::{ByteOrder, BigEndian, LittleEndian};
36
37#[derive(Debug, PartialEq)]
39pub enum FromDecStrErr {
40 InvalidCharacter,
42 InvalidLength,
44}
45
46macro_rules! impl_map_from {
47 ($thing:ident, $from:ty, $to:ty) => {
48 impl From<$from> for $thing {
49 fn from(value: $from) -> $thing {
50 From::from(value as $to)
51 }
52 }
53 }
54}
55
56macro_rules! uint_overflowing_add {
57 ($name:ident, $n_words:tt, $self_expr: expr, $other: expr) => ({
58 uint_overflowing_add_reg!($name, $n_words, $self_expr, $other)
59 })
60}
61
62macro_rules! uint_overflowing_add_reg {
63 ($name:ident, $n_words:tt, $self_expr: expr, $other: expr) => ({
64 uint_overflowing_binop!(
65 $name,
66 $n_words,
67 $self_expr,
68 $other,
69 u64::overflowing_add
70 )
71 })
72}
73
74macro_rules! uint_overflowing_sub {
75 ($name:ident, $n_words:tt, $self_expr: expr, $other: expr) => ({
76 uint_overflowing_sub_reg!($name, $n_words, $self_expr, $other)
77 })
78}
79
80macro_rules! uint_overflowing_binop {
81 ($name:ident, $n_words:tt, $self_expr: expr, $other: expr, $fn:expr) => ({
82 let $name(ref me) = $self_expr;
83 let $name(ref you) = $other;
84
85 let mut ret = unsafe { ::core::mem::uninitialized() };
86 let ret_ptr = &mut ret as *mut [u64; $n_words] as *mut u64;
87 let mut carry = 0u64;
88
89 unroll! {
90 for i in 0..$n_words {
91 use ::core::ptr;
92
93 if carry != 0 {
94 let (res1, overflow1) = ($fn)(me[i], you[i]);
95 let (res2, overflow2) = ($fn)(res1, carry);
96
97 unsafe {
98 ptr::write(
99 ret_ptr.offset(i as _),
100 res2
101 );
102 }
103 carry = (overflow1 as u8 + overflow2 as u8) as u64;
104 } else {
105 let (res, overflow) = ($fn)(me[i], you[i]);
106
107 unsafe {
108 ptr::write(
109 ret_ptr.offset(i as _),
110 res
111 );
112 }
113
114 carry = overflow as u64;
115 }
116 }
117 }
118
119 ($name(ret), carry > 0)
120 })
121}
122
123macro_rules! uint_overflowing_sub_reg {
124 ($name:ident, $n_words:tt, $self_expr: expr, $other: expr) => ({
125 uint_overflowing_binop!(
126 $name,
127 $n_words,
128 $self_expr,
129 $other,
130 u64::overflowing_sub
131 )
132 })
133}
134
135macro_rules! uint_overflowing_mul {
136 ($name:ident, $n_words:tt, $self_expr: expr, $other: expr) => ({
137 uint_overflowing_mul_reg!($name, $n_words, $self_expr, $other)
138 })
139}
140
141macro_rules! uint_full_mul_reg {
142 ($name:ident, 8, $self_expr:expr, $other:expr) => {
143 uint_full_mul_reg!($name, 8, $self_expr, $other, |a, b| a != 0 || b != 0);
144 };
145 ($name:ident, $n_words:tt, $self_expr:expr, $other:expr) => {
146 uint_full_mul_reg!($name, $n_words, $self_expr, $other, |_, _| true);
147 };
148 ($name:ident, $n_words:tt, $self_expr:expr, $other:expr, $check:expr) => ({{
149 #![allow(unused_assignments)]
150
151 let $name(ref me) = $self_expr;
152 let $name(ref you) = $other;
153 let mut ret = [0u64; $n_words * 2];
154
155 unroll! {
156 for i in 0..$n_words {
157 let mut carry = 0u64;
158 let b = you[i];
159
160 unroll! {
161 for j in 0..$n_words {
162 if $check(me[j], carry) {
163 let a = me[j];
164
165 let (hi, low) = split_u128(a as u128 * b as u128);
166
167 let overflow = {
168 let existing_low = &mut ret[i + j];
169 let (low, o) = low.overflowing_add(*existing_low);
170 *existing_low = low;
171 o
172 };
173
174 carry = {
175 let existing_hi = &mut ret[i + j + 1];
176 let hi = hi + overflow as u64;
177 let (hi, o0) = hi.overflowing_add(carry);
178 let (hi, o1) = hi.overflowing_add(*existing_hi);
179 *existing_hi = hi;
180
181 (o0 | o1) as u64
182 }
183 }
184 }
185 }
186 }
187 }
188
189 ret
190 }});
191}
192
193macro_rules! uint_overflowing_mul_reg {
194 ($name:ident, $n_words:tt, $self_expr: expr, $other: expr) => ({
195 let ret: [u64; $n_words * 2] = uint_full_mul_reg!($name, $n_words, $self_expr, $other);
196
197 let ret: [[u64; $n_words]; 2] = unsafe { mem::transmute(ret) };
199
200 #[inline(always)]
202 fn any_nonzero(arr: &[u64; $n_words]) -> bool {
203 unroll! {
204 for i in 0..$n_words {
205 if arr[i] != 0 {
206 return true;
207 }
208 }
209 }
210
211 false
212 }
213
214 ($name(ret[0]), any_nonzero(&ret[1]))
215 })
216}
217
218macro_rules! overflowing {
219 ($op: expr, $overflow: expr) => (
220 {
221 let (overflow_x, overflow_overflow) = $op;
222 $overflow |= overflow_overflow;
223 overflow_x
224 }
225 );
226 ($op: expr) => (
227 {
228 let (overflow_x, _overflow_overflow) = $op;
229 overflow_x
230 }
231 );
232}
233
234macro_rules! panic_on_overflow {
235 ($name: expr) => {
236 if $name {
237 panic!("arithmetic operation overflow")
238 }
239 }
240}
241
242#[inline(always)]
243fn mul_u32(a: (u64, u64), b: u64, carry: u64) -> (u64, u64) {
244 let upper = b * a.0;
245 let lower = b * a.1;
246
247 let (res1, overflow1) = lower.overflowing_add(upper << 32);
248 let (res2, overflow2) = res1.overflowing_add(carry);
249
250 let carry = (upper >> 32) + overflow1 as u64 + overflow2 as u64;
251 (res2, carry)
252}
253
254#[inline(always)]
255fn split(a: u64) -> (u64, u64) {
256 (a >> 32, a & 0xFFFFFFFF)
257}
258
259#[inline(always)]
260fn split_u128(a: u128) -> (u64, u64) {
261 ((a >> 64) as _, (a & 0xFFFFFFFFFFFFFFFF) as _)
262}
263
264macro_rules! construct_uint {
265 ($name:ident, $n_words:tt) => (
266 #[repr(C)]
268 #[derive(Copy, Clone, Eq, PartialEq, Hash)]
269 #[cfg_attr(feature="serialize", derive(Serialize, Deserialize))]
270 pub struct $name(pub [u64; $n_words]);
271
272 impl $name {
273 pub const MAX: $name = $name([u64::max_value(); $n_words]);
274
275 pub fn from_dec_str(value: &str) -> Result<Self, FromDecStrErr> {
277 if !value.bytes().all(|b| b >= 48 && b <= 57) {
278 return Err(FromDecStrErr::InvalidCharacter)
279 }
280
281 let mut res = Self::default();
282 for b in value.bytes().map(|b| b - 48) {
283 let (r, overflow) = res.overflowing_mul_u32(10);
284 if overflow {
285 return Err(FromDecStrErr::InvalidLength);
286 }
287 let (r, overflow) = r.overflowing_add(b.into());
288 if overflow {
289 return Err(FromDecStrErr::InvalidLength);
290 }
291 res = r;
292 }
293 Ok(res)
294 }
295
296 #[inline]
298 pub fn low_u32(&self) -> u32 {
299 let &$name(ref arr) = self;
300 arr[0] as u32
301 }
302
303 #[inline]
305 pub fn low_u64(&self) -> u64 {
306 let &$name(ref arr) = self;
307 arr[0]
308 }
309
310 #[inline]
316 pub fn as_u32(&self) -> u32 {
317 let &$name(ref arr) = self;
318 if (arr[0] & (0xffffffffu64 << 32)) != 0 {
319 panic!("Integer overflow when casting U256")
320 }
321 self.as_u64() as u32
322 }
323
324 #[inline]
330 pub fn as_u64(&self) -> u64 {
331 let &$name(ref arr) = self;
332 for i in 1..$n_words {
333 if arr[i] != 0 {
334 panic!("Integer overflow when casting U256")
335 }
336 }
337 arr[0]
338 }
339
340 #[inline]
342 pub fn is_zero(&self) -> bool {
343 let &$name(ref arr) = self;
344 for i in 0..$n_words { if arr[i] != 0 { return false; } }
345 return true;
346 }
347
348 #[inline]
350 pub fn bits(&self) -> usize {
351 let &$name(ref arr) = self;
352 for i in 1..$n_words {
353 if arr[$n_words - i] > 0 { return (0x40 * ($n_words - i + 1)) - arr[$n_words - i].leading_zeros() as usize; }
354 }
355 0x40 - arr[0].leading_zeros() as usize
356 }
357
358 #[inline]
364 pub fn bit(&self, index: usize) -> bool {
365 let &$name(ref arr) = self;
366 arr[index / 64] & (1 << (index % 64)) != 0
367 }
368
369 pub fn leading_zeros(&self) -> u32 {
371 let mut r = 0;
372 for i in 0..$n_words {
373 let w = self.0[$n_words - i - 1];
374 if w == 0 {
375 r += 64;
376 } else {
377 r += w.leading_zeros();
378 break;
379 }
380 }
381 r
382 }
383
384 pub fn trailing_zeros(&self) -> u32 {
386 let mut r = 0;
387 for i in 0..$n_words {
388 let w = self.0[i];
389 if w == 0 {
390 r += 64;
391 } else {
392 r += w.trailing_zeros();
393 break;
394 }
395 }
396 r
397 }
398
399 #[inline]
405 pub fn byte(&self, index: usize) -> u8 {
406 let &$name(ref arr) = self;
407 (arr[index / 8] >> (((index % 8)) * 8)) as u8
408 }
409
410 #[inline]
412 pub fn to_big_endian(&self, bytes: &mut [u8]) {
413 debug_assert!($n_words * 8 == bytes.len());
414 for i in 0..$n_words {
415 BigEndian::write_u64(&mut bytes[8 * i..], self.0[$n_words - i - 1]);
416 }
417 }
418
419 #[inline]
421 pub fn to_little_endian(&self, bytes: &mut [u8]) {
422 debug_assert!($n_words * 8 == bytes.len());
423 for i in 0..$n_words {
424 LittleEndian::write_u64(&mut bytes[8 * i..], self.0[i]);
425 }
426 }
427
428 #[cfg(feature="std")]
430 #[inline]
431 pub fn to_hex(&self) -> String {
432 use core::cmp;
433 use rustc_hex::ToHex;;
434
435 if self.is_zero() { return "0".to_owned(); } let mut bytes = [0u8; 8 * $n_words];
437 self.to_big_endian(&mut bytes);
438 let bp7 = self.bits() + 7;
439 let len = cmp::max(bp7 / 8, 1);
440 let bytes_hex = bytes[bytes.len() - len..].to_hex();
441 (&bytes_hex[1 - bp7 % 8 / 4..]).to_owned()
442 }
443
444 #[inline]
450 pub fn exp10(n: usize) -> Self {
451 match n {
452 0 => Self::from(1u64),
453 _ => Self::exp10(n - 1).mul_u32(10)
454 }
455 }
456
457 #[inline]
459 pub fn zero() -> Self {
460 From::from(0u64)
461 }
462
463 #[inline]
465 pub fn one() -> Self {
466 From::from(1u64)
467 }
468
469 #[inline]
471 pub fn max_value() -> Self {
472 let mut result = [0; $n_words];
473 for i in 0..$n_words {
474 result[i] = u64::max_value();
475 }
476 $name(result)
477 }
478
479 pub fn pow(self, expon: Self) -> Self {
486 if expon.is_zero() {
487 return Self::one()
488 }
489 let is_even = |x : &Self| x.low_u64() & 1 == 0;
490
491 let u_one = Self::one();
492 let mut y = u_one;
493 let mut n = expon;
494 let mut x = self;
495 while n > u_one {
496 if is_even(&n) {
497 x = x * x;
498 n = n >> 1;
499 } else {
500 y = x * y;
501 x = x * x;
502 n.0[$n_words-1] = n.0[$n_words-1] & ((!0u64)>>1);
504 n = n >> 1;
505 }
506 }
507 x * y
508 }
509
510 pub fn overflowing_pow(self, expon: Self) -> (Self, bool) {
513 if expon.is_zero() { return (Self::one(), false) }
514
515 let is_even = |x : &Self| x.low_u64() & 1 == 0;
516
517 let u_one = Self::one();
518 let mut y = u_one;
519 let mut n = expon;
520 let mut x = self;
521 let mut overflow = false;
522
523 while n > u_one {
524 if is_even(&n) {
525 x = overflowing!(x.overflowing_mul(x), overflow);
526 n = n >> 1;
527 } else {
528 y = overflowing!(x.overflowing_mul(y), overflow);
529 x = overflowing!(x.overflowing_mul(x), overflow);
530 n = (n - u_one) >> 1;
531 }
532 }
533 let res = overflowing!(x.overflowing_mul(y), overflow);
534 (res, overflow)
535 }
536
537 #[inline(always)]
539 pub fn overflowing_add(self, other: $name) -> ($name, bool) {
540 uint_overflowing_add!($name, $n_words, self, other)
541 }
542
543 pub fn saturating_add(self, other: $name) -> $name {
545 match self.overflowing_add(other) {
546 (_, true) => $name::max_value(),
547 (val, false) => val,
548 }
549 }
550
551 #[inline(always)]
553 pub fn overflowing_sub(self, other: $name) -> ($name, bool) {
554 uint_overflowing_sub!($name, $n_words, self, other)
555 }
556
557 pub fn saturating_sub(self, other: $name) -> $name {
559 match self.overflowing_sub(other) {
560 (_, true) => $name::zero(),
561 (val, false) => val,
562 }
563 }
564
565 #[inline(always)]
567 pub fn overflowing_mul(self, other: $name) -> ($name, bool) {
568 uint_overflowing_mul!($name, $n_words, self, other)
569 }
570
571 pub fn saturating_mul(self, other: $name) -> $name {
573 match self.overflowing_mul(other) {
574 (_, true) => $name::max_value(),
575 (val, false) => val,
576 }
577 }
578
579 pub fn overflowing_div(self, other: $name) -> ($name, bool) {
581 (self / other, false)
582 }
583
584 pub fn overflowing_rem(self, other: $name) -> ($name, bool) {
586 (self % other, false)
587 }
588
589 pub fn overflowing_neg(self) -> ($name, bool) {
591 (!self, true)
592 }
593
594 #[allow(dead_code)] fn mul_u32(self, other: u32) -> Self {
597 let (ret, overflow) = self.overflowing_mul_u32(other);
598 panic_on_overflow!(overflow);
599 ret
600 }
601
602 #[allow(dead_code)] fn overflowing_mul_u32(self, other: u32) -> (Self, bool) {
605 let $name(ref arr) = self;
606 let mut ret = [0u64; $n_words];
607 let mut carry = 0;
608 let o = other as u64;
609
610 for i in 0..$n_words {
611 let (res, carry2) = mul_u32(split(arr[i]), o, carry);
612 ret[i] = res;
613 carry = carry2;
614 }
615
616 ($name(ret), carry > 0)
617 }
618
619 pub fn from_big_endian(slice: &[u8]) -> Self {
623 assert!($n_words * 8 >= slice.len());
624
625 let mut ret = [0; $n_words];
626 unsafe {
627 let ret_u8: &mut [u8; $n_words * 8] = mem::transmute(&mut ret);
628 let mut ret_ptr = ret_u8.as_mut_ptr();
629 let mut slice_ptr = slice.as_ptr().offset(slice.len() as isize - 1);
630 for _ in 0..slice.len() {
631 *ret_ptr = *slice_ptr;
632 ret_ptr = ret_ptr.offset(1);
633 slice_ptr = slice_ptr.offset(-1);
634 }
635 }
636
637 $name(ret)
638 }
639
640 pub fn from_little_endian(slice: &[u8]) -> Self {
642 assert!($n_words * 8 >= slice.len());
643
644 let mut ret = [0; $n_words];
645 unsafe {
646 let ret_u8: &mut [u8; $n_words * 8] = mem::transmute(&mut ret);
647 ret_u8[0..slice.len()].copy_from_slice(&slice);
648 }
649
650 $name(ret)
651 }
652 }
653
654 impl Default for $name {
655 fn default() -> Self {
656 $name::zero()
657 }
658 }
659
660 impl From<u64> for $name {
661 fn from(value: u64) -> $name {
662 let mut ret = [0; $n_words];
663 ret[0] = value;
664 $name(ret)
665 }
666 }
667
668
669 impl_map_from!($name, u8, u64);
670 impl_map_from!($name, u16, u64);
671 impl_map_from!($name, u32, u64);
672 impl_map_from!($name, usize, u64);
673
674 impl From<i64> for $name {
675 fn from(value: i64) -> $name {
676 match value >= 0 {
677 true => From::from(value as u64),
678 false => { panic!("Unsigned integer can't be created from negative value"); }
679 }
680 }
681 }
682
683 impl_map_from!($name, i8, i64);
684 impl_map_from!($name, i16, i64);
685 impl_map_from!($name, i32, i64);
686 impl_map_from!($name, isize, i64);
687
688 impl<'a> From<&'a [u8]> for $name {
690 fn from(bytes: &[u8]) -> $name {
691 Self::from_big_endian(bytes)
692 }
693 }
694
695 #[cfg(feature="std")]
696 impl str::FromStr for $name {
697 type Err = ::rustc_hex::FromHexError;
698
699 fn from_str(value: &str) -> Result<$name, Self::Err> {
700 use rustc_hex::FromHex;
701
702 let bytes: Vec<u8> = match value.len() % 2 == 0 {
703 true => try!(value.from_hex()),
704 false => try!(("0".to_owned() + value).from_hex())
705 };
706
707 let bytes_ref: &[u8] = &bytes;
708 Ok(From::from(bytes_ref))
709 }
710 }
711
712 impl Add<$name> for $name {
713 type Output = $name;
714
715 fn add(self, other: $name) -> $name {
716 let (result, overflow) = self.overflowing_add(other);
717 panic_on_overflow!(overflow);
718 result
719 }
720 }
721
722 impl Sub<$name> for $name {
723 type Output = $name;
724
725 #[inline]
726 fn sub(self, other: $name) -> $name {
727 let (result, overflow) = self.overflowing_sub(other);
728 panic_on_overflow!(overflow);
729 result
730 }
731 }
732
733 impl Mul<$name> for $name {
734 type Output = $name;
735
736 fn mul(self, other: $name) -> $name {
737 let (result, overflow) = self.overflowing_mul(other);
738 panic_on_overflow!(overflow);
739 result
740 }
741 }
742
743 impl Div<$name> for $name {
744 type Output = $name;
745
746 fn div(self, other: $name) -> $name {
747 let mut sub_copy = self;
748 let mut shift_copy = other;
749 let mut ret = [0u64; $n_words];
750
751 let my_bits = self.bits();
752 let your_bits = other.bits();
753
754 assert!(your_bits != 0);
756
757 if my_bits < your_bits {
759 return $name(ret);
760 }
761
762 let mut shift = my_bits - your_bits;
764 shift_copy = shift_copy << shift;
765 loop {
766 if sub_copy >= shift_copy {
767 ret[shift / 64] |= 1 << (shift % 64);
768 sub_copy = overflowing!(sub_copy.overflowing_sub(shift_copy));
769 }
770 shift_copy = shift_copy >> 1;
771 if shift == 0 { break; }
772 shift -= 1;
773 }
774
775 $name(ret)
776 }
777 }
778
779 impl Rem<$name> for $name {
780 type Output = $name;
781
782 fn rem(self, other: $name) -> $name {
783 let times = self / other;
784 self - (times * other)
785 }
786 }
787
788 impl BitAnd<$name> for $name {
789 type Output = $name;
790
791 #[inline]
792 fn bitand(self, other: $name) -> $name {
793 let $name(ref arr1) = self;
794 let $name(ref arr2) = other;
795 let mut ret = [0u64; $n_words];
796 for i in 0..$n_words {
797 ret[i] = arr1[i] & arr2[i];
798 }
799 $name(ret)
800 }
801 }
802
803 impl BitXor<$name> for $name {
804 type Output = $name;
805
806 #[inline]
807 fn bitxor(self, other: $name) -> $name {
808 let $name(ref arr1) = self;
809 let $name(ref arr2) = other;
810 let mut ret = [0u64; $n_words];
811 for i in 0..$n_words {
812 ret[i] = arr1[i] ^ arr2[i];
813 }
814 $name(ret)
815 }
816 }
817
818 impl BitOr<$name> for $name {
819 type Output = $name;
820
821 #[inline]
822 fn bitor(self, other: $name) -> $name {
823 let $name(ref arr1) = self;
824 let $name(ref arr2) = other;
825 let mut ret = [0u64; $n_words];
826 for i in 0..$n_words {
827 ret[i] = arr1[i] | arr2[i];
828 }
829 $name(ret)
830 }
831 }
832
833 impl Not for $name {
834 type Output = $name;
835
836 #[inline]
837 fn not(self) -> $name {
838 let $name(ref arr) = self;
839 let mut ret = [0u64; $n_words];
840 for i in 0..$n_words {
841 ret[i] = !arr[i];
842 }
843 $name(ret)
844 }
845 }
846
847 impl Shl<usize> for $name {
848 type Output = $name;
849
850 fn shl(self, shift: usize) -> $name {
851 let $name(ref original) = self;
852 let mut ret = [0u64; $n_words];
853 let word_shift = shift / 64;
854 let bit_shift = shift % 64;
855
856 for i in word_shift..$n_words {
858 ret[i] = original[i - word_shift] << bit_shift;
859 }
860 if bit_shift > 0 {
862 for i in word_shift+1..$n_words {
863 ret[i] += original[i - 1 - word_shift] >> (64 - bit_shift);
864 }
865 }
866 $name(ret)
867 }
868 }
869
870 impl Shr<usize> for $name {
871 type Output = $name;
872
873 fn shr(self, shift: usize) -> $name {
874 let $name(ref original) = self;
875 let mut ret = [0u64; $n_words];
876 let word_shift = shift / 64;
877 let bit_shift = shift % 64;
878
879 for i in word_shift..$n_words {
881 ret[i - word_shift] = original[i] >> bit_shift;
882 }
883
884 if bit_shift > 0 {
886 for i in word_shift+1..$n_words {
887 ret[i - word_shift - 1] += original[i] << (64 - bit_shift);
888 }
889 }
890
891 $name(ret)
892 }
893 }
894
895 impl Ord for $name {
896 fn cmp(&self, other: &$name) -> ::core::cmp::Ordering {
897 let &$name(ref me) = self;
898 let &$name(ref you) = other;
899 let mut i = $n_words;
900 while i > 0 {
901 i -= 1;
902 if me[i] < you[i] { return ::core::cmp::Ordering::Less; }
903 if me[i] > you[i] { return ::core::cmp::Ordering::Greater; }
904 }
905 ::core::cmp::Ordering::Equal
906 }
907 }
908
909 impl PartialOrd for $name {
910 fn partial_cmp(&self, other: &$name) -> Option<::core::cmp::Ordering> {
911 Some(self.cmp(other))
912 }
913 }
914
915 impl ::core::fmt::Debug for $name {
916 fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
917 ::core::fmt::Display::fmt(self, f)
918 }
919 }
920
921 impl ::core::fmt::Display for $name {
922 fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
923 if self.is_zero() {
924 return write!(f, "0");
925 }
926
927 let mut buf = [0_u8; $n_words*20];
928 let mut i = buf.len() - 1;
929 let mut current = *self;
930 let ten = $name::from(10);
931
932 loop {
933 let digit = (current % ten).low_u64() as u8;
934 buf[i] = digit + b'0';
935 current = current / ten;
936 if current.is_zero() {
937 break;
938 }
939 i -= 1;
940 }
941
942 let s = unsafe {::core::str::from_utf8_unchecked(&buf[i..])};
944 f.write_str(s)
945 }
946 }
947
948 impl ::core::fmt::LowerHex for $name {
949 fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
950 let &$name(ref data) = self;
951 try!(write!(f, "0x"));
952 let mut latch = false;
953 for ch in data.iter().rev() {
954 for x in 0..16 {
955 let nibble = (ch & (15u64 << ((15 - x) * 4) as u64)) >> (((15 - x) * 4) as u64);
956 if !latch { latch = nibble != 0 }
957 if latch {
958 try!(write!(f, "{:x}", nibble));
959 }
960 }
961 }
962 Ok(())
963 }
964 }
965
966 #[cfg(feature="std")]
967 impl From<&'static str> for $name {
968 fn from(s: &'static str) -> Self {
969 s.parse().unwrap()
970 }
971 }
972 );
973}
974
975construct_uint!(U128, 2);
976construct_uint!(U256, 4);
977construct_uint!(U512, 8);
978
979impl U256 {
980 #[inline(always)]
983 pub fn full_mul(self, other: U256) -> U512 {
984 U512(uint_full_mul_reg!(U256, 4, self, other))
985 }
986
987 pub fn mod_inverse(self, p: Self) -> Self {
989 let mut mn = (p, self);
990 let mut xy = (U256::zero(), U256::one());
991
992 while mn.1 != U256::zero() {
993 let sb: U256 = ((mn.0 / mn.1).full_mul(xy.1) % U512::from(p)).into();
994 if sb > xy.0 {
995 xy = (xy.1, p - ((sb - xy.0) % p))
996 } else {
997 xy = (xy.1, xy.0 - sb)
998 }
999 mn = (mn.1, mn.0 % mn.1);
1000 }
1001
1002 xy.0
1003 }
1004}
1005
1006impl From<U256> for U512 {
1007 fn from(value: U256) -> U512 {
1008 let U256(ref arr) = value;
1009 let mut ret = [0; 8];
1010 ret[0] = arr[0];
1011 ret[1] = arr[1];
1012 ret[2] = arr[2];
1013 ret[3] = arr[3];
1014 U512(ret)
1015 }
1016}
1017
1018impl From<U512> for U256 {
1019 fn from(value: U512) -> U256 {
1020 let U512(ref arr) = value;
1021 if arr[4] | arr[5] | arr[6] | arr[7] != 0 {
1022 panic!("Overflow");
1023 }
1024 let mut ret = [0; 4];
1025 ret[0] = arr[0];
1026 ret[1] = arr[1];
1027 ret[2] = arr[2];
1028 ret[3] = arr[3];
1029 U256(ret)
1030 }
1031}
1032
1033impl<'a> From<&'a U256> for U512 {
1034 fn from(value: &'a U256) -> U512 {
1035 let U256(ref arr) = *value;
1036 let mut ret = [0; 8];
1037 ret[0] = arr[0];
1038 ret[1] = arr[1];
1039 ret[2] = arr[2];
1040 ret[3] = arr[3];
1041 U512(ret)
1042 }
1043}
1044
1045impl<'a> From<&'a U512> for U256 {
1046 fn from(value: &'a U512) -> U256 {
1047 let U512(ref arr) = *value;
1048 if arr[4] | arr[5] | arr[6] | arr[7] != 0 {
1049 panic!("Overflow");
1050 }
1051 let mut ret = [0; 4];
1052 ret[0] = arr[0];
1053 ret[1] = arr[1];
1054 ret[2] = arr[2];
1055 ret[3] = arr[3];
1056 U256(ret)
1057 }
1058}
1059
1060impl From<U256> for U128 {
1061 fn from(value: U256) -> U128 {
1062 let U256(ref arr) = value;
1063 if arr[2] | arr[3] != 0 {
1064 panic!("Overflow");
1065 }
1066 let mut ret = [0; 2];
1067 ret[0] = arr[0];
1068 ret[1] = arr[1];
1069 U128(ret)
1070 }
1071}
1072
1073impl From<U512> for U128 {
1074 fn from(value: U512) -> U128 {
1075 let U512(ref arr) = value;
1076 if arr[2] | arr[3] | arr[4] | arr[5] | arr[6] | arr[7] != 0 {
1077 panic!("Overflow");
1078 }
1079 let mut ret = [0; 2];
1080 ret[0] = arr[0];
1081 ret[1] = arr[1];
1082 U128(ret)
1083 }
1084}
1085
1086impl From<U128> for U512 {
1087 fn from(value: U128) -> U512 {
1088 let U128(ref arr) = value;
1089 let mut ret = [0; 8];
1090 ret[0] = arr[0];
1091 ret[1] = arr[1];
1092 U512(ret)
1093 }
1094}
1095
1096impl From<U128> for U256 {
1097 fn from(value: U128) -> U256 {
1098 let U128(ref arr) = value;
1099 let mut ret = [0; 4];
1100 ret[0] = arr[0];
1101 ret[1] = arr[1];
1102 U256(ret)
1103 }
1104}
1105
1106impl From<U256> for u64 {
1107 fn from(value: U256) -> u64 {
1108 value.as_u64()
1109 }
1110}
1111
1112impl From<U256> for u32 {
1113 fn from(value: U256) -> u32 {
1114 value.as_u32()
1115 }
1116}
1117
1118impl<'a> From<&'a [u8; 32]> for U256 {
1119 fn from(bytes: &[u8; 32]) -> Self {
1120 bytes[..].into()
1121 }
1122}
1123
1124impl From<[u8; 32]> for U256 {
1125 fn from(bytes: [u8; 32]) -> Self {
1126 bytes[..].as_ref().into()
1127 }
1128}
1129
1130impl From<U256> for [u8; 32] {
1131 fn from(number: U256) -> Self {
1132 let mut arr = [0u8; 32];
1133 number.to_big_endian(&mut arr);
1134 arr
1135 }
1136}
1137
1138impl<'a> From<&'a [u8; 16]> for U128 {
1139 fn from(bytes: &[u8; 16]) -> Self {
1140 bytes[..].into()
1141 }
1142}
1143
1144impl From<[u8; 16]> for U128 {
1145 fn from(bytes: [u8; 16]) -> Self {
1146 bytes[..].as_ref().into()
1147 }
1148}
1149
1150impl From<U128> for [u8; 16] {
1151 fn from(number: U128) -> Self {
1152 let mut arr = [0u8; 16];
1153 number.to_big_endian(&mut arr);
1154 arr
1155 }
1156}
1157
1158impl<'a> From<&'a [u8; 64]> for U512 {
1159 fn from(bytes: &[u8; 64]) -> Self {
1160 bytes[..].into()
1161 }
1162}
1163
1164impl From<[u8; 64]> for U512 {
1165 fn from(bytes: [u8; 64]) -> Self {
1166 bytes[..].as_ref().into()
1167 }
1168}
1169
1170impl From<U512> for [u8; 64] {
1171 fn from(number: U512) -> Self {
1172 let mut arr = [0u8; 64];
1173 number.to_big_endian(&mut arr);
1174 arr
1175 }
1176}
1177
1178#[cfg(feature="heapsizeof")]
1179known_heap_size!(0, U128, U256);
1180
1181#[cfg(test)]
1182mod tests {
1183 use uint::{U128, U256, U512};
1184
1185 #[test]
1186 pub fn display_u128() {
1187 let expected = "340282366920938463463374607431768211455";
1188 let value = U128::MAX;
1189 assert_eq!(format!("{}", value), expected);
1190 assert_eq!(format!("{:?}", value), expected);
1191 }
1192
1193 #[test]
1194 pub fn display_u256() {
1195 let expected = "115792089237316195423570985008687907853269984665640564039457584007913129639935";
1196 let value = U256::MAX;
1197 assert_eq!(format!("{}", value), expected);
1198 assert_eq!(format!("{:?}", value), expected);
1199 }
1200
1201 #[test]
1202 pub fn display_u512() {
1203 let expected = "13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084095";
1204 let value = U512::MAX;
1205 assert_eq!(format!("{}", value), expected);
1206 assert_eq!(format!("{:?}", value), expected);
1207 }
1208}
1209
1210#[cfg(test)]
1211#[cfg(feature="std")]
1212mod std_tests {
1213 use uint::{U128, U256, U512};
1214 use std::str::FromStr;
1215 use super::FromDecStrErr;
1216 use std::u64::MAX;
1217
1218 #[test]
1219 pub fn uint256_from() {
1220 let e = U256([10, 0, 0, 0]);
1221
1222 let ua = U256::from(10u8);
1224 let ub = U256::from(10u16);
1225 let uc = U256::from(10u32);
1226 let ud = U256::from(10u64);
1227 assert_eq!(e, ua);
1228 assert_eq!(e, ub);
1229 assert_eq!(e, uc);
1230 assert_eq!(e, ud);
1231
1232 let va = U256::from(&[10u8][..]);
1234 assert_eq!(e, va);
1235
1236 assert_eq!(U256([0x1010, 0, 0, 0]), U256::from(&[0x10u8, 0x10][..]));
1238 assert_eq!(U256([0x12f0, 0, 0, 0]), U256::from(&[0x12u8, 0xf0][..]));
1239 assert_eq!(U256([0x12f0, 0, 0, 0]), U256::from(&[0, 0x12u8, 0xf0][..]));
1240 assert_eq!(U256([0x12f0, 0 , 0, 0]), U256::from(&[0, 0, 0, 0, 0, 0, 0, 0x12u8, 0xf0][..]));
1241 assert_eq!(U256([0x12f0, 1 , 0, 0]), U256::from(&[1, 0, 0, 0, 0, 0, 0, 0x12u8, 0xf0][..]));
1242 assert_eq!(
1243 U256([0x12f0, 1 , 0x0910203040506077, 0x8090a0b0c0d0e0f0]),
1244 U256::from(&
1245 [
1246 0x80, 0x90, 0xa0, 0xb0, 0xc0, 0xd0, 0xe0, 0xf0,
1247 0x09, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x77,
1248 0, 0, 0, 0, 0, 0, 0, 1,
1249 0, 0, 0, 0, 0, 0, 0x12u8, 0xf0
1250 ][..]
1251 )
1252 );
1253 assert_eq!(
1254 U256([0x00192437100019fa, 0x243710, 0, 0]),
1255 U256::from(&[0x24u8, 0x37, 0x10,0, 0x19, 0x24, 0x37, 0x10, 0, 0x19, 0xfa][..])
1256 );
1257
1258 let sa = U256::from_str("0a").unwrap();
1260 assert_eq!(e, sa);
1261 assert_eq!(U256([0x1010, 0, 0, 0]), U256::from_str("1010").unwrap());
1262 assert_eq!(U256([0x12f0, 0, 0, 0]), U256::from_str("12f0").unwrap());
1263 assert_eq!(U256([0x12f0, 0, 0, 0]), U256::from_str("12f0").unwrap());
1264 assert_eq!(U256([0x12f0, 0 , 0, 0]), U256::from_str("0000000012f0").unwrap());
1265 assert_eq!(U256([0x12f0, 1 , 0, 0]), U256::from_str("0100000000000012f0").unwrap());
1266 assert_eq!(
1267 U256([0x12f0, 1 , 0x0910203040506077, 0x8090a0b0c0d0e0f0]),
1268 U256::from_str("8090a0b0c0d0e0f00910203040506077000000000000000100000000000012f0").unwrap()
1269 );
1270 }
1271
1272 #[test]
1273 pub fn uint256_to() {
1274 let hex = "8090a0b0c0d0e0f00910203040506077583a2cf8264910e1436bda32571012f0";
1275 let uint = U256::from_str(hex).unwrap();
1276 let mut bytes = [0u8; 32];
1277 uint.to_big_endian(&mut bytes);
1278 let uint2 = U256::from(&bytes[..]);
1279 assert_eq!(uint, uint2);
1280 }
1281
1282 #[test]
1283 pub fn uint256_bits_test() {
1284 assert_eq!(U256::from(0u64).bits(), 0);
1285 assert_eq!(U256::from(255u64).bits(), 8);
1286 assert_eq!(U256::from(256u64).bits(), 9);
1287 assert_eq!(U256::from(300u64).bits(), 9);
1288 assert_eq!(U256::from(60000u64).bits(), 16);
1289 assert_eq!(U256::from(70000u64).bits(), 17);
1290
1291 let mut shl = U256::from(70000u64);
1293 shl = shl << 100;
1294 assert_eq!(shl.bits(), 117);
1295 shl = shl << 100;
1296 assert_eq!(shl.bits(), 217);
1297 shl = shl << 100;
1298 assert_eq!(shl.bits(), 0);
1299
1300 assert!(!U256::from(10u8).bit(0));
1303 assert!(U256::from(10u8).bit(1));
1304 assert!(!U256::from(10u8).bit(2));
1305 assert!(U256::from(10u8).bit(3));
1306 assert!(!U256::from(10u8).bit(4));
1307
1308 assert_eq!(U256::from(10u8).byte(0), 10);
1310 assert_eq!(U256::from(0xffu64).byte(0), 0xff);
1311 assert_eq!(U256::from(0xffu64).byte(1), 0);
1312 assert_eq!(U256::from(0x01ffu64).byte(0), 0xff);
1313 assert_eq!(U256::from(0x01ffu64).byte(1), 0x1);
1314 assert_eq!(U256([0u64, 0xfc, 0, 0]).byte(8), 0xfc);
1315 assert_eq!(U256([0u64, 0, 0, u64::max_value()]).byte(31), 0xff);
1316 assert_eq!(U256([0u64, 0, 0, (u64::max_value() >> 8) + 1]).byte(31), 0x01);
1317 }
1318
1319 #[test]
1320 #[cfg_attr(feature="dev", allow(eq_op))]
1321 pub fn uint256_comp_test() {
1322 let small = U256([10u64, 0, 0, 0]);
1323 let big = U256([0x8C8C3EE70C644118u64, 0x0209E7378231E632, 0, 0]);
1324 let bigger = U256([0x9C8C3EE70C644118u64, 0x0209E7378231E632, 0, 0]);
1325 let biggest = U256([0x5C8C3EE70C644118u64, 0x0209E7378231E632, 0, 1]);
1326
1327 assert!(small < big);
1328 assert!(big < bigger);
1329 assert!(bigger < biggest);
1330 assert!(bigger <= biggest);
1331 assert!(biggest <= biggest);
1332 assert!(bigger >= big);
1333 assert!(bigger >= small);
1334 assert!(small <= small);
1335 }
1336
1337 #[test]
1338 pub fn uint256_arithmetic_test() {
1339 let init = U256::from(0xDEADBEEFDEADBEEFu64);
1340 let copy = init;
1341
1342 let add = init + copy;
1343 assert_eq!(add, U256([0xBD5B7DDFBD5B7DDEu64, 1, 0, 0]));
1344 let shl = add << 88;
1346 assert_eq!(shl, U256([0u64, 0xDFBD5B7DDE000000, 0x1BD5B7D, 0]));
1347 let shr = shl >> 40;
1348 assert_eq!(shr, U256([0x7DDE000000000000u64, 0x0001BD5B7DDFBD5B, 0, 0]));
1349 let incr = shr + U256::from(1u64);
1351 assert_eq!(incr, U256([0x7DDE000000000001u64, 0x0001BD5B7DDFBD5B, 0, 0]));
1352 let sub = overflowing!(incr.overflowing_sub(init));
1354 assert_eq!(sub, U256([0x9F30411021524112u64, 0x0001BD5B7DDFBD5A, 0, 0]));
1355 let mult = sub.mul_u32(300);
1357 assert_eq!(mult, U256([0x8C8C3EE70C644118u64, 0x0209E7378231E632, 0, 0]));
1358 assert_eq!(U256::from(105u8) / U256::from(5u8), U256::from(21u8));
1360 let div = mult / U256::from(300u16);
1361 assert_eq!(div, U256([0x9F30411021524112u64, 0x0001BD5B7DDFBD5A, 0, 0]));
1362
1363 let a = U256::from_str("ff000000000000000000000000000000000000000000000000000000000000d1").unwrap();
1364 let b = U256::from_str("00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff2e").unwrap();
1365 println!("{:x}", a);
1366 println!("{:x}", b);
1367 assert_eq!(!a, b);
1368 assert_eq!(a, !b);
1369 }
1370
1371 #[test]
1372 pub fn uint256_simple_mul() {
1373 let a = U256::from_str("10000000000000000").unwrap();
1374 let b = U256::from_str("10000000000000000").unwrap();
1375
1376 let c = U256::from_str("100000000000000000000000000000000").unwrap();
1377 println!("Multiplying");
1378 let result = a.overflowing_mul(b);
1379 println!("Got result");
1380 assert_eq!(result, (c, false))
1381 }
1382
1383 #[test]
1384 pub fn uint256_extreme_bitshift_test() {
1385 let init = U256::from(0xDEADBEEFDEADBEEFu64);
1388
1389 assert_eq!(init << 64, U256([0, 0xDEADBEEFDEADBEEF, 0, 0]));
1390 let add = (init << 64) + init;
1391 assert_eq!(add, U256([0xDEADBEEFDEADBEEF, 0xDEADBEEFDEADBEEF, 0, 0]));
1392 assert_eq!(add >> 0, U256([0xDEADBEEFDEADBEEF, 0xDEADBEEFDEADBEEF, 0, 0]));
1393 assert_eq!(add << 0, U256([0xDEADBEEFDEADBEEF, 0xDEADBEEFDEADBEEF, 0, 0]));
1394 assert_eq!(add >> 64, U256([0xDEADBEEFDEADBEEF, 0, 0, 0]));
1395 assert_eq!(add << 64, U256([0, 0xDEADBEEFDEADBEEF, 0xDEADBEEFDEADBEEF, 0]));
1396 }
1397
1398 #[test]
1399 pub fn uint256_exp10() {
1400 assert_eq!(U256::exp10(0), U256::from(1u64));
1401 println!("\none: {:?}", U256::from(1u64));
1402 println!("ten: {:?}", U256::from(10u64));
1403 assert_eq!(U256::from(2u64) * U256::from(10u64), U256::from(20u64));
1404 assert_eq!(U256::exp10(1), U256::from(10u64));
1405 assert_eq!(U256::exp10(2), U256::from(100u64));
1406 assert_eq!(U256::exp10(5), U256::from(100000u64));
1407 }
1408
1409 #[test]
1410 pub fn uint256_mul32() {
1411 assert_eq!(U256::from(0u64).mul_u32(2), U256::from(0u64));
1412 assert_eq!(U256::from(1u64).mul_u32(2), U256::from(2u64));
1413 assert_eq!(U256::from(10u64).mul_u32(2), U256::from(20u64));
1414 assert_eq!(U256::from(10u64).mul_u32(5), U256::from(50u64));
1415 assert_eq!(U256::from(1000u64).mul_u32(50), U256::from(50000u64));
1416 }
1417
1418 #[test]
1419 fn uint256_pow() {
1420 assert_eq!(U256::from(10).pow(U256::from(0)), U256::from(1));
1421 assert_eq!(U256::from(10).pow(U256::from(1)), U256::from(10));
1422 assert_eq!(U256::from(10).pow(U256::from(2)), U256::from(100));
1423 assert_eq!(U256::from(10).pow(U256::from(3)), U256::from(1000));
1424 assert_eq!(U256::from(10).pow(U256::from(20)), U256::exp10(20));
1425 }
1426
1427 #[test]
1428 #[should_panic]
1429 fn uint256_pow_overflow_panic() {
1430 U256::from(2).pow(U256::from(0x100));
1431 }
1432
1433 #[test]
1434 fn should_format_hex_correctly() {
1435 assert_eq!(&U256::from(0).to_hex(), &"0");
1436 assert_eq!(&U256::from(0x1).to_hex(), &"1");
1437 assert_eq!(&U256::from(0xf).to_hex(), &"f");
1438 assert_eq!(&U256::from(0x10).to_hex(), &"10");
1439 assert_eq!(&U256::from(0xff).to_hex(), &"ff");
1440 assert_eq!(&U256::from(0x100).to_hex(), &"100");
1441 assert_eq!(&U256::from(0xfff).to_hex(), &"fff");
1442 assert_eq!(&U256::from(0x1000).to_hex(), &"1000");
1443 }
1444
1445 #[test]
1446 fn uint256_overflowing_pow() {
1447 assert_eq!(
1452 U256::from(2).overflowing_pow(U256::from(0x100)),
1453 (U256::zero(), true)
1454 );
1455 }
1456
1457 #[test]
1458 pub fn uint256_mul1() {
1459 assert_eq!(U256::from(1u64) * U256::from(10u64), U256::from(10u64));
1460 }
1461
1462 #[test]
1463 pub fn uint256_mul2() {
1464 let a = U512::from_str("10000000000000000fffffffffffffffe").unwrap();
1465 let b = U512::from_str("ffffffffffffffffffffffffffffffff").unwrap();
1466
1467 assert_eq!(a * b, U512::from_str("10000000000000000fffffffffffffffcffffffffffffffff0000000000000002").unwrap());
1468 }
1469
1470 #[test]
1471 pub fn uint256_overflowing_mul() {
1472 assert_eq!(
1473 U256::from_str("100000000000000000000000000000000").unwrap().overflowing_mul(
1474 U256::from_str("100000000000000000000000000000000").unwrap()
1475 ),
1476 (U256::zero(), true)
1477 );
1478 }
1479
1480 #[test]
1481 pub fn uint128_add() {
1482 assert_eq!(
1483 U128::from_str("fffffffffffffffff").unwrap() + U128::from_str("fffffffffffffffff").unwrap(),
1484 U128::from_str("1ffffffffffffffffe").unwrap()
1485 );
1486 }
1487
1488 #[test]
1489 pub fn uint128_add_overflow() {
1490 assert_eq!(
1491 U128::from_str("ffffffffffffffffffffffffffffffff").unwrap()
1492 .overflowing_add(
1493 U128::from_str("ffffffffffffffffffffffffffffffff").unwrap()
1494 ),
1495 (U128::from_str("fffffffffffffffffffffffffffffffe").unwrap(), true)
1496 );
1497 }
1498
1499 #[test]
1500 #[should_panic]
1501 #[cfg(debug_assertions)]
1502 pub fn uint128_add_overflow_panic() {
1503 let _res = U128::from_str("ffffffffffffffffffffffffffffffff").unwrap()
1504 +
1505 U128::from_str("ffffffffffffffffffffffffffffffff").unwrap();
1506 }
1507
1508 #[test]
1509 pub fn uint128_mul() {
1510 assert_eq!(
1511 U128::from_str("fffffffff").unwrap() * U128::from_str("fffffffff").unwrap(),
1512 U128::from_str("ffffffffe000000001").unwrap());
1513 }
1514
1515 #[test]
1516 pub fn uint512_mul() {
1517 assert_eq!(
1518 U512::from_str("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()
1519 *
1520 U512::from_str("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap(),
1521 U512::from_str("3fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000000000000000000000000000000000000000000000000000000000000001").unwrap()
1522 );
1523 }
1524
1525 #[test]
1526 pub fn uint256_mul_overflow() {
1527 assert_eq!(
1528 U256::from_str("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()
1529 .overflowing_mul(
1530 U256::from_str("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()
1531 ),
1532 (U256::from_str("1").unwrap(), true)
1533 );
1534 }
1535
1536 #[test]
1537 #[should_panic]
1538 pub fn uint256_mul_overflow_panic() {
1539 let _res = U256::from_str("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()
1540 *
1541 U256::from_str("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap();
1542 }
1543
1544 #[test]
1545 pub fn uint256_sub_overflow() {
1546 assert_eq!(
1547 U256::from_str("0").unwrap()
1548 .overflowing_sub(
1549 U256::from_str("1").unwrap()
1550 ),
1551 (U256::from_str("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap(), true)
1552 );
1553 }
1554
1555 #[test]
1556 #[should_panic]
1557 pub fn uint256_sub_overflow_panic() {
1558 let _res = U256::from_str("0").unwrap()
1559 -
1560 U256::from_str("1").unwrap();
1561 }
1562
1563 #[test]
1564 pub fn uint256_shl() {
1565 assert_eq!(
1566 U256::from_str("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()
1567 << 4,
1568 U256::from_str("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0").unwrap()
1569 );
1570 }
1571
1572 #[test]
1573 pub fn uint256_shl_words() {
1574 assert_eq!(
1575 U256::from_str("0000000000000001ffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()
1576 << 64,
1577 U256::from_str("ffffffffffffffffffffffffffffffffffffffffffffffff0000000000000000").unwrap()
1578 );
1579 assert_eq!(
1580 U256::from_str("0000000000000000ffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()
1581 << 64,
1582 U256::from_str("ffffffffffffffffffffffffffffffffffffffffffffffff0000000000000000").unwrap()
1583 );
1584 }
1585
1586 #[test]
1587 pub fn uint256_mul() {
1588 assert_eq!(
1589 U256::from_str("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff").unwrap()
1590 *
1591 U256::from_str("2").unwrap(),
1592 U256::from_str("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe").unwrap()
1593 );
1594 }
1595
1596 #[test]
1597 fn uint256_div() {
1598 assert_eq!(U256::from(10u64) / U256::from(1u64), U256::from(10u64));
1599 assert_eq!(U256::from(10u64) / U256::from(2u64), U256::from(5u64));
1600 assert_eq!(U256::from(10u64) / U256::from(3u64), U256::from(3u64));
1601 }
1602
1603 #[test]
1604 fn uint256_rem() {
1605 assert_eq!(U256::from(10u64) % U256::from(1u64), U256::from(0u64));
1606 assert_eq!(U256::from(10u64) % U256::from(3u64), U256::from(1u64));
1607 }
1608
1609 #[test]
1610 fn uint256_from_dec_str() {
1611 assert_eq!(U256::from_dec_str("10").unwrap(), U256::from(10u64));
1612 assert_eq!(U256::from_dec_str("1024").unwrap(), U256::from(1024u64));
1613 assert_eq!(U256::from_dec_str("115792089237316195423570985008687907853269984665640564039457584007913129639936"), Err(FromDecStrErr::InvalidLength));
1614 assert_eq!(U256::from_dec_str("0x11"), Err(FromDecStrErr::InvalidCharacter));
1615 }
1616
1617 #[test]
1618 fn display_uint() {
1619 let s = "12345678987654321023456789";
1620 assert_eq!(format!("{}", U256::from_dec_str(s).unwrap()), s);
1621 }
1622
1623 #[test]
1624 fn display_uint_zero() {
1625 assert_eq!(format!("{}", U256::from(0)), "0");
1626 }
1627
1628 #[test]
1629 fn u512_multi_adds() {
1630 let (result, _) = U512([0, 0, 0, 0, 0, 0, 0, 0]).overflowing_add(U512([0, 0, 0, 0, 0, 0, 0, 0]));
1631 assert_eq!(result, U512([0, 0, 0, 0, 0, 0, 0, 0]));
1632
1633 let (result, _) = U512([1, 0, 0, 0, 0, 0, 0, 1]).overflowing_add(U512([1, 0, 0, 0, 0, 0, 0, 1]));
1634 assert_eq!(result, U512([2, 0, 0, 0, 0, 0, 0, 2]));
1635
1636 let (result, _) = U512([0, 0, 0, 0, 0, 0, 0, 1]).overflowing_add(U512([0, 0, 0, 0, 0, 0, 0, 1]));
1637 assert_eq!(result, U512([0, 0, 0, 0, 0, 0, 0, 2]));
1638
1639 let (result, _) = U512([0, 0, 0, 0, 0, 0, 2, 1]).overflowing_add(U512([0, 0, 0, 0, 0, 0, 3, 1]));
1640 assert_eq!(result, U512([0, 0, 0, 0, 0, 0, 5, 2]));
1641
1642 let (result, _) = U512([1, 2, 3, 4, 5, 6, 7, 8]).overflowing_add(U512([9, 10, 11, 12, 13, 14, 15, 16]));
1643 assert_eq!(result, U512([10, 12, 14, 16, 18, 20, 22, 24]));
1644
1645 let (_, overflow) = U512([0, 0, 0, 0, 0, 0, 2, 1]).overflowing_add(U512([0, 0, 0, 0, 0, 0, 3, 1]));
1646 assert!(!overflow);
1647
1648 let (_, overflow) = U512([MAX, MAX, MAX, MAX, MAX, MAX, MAX, MAX])
1649 .overflowing_add(U512([MAX, MAX, MAX, MAX, MAX, MAX, MAX, MAX]));
1650 assert!(overflow);
1651
1652 let (_, overflow) = U512([0, 0, 0, 0, 0, 0, 0, MAX])
1653 .overflowing_add(U512([0, 0, 0, 0, 0, 0, 0, MAX]));
1654 assert!(overflow);
1655
1656 let (_, overflow) = U512([0, 0, 0, 0, 0, 0, 0, MAX])
1657 .overflowing_add(U512([0, 0, 0, 0, 0, 0, 0, 0]));
1658 assert!(!overflow);
1659 }
1660
1661 #[test]
1662 fn u256_multi_adds() {
1663 let (result, _) = U256([0, 0, 0, 0]).overflowing_add(U256([0, 0, 0, 0]));
1664 assert_eq!(result, U256([0, 0, 0, 0]));
1665
1666 let (result, _) = U256([0, 0, 0, 1]).overflowing_add(U256([0, 0, 0, 1]));
1667 assert_eq!(result, U256([0, 0, 0, 2]));
1668
1669 let (result, overflow) = U256([0, 0, 2, 1]).overflowing_add(U256([0, 0, 3, 1]));
1670 assert_eq!(result, U256([0, 0, 5, 2]));
1671 assert!(!overflow);
1672
1673 let (_, overflow) = U256([MAX, MAX, MAX, MAX])
1674 .overflowing_add(U256([MAX, MAX, MAX, MAX]));
1675 assert!(overflow);
1676
1677 let (_, overflow) = U256([0, 0, 0, MAX]).overflowing_add(U256([0, 0, 0, MAX]));
1678 assert!(overflow);
1679 }
1680
1681
1682 #[test]
1683 fn u256_multi_subs() {
1684 let (result, _) = U256([0, 0, 0, 0]).overflowing_sub(U256([0, 0, 0, 0]));
1685 assert_eq!(result, U256([0, 0, 0, 0]));
1686
1687 let (result, _) = U256([0, 0, 0, 1]).overflowing_sub(U256([0, 0, 0, 1]));
1688 assert_eq!(result, U256([0, 0, 0, 0]));
1689
1690 let (_, overflow) = U256([0, 0, 2, 1]).overflowing_sub(U256([0, 0, 3, 1]));
1691 assert!(overflow);
1692
1693 let (result, overflow) =
1694 U256([MAX, MAX, MAX, MAX])
1695 .overflowing_sub(U256([MAX/2, MAX/2, MAX/2, MAX/2]));
1696
1697 assert!(!overflow);
1698 assert_eq!(U256([MAX/2+1, MAX/2+1, MAX/2+1, MAX/2+1]), result);
1699
1700 let (result, overflow) = U256([0, 0, 0, 1]).overflowing_sub(U256([0, 0, 1, 0]));
1701 assert!(!overflow);
1702 assert_eq!(U256([0, 0, MAX, 0]), result);
1703
1704 let (result, overflow) = U256([0, 0, 0, 1]).overflowing_sub(U256([1, 0, 0, 0]));
1705 assert!(!overflow);
1706 assert_eq!(U256([MAX, MAX, MAX, 0]), result);
1707 }
1708
1709 #[test]
1710 fn u512_multi_subs() {
1711 let (result, _) = U512([0, 0, 0, 0, 0, 0, 0, 0]).overflowing_sub(U512([0, 0, 0, 0, 0, 0, 0, 0]));
1712 assert_eq!(result, U512([0, 0, 0, 0, 0, 0, 0, 0]));
1713
1714 let (result, _) = U512([10, 9, 8, 7, 6, 5, 4, 3]).overflowing_sub(U512([9, 8, 7, 6, 5, 4, 3, 2]));
1715 assert_eq!(result, U512([1, 1, 1, 1, 1, 1, 1, 1]));
1716
1717 let (_, overflow) = U512([10, 9, 8, 7, 6, 5, 4, 3]).overflowing_sub(U512([9, 8, 7, 6, 5, 4, 3, 2]));
1718 assert!(!overflow);
1719
1720 let (_, overflow) = U512([9, 8, 7, 6, 5, 4, 3, 2]).overflowing_sub(U512([10, 9, 8, 7, 6, 5, 4, 3]));
1721 assert!(overflow);
1722 }
1723
1724 #[test]
1725 fn u256_multi_carry_all() {
1726 let (result, _) = U256([MAX, 0, 0, 0]).overflowing_mul(U256([MAX, 0, 0, 0]));
1727 assert_eq!(U256([1, MAX-1, 0, 0]), result);
1728
1729 let (result, _) = U256([0, MAX, 0, 0]).overflowing_mul(U256([MAX, 0, 0, 0]));
1730 assert_eq!(U256([0, 1, MAX-1, 0]), result);
1731
1732 let (result, _) = U256([MAX, MAX, 0, 0]).overflowing_mul(U256([MAX, 0, 0, 0]));
1733 assert_eq!(U256([1, MAX, MAX-1, 0]), result);
1734
1735 let (result, _) = U256([MAX, 0, 0, 0]).overflowing_mul(U256([MAX, MAX, 0, 0]));
1736 assert_eq!(U256([1, MAX, MAX-1, 0]), result);
1737
1738 let (result, _) = U256([MAX, MAX, 0, 0])
1739 .overflowing_mul(U256([MAX, MAX, 0, 0]));
1740 assert_eq!(U256([1, 0, MAX-1, MAX]), result);
1741
1742 let (result, _) = U256([MAX, 0, 0, 0]).overflowing_mul(U256([MAX, MAX, MAX, 0]));
1743 assert_eq!(U256([1, MAX, MAX, MAX-1]), result);
1744
1745 let (result, _) = U256([MAX, MAX, MAX, 0]).overflowing_mul(U256([MAX, 0, 0, 0]));
1746 assert_eq!(U256([1, MAX, MAX, MAX-1]), result);
1747
1748 let (result, _) = U256([MAX, 0, 0, 0]).overflowing_mul(
1749 U256([MAX, MAX, MAX, MAX]));
1750 assert_eq!(U256([1, MAX, MAX, MAX]), result);
1751
1752 let (result, _) = U256([MAX, MAX, MAX, MAX])
1753 .overflowing_mul(U256([MAX, 0, 0, 0]));
1754 assert_eq!(U256([1, MAX, MAX, MAX]), result);
1755
1756 let (result, _) = U256([MAX, MAX, MAX, 0])
1757 .overflowing_mul(U256([MAX, MAX, 0, 0]));
1758 assert_eq!(U256([1, 0, MAX, MAX-1]), result);
1759
1760 let (result, _) = U256([MAX, MAX, 0, 0])
1761 .overflowing_mul(U256([MAX, MAX, MAX, 0]));
1762 assert_eq!(U256([1, 0, MAX, MAX-1]), result);
1763
1764 let (result, _) = U256([MAX, MAX, MAX, MAX])
1765 .overflowing_mul(U256([MAX, MAX, 0, 0]));
1766 assert_eq!(U256([1, 0, MAX, MAX]), result);
1767
1768 let (result, _) = U256([MAX, MAX, 0, 0])
1769 .overflowing_mul(U256([MAX, MAX, MAX, MAX]));
1770 assert_eq!(U256([1, 0, MAX, MAX]), result);
1771
1772 let (result, _) = U256([MAX, MAX, MAX, 0])
1773 .overflowing_mul(U256([MAX, MAX, MAX, 0]));
1774 assert_eq!(U256([1, 0, 0, MAX-1]), result);
1775
1776 let (result, _) = U256([MAX, MAX, MAX, 0])
1777 .overflowing_mul(U256([MAX, MAX, MAX, MAX]));
1778 assert_eq!(U256([1, 0, 0, MAX]), result);
1779
1780 let (result, _) = U256([MAX, MAX, MAX, MAX])
1781 .overflowing_mul(U256([MAX, MAX, MAX, 0]));
1782 assert_eq!(U256([1, 0, 0, MAX]), result);
1783
1784 let (result, _) = U256([0, 0, 0, MAX]).overflowing_mul(U256([0, 0, 0, MAX]));
1785 assert_eq!(U256([0, 0, 0, 0]), result);
1786
1787 let (result, _) = U256([1, 0, 0, 0]).overflowing_mul(U256([0, 0, 0, MAX]));
1788 assert_eq!(U256([0, 0, 0, MAX]), result);
1789
1790 let (result, _) = U256([MAX, MAX, MAX, MAX])
1791 .overflowing_mul(U256([MAX, MAX, MAX, MAX]));
1792 assert_eq!(U256([1, 0, 0, 0]), result);
1793 }
1794
1795 #[test]
1796 fn u256_multi_muls() {
1797 let (result, _) = U256([0, 0, 0, 0]).overflowing_mul(U256([0, 0, 0, 0]));
1798 assert_eq!(U256([0, 0, 0, 0]), result);
1799
1800 let (result, _) = U256([1, 0, 0, 0]).overflowing_mul(U256([1, 0, 0, 0]));
1801 assert_eq!(U256([1, 0, 0, 0]), result);
1802
1803 let (result, _) = U256([5, 0, 0, 0]).overflowing_mul(U256([5, 0, 0, 0]));
1804 assert_eq!(U256([25, 0, 0, 0]), result);
1805
1806 let (result, _) = U256([0, 5, 0, 0]).overflowing_mul(U256([0, 5, 0, 0]));
1807 assert_eq!(U256([0, 0, 25, 0]), result);
1808
1809 let (result, _) = U256([0, 0, 0, 1]).overflowing_mul(U256([1, 0, 0, 0]));
1810 assert_eq!(U256([0, 0, 0, 1]), result);
1811
1812 let (result, _) = U256([0, 0, 0, 5]).overflowing_mul(U256([2, 0, 0, 0]));
1813 assert_eq!(U256([0, 0, 0, 10]), result);
1814
1815 let (result, _) = U256([0, 0, 1, 0]).overflowing_mul(U256([0, 5, 0, 0]));
1816 assert_eq!(U256([0, 0, 0, 5]), result);
1817
1818 let (result, _) = U256([0, 0, 8, 0]).overflowing_mul(U256([0, 0, 7, 0]));
1819 assert_eq!(U256([0, 0, 0, 0]), result);
1820
1821 let (result, _) = U256([2, 0, 0, 0]).overflowing_mul(U256([0, 5, 0, 0]));
1822 assert_eq!(U256([0, 10, 0, 0]), result);
1823
1824 let (result, _) = U256([1, 0, 0, 0]).overflowing_mul(U256([0, 0, 0, MAX]));
1825 assert_eq!(U256([0, 0, 0, MAX]), result);
1826 }
1827
1828 #[test]
1829 fn u256_multi_muls_overflow() {
1830 let (_, overflow) = U256([1, 0, 0, 0]).overflowing_mul(U256([0, 0, 0, 0]));
1831 assert!(!overflow);
1832
1833 let (_, overflow) = U256([1, 0, 0, 0]).overflowing_mul(U256([0, 0, 0, MAX]));
1834 assert!(!overflow);
1835
1836 let (_, overflow) = U256([0, 1, 0, 0]).overflowing_mul(U256([0, 0, 0, MAX]));
1837 assert!(overflow);
1838
1839 let (_, overflow) = U256([0, 1, 0, 0]).overflowing_mul(U256([0, 1, 0, 0]));
1840 assert!(!overflow);
1841
1842 let (_, overflow) = U256([0, 1, 0, MAX]).overflowing_mul(U256([0, 1, 0, MAX]));
1843 assert!(overflow);
1844
1845 let (_, overflow) = U256([0, MAX, 0, 0]).overflowing_mul(U256([0, MAX, 0, 0]));
1846 assert!(!overflow);
1847
1848 let (_, overflow) = U256([1, 0, 0, 0]).overflowing_mul(U256([10, 0, 0, 0]));
1849 assert!(!overflow);
1850
1851 let (_, overflow) = U256([2, 0, 0, 0]).overflowing_mul(U256([0, 0, 0, MAX / 2]));
1852 assert!(!overflow);
1853
1854 let (_, overflow) = U256([0, 0, 8, 0]).overflowing_mul(U256([0, 0, 7, 0]));
1855 assert!(overflow);
1856 }
1857
1858 #[test]
1859 fn big_endian() {
1860 let source = U256([1, 0, 0, 0]);
1861 let mut target = vec![0u8; 32];
1862
1863 assert_eq!(source, U256::from(1));
1864
1865 source.to_big_endian(&mut target);
1866 assert_eq!(
1867 vec![0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
1868 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 1u8],
1869 target);
1870
1871 let source = U256([512, 0, 0, 0]);
1872 let mut target = vec![0u8; 32];
1873
1874 source.to_big_endian(&mut target);
1875 assert_eq!(
1876 vec![0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
1877 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 2u8, 0u8],
1878 target);
1879
1880 let source = U256([0, 512, 0, 0]);
1881 let mut target = vec![0u8; 32];
1882
1883 source.to_big_endian(&mut target);
1884 assert_eq!(
1885 vec![0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8,
1886 0u8, 0u8, 0u8, 0u8, 0u8, 2u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8],
1887 target);
1888
1889 let source = U256::from_str("0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20").unwrap();
1890 source.to_big_endian(&mut target);
1891 assert_eq!(
1892 vec![0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11,
1893 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20],
1894 target);
1895 }
1896
1897 #[test]
1898 #[cfg_attr(feature="dev", allow(cyclomatic_complexity))]
1899 fn u256_multi_full_mul() {
1900 let result = U256([0, 0, 0, 0]).full_mul(U256([0, 0, 0, 0]));
1901 assert_eq!(U512([0, 0, 0, 0, 0, 0, 0, 0]), result);
1902
1903 let result = U256([1, 0, 0, 0]).full_mul(U256([1, 0, 0, 0]));
1904 assert_eq!(U512([1, 0, 0, 0, 0, 0, 0, 0]), result);
1905
1906 let result = U256([5, 0, 0, 0]).full_mul(U256([5, 0, 0, 0]));
1907 assert_eq!(U512([25, 0, 0, 0, 0, 0, 0, 0]), result);
1908
1909 let result = U256([0, 5, 0, 0]).full_mul(U256([0, 5, 0, 0]));
1910 assert_eq!(U512([0, 0, 25, 0, 0, 0, 0, 0]), result);
1911
1912 let result = U256([0, 0, 0, 4]).full_mul(U256([4, 0, 0, 0]));
1913 assert_eq!(U512([0, 0, 0, 16, 0, 0, 0, 0]), result);
1914
1915 let result = U256([0, 0, 0, 5]).full_mul(U256([2, 0, 0, 0]));
1916 assert_eq!(U512([0, 0, 0, 10, 0, 0, 0, 0]), result);
1917
1918 let result = U256([0, 0, 2, 0]).full_mul(U256([0, 5, 0, 0]));
1919 assert_eq!(U512([0, 0, 0, 10, 0, 0, 0, 0]), result);
1920
1921 let result = U256([0, 3, 0, 0]).full_mul(U256([0, 0, 3, 0]));
1922 assert_eq!(U512([0, 0, 0, 9, 0, 0, 0, 0]), result);
1923
1924 let result = U256([0, 0, 8, 0]).full_mul(U256([0, 0, 6, 0]));
1925 assert_eq!(U512([0, 0, 0, 0, 48, 0, 0, 0]), result);
1926
1927 let result = U256([9, 0, 0, 0]).full_mul(U256([0, 3, 0, 0]));
1928 assert_eq!(U512([0, 27, 0, 0, 0, 0, 0, 0]), result);
1929
1930 let result = U256([MAX, 0, 0, 0]).full_mul(U256([MAX, 0, 0, 0]));
1931 assert_eq!(U512([1, MAX-1, 0, 0, 0, 0, 0, 0]), result);
1932
1933 let result = U256([0, MAX, 0, 0]).full_mul(U256([MAX, 0, 0, 0]));
1934 assert_eq!(U512([0, 1, MAX-1, 0, 0, 0, 0, 0]), result);
1935
1936 let result = U256([MAX, MAX, 0, 0]).full_mul(U256([MAX, 0, 0, 0]));
1937 assert_eq!(U512([1, MAX, MAX-1, 0, 0, 0, 0, 0]), result);
1938
1939 let result = U256([MAX, 0, 0, 0]).full_mul(U256([MAX, MAX, 0, 0]));
1940 assert_eq!(U512([1, MAX, MAX-1, 0, 0, 0, 0, 0]), result);
1941
1942 let result = U256([MAX, MAX, 0, 0]).full_mul(U256([MAX, MAX, 0, 0]));
1943 assert_eq!(U512([1, 0, MAX-1, MAX, 0, 0, 0, 0]), result);
1944
1945 let result = U256([MAX, 0, 0, 0]).full_mul(U256([MAX, MAX, MAX, 0]));
1946 assert_eq!(U512([1, MAX, MAX, MAX-1, 0, 0, 0, 0]), result);
1947
1948 let result = U256([MAX, MAX, MAX, 0]).full_mul(U256([MAX, 0, 0, 0]));
1949 assert_eq!(U512([1, MAX, MAX, MAX-1, 0, 0, 0, 0]), result);
1950
1951 let result = U256([MAX, 0, 0, 0]).full_mul(U256([MAX, MAX, MAX, MAX]));
1952 assert_eq!(U512([1, MAX, MAX, MAX, MAX-1, 0, 0, 0]), result);
1953
1954 let result = U256([MAX, MAX, MAX, MAX]).full_mul(U256([MAX, 0, 0, 0]));
1955 assert_eq!(U512([1, MAX, MAX, MAX, MAX-1, 0, 0, 0]), result);
1956
1957 let result = U256([MAX, MAX, MAX, 0]).full_mul(U256([MAX, MAX, 0, 0]));
1958 assert_eq!(U512([1, 0, MAX, MAX-1, MAX, 0, 0, 0]), result);
1959
1960 let result = U256([MAX, MAX, 0, 0]).full_mul(U256([MAX, MAX, MAX, 0]));
1961 assert_eq!(U512([1, 0, MAX, MAX-1, MAX, 0, 0, 0]), result);
1962
1963 let result = U256([MAX, MAX, MAX, MAX]).full_mul(U256([MAX, MAX, 0, 0]));
1964 assert_eq!(U512([1, 0, MAX, MAX, MAX-1, MAX, 0, 0]), result);
1965
1966 let result = U256([MAX, MAX, 0, 0]).full_mul(U256([MAX, MAX, MAX, MAX]));
1967 assert_eq!(U512([1, 0, MAX, MAX, MAX-1, MAX, 0, 0]), result);
1968
1969 let result = U256([MAX, MAX, MAX, 0]).full_mul(U256([MAX, MAX, MAX, 0]));
1970 assert_eq!(U512([1, 0, 0, MAX-1, MAX, MAX, 0, 0]), result);
1971
1972 let result = U256([MAX, MAX, MAX, 0]).full_mul(U256([MAX, MAX, MAX, MAX]));
1973 assert_eq!(U512([1, 0, 0, MAX, MAX-1, MAX, MAX, 0]), result);
1974
1975 let result = U256([MAX, MAX, MAX, MAX]).full_mul(U256([MAX, MAX, MAX, 0]));
1976 assert_eq!(U512([1, 0, 0, MAX, MAX-1, MAX, MAX, 0]), result);
1977
1978 let result = U256([MAX, MAX, MAX, MAX]).full_mul(U256([MAX, MAX, MAX, MAX]));
1979 assert_eq!(U512([1, 0, 0, 0, MAX-1, MAX, MAX, MAX]), result);
1980
1981 let result = U256([0, 0, 0, MAX]).full_mul(U256([0, 0, 0, MAX]));
1982 assert_eq!(U512([0, 0, 0, 0, 0, 0, 1, MAX-1]), result);
1983
1984 let result = U256([1, 0, 0, 0]).full_mul(U256([0, 0, 0, MAX]));
1985 assert_eq!(U512([0, 0, 0, MAX, 0, 0, 0, 0]), result);
1986
1987 let result = U256([1, 2, 3, 4]).full_mul(U256([5, 0, 0, 0]));
1988 assert_eq!(U512([5, 10, 15, 20, 0, 0, 0, 0]), result);
1989
1990 let result = U256([1, 2, 3, 4]).full_mul(U256([0, 6, 0, 0]));
1991 assert_eq!(U512([0, 6, 12, 18, 24, 0, 0, 0]), result);
1992
1993 let result = U256([1, 2, 3, 4]).full_mul(U256([0, 0, 7, 0]));
1994 assert_eq!(U512([0, 0, 7, 14, 21, 28, 0, 0]), result);
1995
1996 let result = U256([1, 2, 3, 4]).full_mul(U256([0, 0, 0, 8]));
1997 assert_eq!(U512([0, 0, 0, 8, 16, 24, 32, 0]), result);
1998
1999 let result = U256([1, 2, 3, 4]).full_mul(U256([5, 6, 7, 8]));
2000 assert_eq!(U512([5, 16, 34, 60, 61, 52, 32, 0]), result);
2001 }
2002
2003 #[test]
2004 fn u256_multi_muls2() {
2005
2006 let (result, _) = U256([0, 0, 0, 0]).overflowing_mul(U256([0, 0, 0, 0]));
2007 assert_eq!(U256([0, 0, 0, 0]), result);
2008
2009 let (result, _) = U256([1, 0, 0, 0]).overflowing_mul(U256([1, 0, 0, 0]));
2010 assert_eq!(U256([1, 0, 0, 0]), result);
2011
2012 let (result, _) = U256([5, 0, 0, 0]).overflowing_mul(U256([5, 0, 0, 0]));
2013 assert_eq!(U256([25, 0, 0, 0]), result);
2014
2015 let (result, _) = U256([0, 5, 0, 0]).overflowing_mul(U256([0, 5, 0, 0]));
2016 assert_eq!(U256([0, 0, 25, 0]), result);
2017
2018 let (result, _) = U256([0, 0, 0, 1]).overflowing_mul(U256([1, 0, 0, 0]));
2019 assert_eq!(U256([0, 0, 0, 1]), result);
2020
2021 let (result, _) = U256([0, 0, 0, 5]).overflowing_mul(U256([2, 0, 0, 0]));
2022 assert_eq!(U256([0, 0, 0, 10]), result);
2023
2024 let (result, _) = U256([0, 0, 1, 0]).overflowing_mul(U256([0, 5, 0, 0]));
2025 assert_eq!(U256([0, 0, 0, 5]), result);
2026
2027 let (result, _) = U256([0, 0, 8, 0]).overflowing_mul(U256([0, 0, 7, 0]));
2028 assert_eq!(U256([0, 0, 0, 0]), result);
2029
2030 let (result, _) = U256([2, 0, 0, 0]).overflowing_mul(U256([0, 5, 0, 0]));
2031 assert_eq!(U256([0, 10, 0, 0]), result);
2032
2033 let (result, _) = U256([1, 0, 0, 0]).overflowing_mul(U256([0, 0, 0, u64::max_value()]));
2034 assert_eq!(U256([0, 0, 0, u64::max_value()]), result);
2035
2036 let x1: U256 = "0000000000000000000000000000000000000000000000000000012365124623".into();
2037 let x2sqr_right: U256 = "000000000000000000000000000000000000000000014baeef72e0378e2328c9".into();
2038 let x1sqr = x1 * x1;
2039 assert_eq!(x2sqr_right, x1sqr);
2040
2041 let x1cube = x1sqr * x1;
2042 let x1cube_right: U256 = "0000000000000000000000000000000001798acde139361466f712813717897b".into();
2043 assert_eq!(x1cube_right, x1cube);
2044
2045 let x1quad = x1cube * x1;
2046 let x1quad_right: U256 = "000000000000000000000001adbdd6bd6ff027485484b97f8a6a4c7129756dd1".into();
2047 assert_eq!(x1quad_right, x1quad);
2048
2049 let x1penta = x1quad * x1;
2050 let x1penta_right: U256 = "00000000000001e92875ac24be246e1c57e0507e8c46cc8d233b77f6f4c72993".into();
2051 assert_eq!(x1penta_right, x1penta);
2052
2053 let x1septima = x1penta * x1;
2054 let x1septima_right: U256 = "00022cca1da3f6e5722b7d3cc5bbfb486465ebc5a708dd293042f932d7eee119".into();
2055 assert_eq!(x1septima_right, x1septima);
2056 }
2057
2058 #[test]
2059 fn example() {
2060 let mut val: U256 = 1023.into();
2061 for _ in 0..200 { val = val * 2.into() }
2062 assert_eq!(&format!("{}", val), "1643897619276947051879427220465009342380213662639797070513307648");
2063 }
2064
2065 #[test]
2066 fn little_endian() {
2067 let number: U256 = "00022cca1da3f6e5722b7d3cc5bbfb486465ebc5a708dd293042f932d7eee119".into();
2068 let expected = [
2069 0x19, 0xe1, 0xee, 0xd7,
2070 0x32, 0xf9, 0x42, 0x30,
2071 0x29, 0xdd, 0x08, 0xa7,
2072 0xc5, 0xeb, 0x65, 0x64,
2073 0x48, 0xfb, 0xbb, 0xc5,
2074 0x3c, 0x7d, 0x2b, 0x72,
2075 0xe5, 0xf6, 0xa3, 0x1d,
2076 0xca, 0x2c, 0x02, 0x00
2077 ];
2078 let mut result = [0u8; 32];
2079 number.to_little_endian(&mut result);
2080 assert_eq!(expected, result);
2081 }
2082
2083 #[test]
2084 fn slice_roundtrip() {
2085 let raw = [
2086 1u8, 2, 3, 5, 7, 11, 13, 17,
2087 19, 23, 29, 31, 37, 41, 43, 47,
2088 53, 59, 61, 67, 71, 73, 79, 83,
2089 89, 97, 101, 103, 107, 109, 113, 127
2090 ];
2091
2092 let u256: U256 = (&raw[..]).into();
2093
2094 let mut new_raw = [0u8; 32];
2095
2096 u256.to_big_endian(&mut new_raw);
2097
2098 assert_eq!(&raw, &new_raw);
2099 }
2100
2101 #[test]
2102 fn slice_roundtrip_le() {
2103 let raw = [
2104 1u8, 2, 3, 5, 7, 11, 13, 17,
2105 19, 23, 29, 31, 37, 41, 43, 47,
2106 53, 59, 61, 67, 71, 73, 79, 83,
2107 89, 97, 101, 103, 107, 109, 113, 127
2108 ];
2109
2110 let u256 = U256::from_little_endian(&raw[..]);
2111
2112 let mut new_raw = [0u8; 32];
2113
2114 u256.to_little_endian(&mut new_raw);
2115
2116 assert_eq!(&raw, &new_raw);
2117 }
2118
2119 #[test]
2120 fn slice_roundtrip_le2() {
2121 let raw = [
2122 2, 3, 5, 7, 11, 13, 17,
2123 19, 23, 29, 31, 37, 41, 43, 47,
2124 53, 59, 61, 67, 71, 73, 79, 83,
2125 89, 97, 101, 103, 107, 109, 113, 127
2126 ];
2127
2128 let u256 = U256::from_little_endian(&raw[..]);
2129
2130 let mut new_raw = [0u8; 32];
2131
2132 u256.to_little_endian(&mut new_raw);
2133
2134 assert_eq!(&raw, &new_raw[..31]);
2135 }
2136
2137 #[test]
2138 fn modular_inverse() {
2139 let modulo = U256::from_dec_str("115792089210356248762697446949407573530086143415290314195533631308867097853951").unwrap();
2140 let number = U256::from_dec_str("48439561293906451759052585252797914202762949526041747995844080717082404635286").unwrap();
2141 let mod_inv = number.mod_inverse(modulo);
2142 assert_eq!(
2143 mod_inv,
2144 U256::from_dec_str("101489101214698129329668954935570020318890663581888936938143465331216272806456").unwrap()
2145 )
2146 }
2147
2148 #[test]
2149 fn fixed_arrays_roundtrip() {
2150 let raw: U256 = "7094875209347850239487502394881".into();
2151 let array: [u8; 32] = raw.into();
2152 let new_raw = array.into();
2153
2154 assert_eq!(raw, new_raw);
2155 }
2156
2157 #[test]
2158 fn from_little_endian() {
2159 let source: [u8; 32] = [
2160 1, 0, 0, 0, 0, 0, 0, 0,
2161 0, 0, 0, 0, 0, 0, 0, 0,
2162 0, 0, 0, 0, 0, 0, 0, 0,
2163 0, 0, 0, 0, 0, 0, 0, 0,
2164 ];
2165
2166 let number = U256::from_little_endian(&source[..]);
2167
2168 assert_eq!(U256::from(1), number);
2169 }
2170
2171 #[test]
2172 fn from_big_endian() {
2173 let source: [u8; 32] = [
2174 0, 0, 0, 0, 0, 0, 0, 0,
2175 0, 0, 0, 0, 0, 0, 0, 0,
2176 0, 0, 0, 0, 0, 0, 0, 0,
2177 0, 0, 0, 0, 0, 0, 0, 1,
2178 ];
2179
2180 let number = U256::from_big_endian(&source[..]);
2181
2182 assert_eq!(U256::from(1), number);
2183 }
2184
2185 #[test]
2186 fn leading_zeros() {
2187 assert_eq!(U256::from("000000000000000000000001adbdd6bd6ff027485484b97f8a6a4c7129756dd1").leading_zeros(), 95);
2188 assert_eq!(U256::from("f00000000000000000000001adbdd6bd6ff027485484b97f8a6a4c7129756dd1").leading_zeros(), 0);
2189 assert_eq!(U256::from("0000000000000000000000000000000000000000000000000000000000000001").leading_zeros(), 255);
2190 assert_eq!(U256::from("0000000000000000000000000000000000000000000000000000000000000000").leading_zeros(), 256);
2191 }
2192
2193 #[test]
2194 fn trailing_zeros() {
2195 assert_eq!(U256::from("1adbdd6bd6ff027485484b97f8a6a4c7129756dd100000000000000000000000").trailing_zeros(), 92);
2196 assert_eq!(U256::from("1adbdd6bd6ff027485484b97f8a6a4c7129756dd10000000000000000000000f").trailing_zeros(), 0);
2197 assert_eq!(U256::from("8000000000000000000000000000000000000000000000000000000000000000").trailing_zeros(), 255);
2198 assert_eq!(U256::from("0000000000000000000000000000000000000000000000000000000000000000").trailing_zeros(), 256);
2199 }
2200
2201 mod laws {
2202 use uint::{U128, U256, U512};
2203
2204 macro_rules! uint_arbitrary {
2205 ($uint:ty, $n_bytes:tt) => {
2206 impl ::quickcheck::Arbitrary for $uint {
2207 fn arbitrary<G: ::quickcheck::Gen>(g: &mut G) -> Self {
2208 let mut res = [0u8; $n_bytes];
2209
2210 let p = g.next_f64();
2211 let range =
2212 if p < 0.1 {
2213 $n_bytes
2214 } else if p < 0.2 {
2215 $n_bytes / 2
2216 } else {
2217 $n_bytes / 5
2218 };
2219
2220 let size = g.gen_range(0, range);
2221 g.fill_bytes(&mut res[..size]);
2222
2223 Self::from(res)
2224 }
2225 }
2226 }
2227 }
2228
2229 uint_arbitrary!(U128, 16);
2230 uint_arbitrary!(U256, 32);
2231 uint_arbitrary!(U512, 64);
2232
2233 macro_rules! o_try {
2234 ($o:expr) => {{
2235 let (val, o) = $o;
2236 if o { return ::quickcheck::TestResult::discard(); }
2237 val
2238 }};
2239 }
2240
2241 macro_rules! try_expr {
2242 ($any:ident) => { $any };
2243 ($first:ident + $($second:tt)*) => {
2244 o_try!($first.overflowing_add(try_expr!($($second)*)))
2245 };
2246 (($($anything:tt)*)) => {
2247 try_expr!($($anything)*)
2248 };
2249 ($first:ident * $($second:tt)*) => {
2250 o_try!($first.overflowing_mul(try_expr!($($second)*)))
2251 };
2252 (($($first:tt)*) + $($rest:tt)*) => {{
2253 let first = try_expr!($($first)*);
2254 try_expr!(first + $($rest)*)
2255 }};
2256 (($($first:tt)*) * $($rest:tt)*) => {{
2257 let first = try_expr!($($first)*);
2258 try_expr!(first * $($rest)*)
2259 }};
2260 }
2261
2262 macro_rules! uint_laws {
2263 ($mod_name:ident, $uint_ty:ident) => {
2264 mod $mod_name {
2265 use quickcheck::TestResult;
2266 use uint::*;
2267
2268 quickcheck! {
2269 fn associative_add(x: $uint_ty, y: $uint_ty, z: $uint_ty) -> TestResult {
2270 TestResult::from_bool(
2271 try_expr!((x + y) + z) ==
2272 try_expr!(x + (y + z))
2273 )
2274 }
2275 }
2276
2277 quickcheck! {
2278 fn associative_mul(x: $uint_ty, y: $uint_ty, z: $uint_ty) -> TestResult {
2279 TestResult::from_bool(
2280 try_expr!((x * y) * z) == try_expr!(x * (y * z))
2281 )
2282 }
2283 }
2284
2285 quickcheck! {
2286 fn commutative_add(x: $uint_ty, y: $uint_ty) -> TestResult {
2287 TestResult::from_bool(
2288 try_expr!(x + y) == try_expr!(y + x)
2289 )
2290 }
2291 }
2292
2293 quickcheck! {
2294 fn commutative_mul(x: $uint_ty, y: $uint_ty) -> TestResult {
2295 TestResult::from_bool(
2296 try_expr!(x * y) == try_expr!(y * x)
2297 )
2298 }
2299 }
2300
2301 quickcheck! {
2302 fn identity_add(x: $uint_ty) -> bool {
2303 x + $uint_ty::zero() == x
2304 }
2305 }
2306
2307 quickcheck! {
2308 fn identity_mul(x: $uint_ty) -> bool {
2309 x * $uint_ty::one() == x
2310 }
2311 }
2312
2313 quickcheck! {
2314 fn identity_div(x: $uint_ty) -> bool {
2315 x / $uint_ty::one() == x
2316 }
2317 }
2318
2319 quickcheck! {
2320 fn absorbing_rem(x: $uint_ty) -> bool {
2321 x % $uint_ty::one() == $uint_ty::zero()
2322 }
2323 }
2324
2325 quickcheck! {
2326 fn absorbing_sub(x: $uint_ty) -> bool {
2327 x - x == $uint_ty::zero()
2328 }
2329 }
2330
2331 quickcheck! {
2332 fn absorbing_mul(x: $uint_ty) -> bool {
2333 x * $uint_ty::zero() == $uint_ty::zero()
2334 }
2335 }
2336
2337 quickcheck! {
2338 fn distributive_mul_over_add(x: $uint_ty, y: $uint_ty, z: $uint_ty) -> TestResult {
2339 TestResult::from_bool(
2340 try_expr!(x * (y + z)) == try_expr!((x * y) + (x * z)) &&
2341 try_expr!((x + y) * z) == try_expr!((x * z) + (y * z))
2342 )
2343 }
2344 }
2345
2346 quickcheck! {
2347 fn pow_mul(x: $uint_ty) -> TestResult {
2348 let (p2, o) = x.overflowing_pow($uint_ty::from(2));
2349 if o { return TestResult::discard(); }
2350 let (p3, o) = x.overflowing_pow($uint_ty::from(3));
2351 if o { return TestResult::discard(); }
2352
2353 TestResult::from_bool(
2354 p2 == x * x && p3 == x * x * x
2355 )
2356 }
2357 }
2358
2359 quickcheck! {
2360 fn add_increases(x: $uint_ty, y: $uint_ty) -> TestResult {
2361 if y.is_zero() {
2362 return TestResult::discard();
2363 }
2364
2365 TestResult::from_bool(
2366 try_expr!(x + y) > x
2367 )
2368 }
2369 }
2370
2371 quickcheck! {
2372 fn mul_increases(x: $uint_ty, y: $uint_ty) -> TestResult {
2373 if y.is_zero() {
2374 return TestResult::discard();
2375 }
2376
2377 TestResult::from_bool(
2378 try_expr!(x * y) >= x
2379 )
2380 }
2381 }
2382
2383 quickcheck! {
2384 fn div_decreases_dividend(x: $uint_ty, y: $uint_ty) -> TestResult {
2385 if y.is_zero() {
2386 return TestResult::discard();
2387 }
2388
2389 TestResult::from_bool(
2390 x / y <= x
2391 )
2392 }
2393 }
2394
2395 quickcheck! {
2396 fn rem_decreases_divisor(x: $uint_ty, y: $uint_ty) -> TestResult {
2397 if y.is_zero() {
2398 return TestResult::discard();
2399 }
2400
2401 TestResult::from_bool(
2402 x % y < y
2403 )
2404 }
2405 }
2406 }
2407 }
2408 }
2409
2410 uint_laws!(u128, U128);
2411 uint_laws!(u256, U256);
2412 uint_laws!(u512, U512);
2413 }
2414}