1use core::fmt;
33
34#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
36#[non_exhaustive]
37pub enum FromStrRadixErrKind {
38 InvalidCharacter,
40
41 InvalidLength,
43
44 UnsupportedRadix,
46}
47
48#[derive(Debug)]
49enum FromStrRadixErrSrc {
50 Hex(FromHexError),
51 Dec(FromDecStrErr),
52}
53
54impl fmt::Display for FromStrRadixErrSrc {
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 match self {
57 FromStrRadixErrSrc::Dec(d) => write!(f, "{}", d),
58 FromStrRadixErrSrc::Hex(h) => write!(f, "{}", h),
59 }
60 }
61}
62
63#[derive(Debug)]
65pub struct FromStrRadixErr {
66 kind: FromStrRadixErrKind,
67 source: Option<FromStrRadixErrSrc>,
68}
69
70impl FromStrRadixErr {
71 #[doc(hidden)]
72 pub fn unsupported() -> Self {
73 Self { kind: FromStrRadixErrKind::UnsupportedRadix, source: None }
74 }
75
76 pub fn kind(&self) -> FromStrRadixErrKind {
78 self.kind
79 }
80}
81
82impl fmt::Display for FromStrRadixErr {
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 if let Some(ref src) = self.source {
85 return write!(f, "{}", src);
86 }
87
88 match self.kind {
89 FromStrRadixErrKind::UnsupportedRadix => write!(f, "the given radix is not supported"),
90 FromStrRadixErrKind::InvalidCharacter => write!(f, "input contains an invalid character"),
91 FromStrRadixErrKind::InvalidLength => write!(f, "length not supported for radix or type"),
92 }
93 }
94}
95
96#[cfg(feature = "std")]
97impl std::error::Error for FromStrRadixErr {
98 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
99 match self.source {
100 Some(FromStrRadixErrSrc::Dec(ref d)) => Some(d),
101 Some(FromStrRadixErrSrc::Hex(ref h)) => Some(h),
102 None => None,
103 }
104 }
105}
106
107impl From<FromDecStrErr> for FromStrRadixErr {
108 fn from(e: FromDecStrErr) -> Self {
109 let kind = match e {
110 FromDecStrErr::InvalidCharacter => FromStrRadixErrKind::InvalidCharacter,
111 FromDecStrErr::InvalidLength => FromStrRadixErrKind::InvalidLength,
112 };
113
114 Self { kind, source: Some(FromStrRadixErrSrc::Dec(e)) }
115 }
116}
117
118impl From<FromHexError> for FromStrRadixErr {
119 fn from(e: FromHexError) -> Self {
120 let kind = match e.inner {
121 hex::FromHexError::InvalidHexCharacter { .. } => FromStrRadixErrKind::InvalidCharacter,
122 hex::FromHexError::InvalidStringLength => FromStrRadixErrKind::InvalidLength,
123 hex::FromHexError::OddLength => FromStrRadixErrKind::InvalidLength,
124 };
125
126 Self { kind, source: Some(FromStrRadixErrSrc::Hex(e)) }
127 }
128}
129
130#[derive(Debug, PartialEq)]
132pub enum FromDecStrErr {
133 InvalidCharacter,
135 InvalidLength,
137}
138
139impl fmt::Display for FromDecStrErr {
140 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141 write!(
142 f,
143 "{}",
144 match self {
145 FromDecStrErr::InvalidCharacter => "a character is not in the range 0-9",
146 FromDecStrErr::InvalidLength => "the number is too large for the type",
147 }
148 )
149 }
150}
151
152#[cfg(feature = "std")]
153impl std::error::Error for FromDecStrErr {}
154
155#[derive(Debug)]
156pub struct FromHexError {
157 inner: hex::FromHexError,
158}
159
160impl fmt::Display for FromHexError {
161 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162 write!(f, "{}", self.inner)
163 }
164}
165
166#[cfg(feature = "std")]
167impl std::error::Error for FromHexError {
168 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
169 Some(&self.inner)
170 }
171}
172
173#[doc(hidden)]
174impl From<hex::FromHexError> for FromHexError {
175 fn from(inner: hex::FromHexError) -> Self {
176 Self { inner }
177 }
178}
179
180#[macro_export]
181#[doc(hidden)]
182macro_rules! impl_map_from {
183 ($thing:ident, $from:ty, $to:ty) => {
184 impl From<$from> for $thing {
185 fn from(value: $from) -> $thing {
186 From::from(value as $to)
187 }
188 }
189 };
190}
191
192#[macro_export]
193#[doc(hidden)]
194macro_rules! impl_try_from_for_primitive {
195 ($from:ident, $to:ty) => {
196 impl $crate::core_::convert::TryFrom<$from> for $to {
197 type Error = &'static str;
198
199 #[inline]
200 fn try_from(u: $from) -> $crate::core_::result::Result<$to, &'static str> {
201 let $from(arr) = u;
202 if !u.fits_word() || arr[0] > <$to>::max_value() as u64 {
203 Err(concat!(
204 "integer overflow when casting to ",
205 stringify!($to)
206 ))
207 } else {
208 Ok(arr[0] as $to)
209 }
210 }
211 }
212 };
213}
214
215#[macro_export]
216#[doc(hidden)]
217macro_rules! uint_overflowing_binop {
218 ($name:ident, $n_words: tt, $self_expr: expr, $other: expr, $fn:expr) => {{
219 use $crate::core_ as core;
220 let $name(ref me) = $self_expr;
221 let $name(ref you) = $other;
222
223 let mut ret = [0u64; $n_words];
224 let ret_ptr = &mut ret as *mut [u64; $n_words] as *mut u64;
225 let mut carry = 0u64;
226 $crate::static_assertions::const_assert!(
227 core::isize::MAX as usize / core::mem::size_of::<u64>() > $n_words
228 );
229
230 use $crate::unroll;
233 unroll! {
234 for i in 0..$n_words {
235 use core::ptr;
236
237 if carry != 0 {
238 let (res1, overflow1) = ($fn)(me[i], you[i]);
239 let (res2, overflow2) = ($fn)(res1, carry);
240
241 unsafe {
242 *ret_ptr.offset(i as _) = res2
244 }
245 carry = (overflow1 as u8 + overflow2 as u8) as u64;
246 } else {
247 let (res, overflow) = ($fn)(me[i], you[i]);
248
249 unsafe {
250 *ret_ptr.offset(i as _) = res
252 }
253
254 carry = overflow as u64;
255 }
256 }
257 }
258
259 ($name(ret), carry > 0)
260 }};
261}
262
263#[macro_export]
264#[doc(hidden)]
265macro_rules! uint_full_mul_reg {
266 ($name:ident, 8, $self_expr:expr, $other:expr) => {
267 $crate::uint_full_mul_reg!($name, 8, $self_expr, $other, |a, b| a != 0 || b != 0);
268 };
269 ($name:ident, $n_words:tt, $self_expr:expr, $other:expr) => {
270 $crate::uint_full_mul_reg!($name, $n_words, $self_expr, $other, |_, _| true);
271 };
272 ($name:ident, $n_words:tt, $self_expr:expr, $other:expr, $check:expr) => {{
273 {
274 #![allow(unused_assignments)]
275
276 let $name(ref me) = $self_expr;
277 let $name(ref you) = $other;
278 let mut ret = [0u64; $n_words * 2];
279
280 use $crate::unroll;
281 unroll! {
282 for i in 0..$n_words {
283 let mut carry = 0u64;
284 let b = you[i];
285
286 unroll! {
287 for j in 0..$n_words {
288 if $check(me[j], carry) {
289 let a = me[j];
290
291 let (hi, low) = Self::split_u128(a as u128 * b as u128);
292
293 let overflow = {
294 let existing_low = &mut ret[i + j];
295 let (low, o) = low.overflowing_add(*existing_low);
296 *existing_low = low;
297 o
298 };
299
300 carry = {
301 let existing_hi = &mut ret[i + j + 1];
302 let hi = hi + overflow as u64;
303 let (hi, o0) = hi.overflowing_add(carry);
304 let (hi, o1) = hi.overflowing_add(*existing_hi);
305 *existing_hi = hi;
306
307 (o0 | o1) as u64
308 }
309 }
310 }
311 }
312 }
313 }
314
315 ret
316 }
317 }};
318}
319
320#[macro_export]
321#[doc(hidden)]
322macro_rules! uint_overflowing_mul {
323 ($name:ident, $n_words: tt, $self_expr: expr, $other: expr) => {{
324 let ret: [u64; $n_words * 2] =
325 $crate::uint_full_mul_reg!($name, $n_words, $self_expr, $other);
326
327 let ret: [[u64; $n_words]; 2] = unsafe { $crate::core_::mem::transmute(ret) };
329
330 #[inline(always)]
332 fn any_nonzero(arr: &[u64; $n_words]) -> bool {
333 use $crate::unroll;
334 unroll! {
335 for i in 0..$n_words {
336 if arr[i] != 0 {
337 return true;
338 }
339 }
340 }
341
342 false
343 }
344
345 ($name(ret[0]), any_nonzero(&ret[1]))
346 }};
347}
348
349#[macro_export]
350#[doc(hidden)]
351macro_rules! overflowing {
352 ($op: expr, $overflow: expr) => {{
353 let (overflow_x, overflow_overflow) = $op;
354 $overflow |= overflow_overflow;
355 overflow_x
356 }};
357 ($op: expr) => {{
358 let (overflow_x, _overflow_overflow) = $op;
359 overflow_x
360 }};
361}
362
363#[macro_export]
364#[doc(hidden)]
365macro_rules! panic_on_overflow {
366 ($name: expr) => {
367 if $name {
368 panic!("arithmetic operation overflow")
369 }
370 };
371}
372
373#[macro_export]
374#[doc(hidden)]
375macro_rules! impl_mul_from {
376 ($name: ty, $other: ident) => {
377 impl $crate::core_::ops::Mul<$other> for $name {
378 type Output = $name;
379
380 fn mul(self, other: $other) -> $name {
381 let bignum: $name = other.into();
382 let (result, overflow) = self.overflowing_mul(bignum);
383 $crate::panic_on_overflow!(overflow);
384 result
385 }
386 }
387
388 impl<'a> $crate::core_::ops::Mul<&'a $other> for $name {
389 type Output = $name;
390
391 fn mul(self, other: &'a $other) -> $name {
392 let bignum: $name = (*other).into();
393 let (result, overflow) = self.overflowing_mul(bignum);
394 $crate::panic_on_overflow!(overflow);
395 result
396 }
397 }
398
399 impl<'a> $crate::core_::ops::Mul<&'a $other> for &'a $name {
400 type Output = $name;
401
402 fn mul(self, other: &'a $other) -> $name {
403 let bignum: $name = (*other).into();
404 let (result, overflow) = self.overflowing_mul(bignum);
405 $crate::panic_on_overflow!(overflow);
406 result
407 }
408 }
409
410 impl<'a> $crate::core_::ops::Mul<$other> for &'a $name {
411 type Output = $name;
412
413 fn mul(self, other: $other) -> $name {
414 let bignum: $name = other.into();
415 let (result, overflow) = self.overflowing_mul(bignum);
416 $crate::panic_on_overflow!(overflow);
417 result
418 }
419 }
420
421 impl $crate::core_::ops::MulAssign<$other> for $name {
422 fn mul_assign(&mut self, other: $other) {
423 let result = *self * other;
424 *self = result
425 }
426 }
427 };
428}
429
430#[macro_export]
431#[doc(hidden)]
432macro_rules! impl_mul_for_primitive {
433 ($name: ty, $other: ident) => {
434 impl $crate::core_::ops::Mul<$other> for $name {
435 type Output = $name;
436
437 fn mul(self, other: $other) -> $name {
438 let (result, carry) = self.overflowing_mul_u64(other as u64);
439 $crate::panic_on_overflow!(carry > 0);
440 result
441 }
442 }
443
444 impl<'a> $crate::core_::ops::Mul<&'a $other> for $name {
445 type Output = $name;
446
447 fn mul(self, other: &'a $other) -> $name {
448 let (result, carry) = self.overflowing_mul_u64(*other as u64);
449 $crate::panic_on_overflow!(carry > 0);
450 result
451 }
452 }
453
454 impl<'a> $crate::core_::ops::Mul<&'a $other> for &'a $name {
455 type Output = $name;
456
457 fn mul(self, other: &'a $other) -> $name {
458 let (result, carry) = self.overflowing_mul_u64(*other as u64);
459 $crate::panic_on_overflow!(carry > 0);
460 result
461 }
462 }
463
464 impl<'a> $crate::core_::ops::Mul<$other> for &'a $name {
465 type Output = $name;
466
467 fn mul(self, other: $other) -> $name {
468 let (result, carry) = self.overflowing_mul_u64(other as u64);
469 $crate::panic_on_overflow!(carry > 0);
470 result
471 }
472 }
473
474 impl $crate::core_::ops::MulAssign<$other> for $name {
475 fn mul_assign(&mut self, other: $other) {
476 let result = *self * (other as u64);
477 *self = result
478 }
479 }
480 };
481}
482
483#[macro_export]
484macro_rules! construct_uint {
485 ( $(#[$attr:meta])* $visibility:vis struct $name:ident (1); ) => {
486 $crate::construct_uint!{ @construct $(#[$attr])* $visibility struct $name (1); }
487 };
488
489 ( $(#[$attr:meta])* $visibility:vis struct $name:ident ( $n_words:tt ); ) => {
490 $crate::construct_uint! { @construct $(#[$attr])* $visibility struct $name ($n_words); }
491
492 impl $crate::core_::convert::From<u128> for $name {
493 fn from(value: u128) -> $name {
494 let mut ret = [0; $n_words];
495 ret[0] = value as u64;
496 ret[1] = (value >> 64) as u64;
497 $name(ret)
498 }
499 }
500
501 impl $crate::core_::convert::From<i128> for $name {
502 fn from(value: i128) -> $name {
503 match value >= 0 {
504 true => From::from(value as u128),
505 false => { panic!("Unsigned integer can't be created from negative value"); }
506 }
507 }
508 }
509
510 impl $name {
511 #[inline]
513 pub const fn low_u128(&self) -> u128 {
514 let &$name(ref arr) = self;
515 ((arr[1] as u128) << 64) + arr[0] as u128
516 }
517
518 #[inline]
524 pub fn as_u128(&self) -> u128 {
525 let &$name(ref arr) = self;
526 for i in 2..$n_words {
527 if arr[i] != 0 {
528 panic!("Integer overflow when casting to u128")
529 }
530
531 }
532 self.low_u128()
533 }
534 }
535
536 impl $crate::core_::convert::TryFrom<$name> for u128 {
537 type Error = &'static str;
538
539 #[inline]
540 fn try_from(u: $name) -> $crate::core_::result::Result<u128, &'static str> {
541 let $name(arr) = u;
542 for i in 2..$n_words {
543 if arr[i] != 0 {
544 return Err("integer overflow when casting to u128");
545 }
546 }
547 Ok(((arr[1] as u128) << 64) + arr[0] as u128)
548 }
549 }
550
551 impl $crate::core_::convert::TryFrom<$name> for i128 {
552 type Error = &'static str;
553
554 #[inline]
555 fn try_from(u: $name) -> $crate::core_::result::Result<i128, &'static str> {
556 let err_str = "integer overflow when casting to i128";
557 let i = u128::try_from(u).map_err(|_| err_str)?;
558 if i > i128::max_value() as u128 {
559 Err(err_str)
560 } else {
561 Ok(i as i128)
562 }
563 }
564 }
565 };
566 ( @construct $(#[$attr:meta])* $visibility:vis struct $name:ident ( $n_words:tt ); ) => {
567 #[repr(C)]
569 $(#[$attr])*
570 #[derive(Copy, Clone, Eq, PartialEq, Hash)]
571 $visibility struct $name (pub [u64; $n_words]);
572
573 impl AsRef<[u64]> for $name {
575 #[inline]
576 fn as_ref(&self) -> &[u64] {
577 &self.0
578 }
579 }
580
581 impl<'a> From<&'a $name> for $name {
582 fn from(x: &'a $name) -> $name {
583 *x
584 }
585 }
586
587 impl $name {
588 const WORD_BITS: usize = 64;
589 pub const MAX: $name = $name([u64::max_value(); $n_words]);
591
592 pub fn from_str_radix(txt: &str, radix: u32) -> Result<Self, $crate::FromStrRadixErr> {
595 let parsed = match radix {
596 10 => Self::from_dec_str(txt)?,
597 16 => core::str::FromStr::from_str(txt)?,
598 _ => return Err($crate::FromStrRadixErr::unsupported()),
599 };
600
601 Ok(parsed)
602 }
603
604 pub fn from_dec_str(value: &str) -> $crate::core_::result::Result<Self, $crate::FromDecStrErr> {
606 let mut res = Self::default();
607 for b in value.bytes().map(|b| b.wrapping_sub(b'0')) {
608 if b > 9 {
610 return Err($crate::FromDecStrErr::InvalidCharacter)
611 }
612 let (r, overflow) = res.overflowing_mul_u64(10);
613 if overflow > 0 {
614 return Err($crate::FromDecStrErr::InvalidLength);
615 }
616 let (r, overflow) = r.overflowing_add(b.into());
617 if overflow {
618 return Err($crate::FromDecStrErr::InvalidLength);
619 }
620 res = r;
621 }
622 Ok(res)
623 }
624
625 #[inline]
627 pub const fn low_u32(&self) -> u32 {
628 let &$name(ref arr) = self;
629 arr[0] as u32
630 }
631
632 #[inline]
634 pub const fn low_u64(&self) -> u64 {
635 let &$name(ref arr) = self;
636 arr[0]
637 }
638
639 #[inline]
645 pub fn as_u32(&self) -> u32 {
646 let &$name(ref arr) = self;
647 if !self.fits_word() || arr[0] > u32::max_value() as u64 {
648 panic!("Integer overflow when casting to u32")
649 }
650 self.as_u64() as u32
651 }
652
653 #[inline]
659 pub fn as_u64(&self) -> u64 {
660 let &$name(ref arr) = self;
661 if !self.fits_word() {
662 panic!("Integer overflow when casting to u64")
663 }
664 arr[0]
665 }
666
667 #[inline]
673 pub fn as_usize(&self) -> usize {
674 let &$name(ref arr) = self;
675 if !self.fits_word() || arr[0] > usize::max_value() as u64 {
676 panic!("Integer overflow when casting to usize")
677 }
678 arr[0] as usize
679 }
680
681 #[inline]
683 pub fn is_zero(&self) -> bool {
684 let &$name(ref arr) = self;
685 for i in 0..$n_words { if arr[i] != 0 { return false; } }
686 return true;
687 }
688
689 #[inline]
691 fn fits_word(&self) -> bool {
692 let &$name(ref arr) = self;
693 for i in 1..$n_words { if arr[i] != 0 { return false; } }
694 return true;
695 }
696
697
698 #[inline]
700 pub fn bits(&self) -> usize {
701 let &$name(ref arr) = self;
702 for i in 1..$n_words {
703 if arr[$n_words - i] > 0 { return (0x40 * ($n_words - i + 1)) - arr[$n_words - i].leading_zeros() as usize; }
704 }
705 0x40 - arr[0].leading_zeros() as usize
706 }
707
708 #[inline]
714 pub const fn bit(&self, index: usize) -> bool {
715 let &$name(ref arr) = self;
716 arr[index / 64] & (1 << (index % 64)) != 0
717 }
718
719 pub fn leading_zeros(&self) -> u32 {
721 let mut r = 0;
722 for i in 0..$n_words {
723 let w = self.0[$n_words - i - 1];
724 if w == 0 {
725 r += 64;
726 } else {
727 r += w.leading_zeros();
728 break;
729 }
730 }
731 r
732 }
733
734 pub fn trailing_zeros(&self) -> u32 {
736 let mut r = 0;
737 for i in 0..$n_words {
738 let w = self.0[i];
739 if w == 0 {
740 r += 64;
741 } else {
742 r += w.trailing_zeros();
743 break;
744 }
745 }
746 r
747 }
748
749 #[inline]
755 pub const fn byte(&self, index: usize) -> u8 {
756 let &$name(ref arr) = self;
757 (arr[index / 8] >> (((index % 8)) * 8)) as u8
758 }
759
760 #[inline]
762 pub fn to_big_endian(&self, bytes: &mut [u8]) {
763 use $crate::byteorder::{ByteOrder, BigEndian};
764 debug_assert!($n_words * 8 == bytes.len());
765 for i in 0..$n_words {
766 BigEndian::write_u64(&mut bytes[8 * i..], self.0[$n_words - i - 1]);
767 }
768 }
769
770 #[inline]
772 pub fn to_little_endian(&self, bytes: &mut [u8]) {
773 use $crate::byteorder::{ByteOrder, LittleEndian};
774 debug_assert!($n_words * 8 == bytes.len());
775 for i in 0..$n_words {
776 LittleEndian::write_u64(&mut bytes[8 * i..], self.0[i]);
777 }
778 }
779
780
781 #[inline]
787 pub fn exp10(n: usize) -> Self {
788 match n {
789 0 => Self::from(1u64),
790 _ => Self::exp10(n - 1) * 10u32
791 }
792 }
793
794 #[inline]
796 pub const fn zero() -> Self {
797 Self([0; $n_words])
798 }
799
800 #[inline]
802 pub fn one() -> Self {
803 From::from(1u64)
804 }
805
806 #[inline]
808 pub fn max_value() -> Self {
809 let mut result = [0; $n_words];
810 for i in 0..$n_words {
811 result[i] = u64::max_value();
812 }
813 $name(result)
814 }
815
816 fn full_shl(self, shift: u32) -> [u64; $n_words + 1] {
817 debug_assert!(shift < Self::WORD_BITS as u32);
818 let mut u = [0u64; $n_words + 1];
819 let u_lo = self.0[0] << shift;
820 let u_hi = self >> (Self::WORD_BITS as u32 - shift);
821 u[0] = u_lo;
822 u[1..].copy_from_slice(&u_hi.0[..]);
823 u
824 }
825
826 fn full_shr(u: [u64; $n_words + 1], shift: u32) -> Self {
827 debug_assert!(shift < Self::WORD_BITS as u32);
828 let mut res = Self::zero();
829 for i in 0..$n_words {
830 res.0[i] = u[i] >> shift;
831 }
832 if shift > 0 {
834 for i in 1..=$n_words {
835 res.0[i - 1] |= u[i] << (Self::WORD_BITS as u32 - shift);
836 }
837 }
838 res
839 }
840
841 fn full_mul_u64(self, by: u64) -> [u64; $n_words + 1] {
842 let (prod, carry) = self.overflowing_mul_u64(by);
843 let mut res = [0u64; $n_words + 1];
844 res[..$n_words].copy_from_slice(&prod.0[..]);
845 res[$n_words] = carry;
846 res
847 }
848
849 fn div_mod_small(mut self, other: u64) -> (Self, Self) {
850 let mut rem = 0u64;
851 self.0.iter_mut().rev().for_each(|d| {
852 let (q, r) = Self::div_mod_word(rem, *d, other);
853 *d = q;
854 rem = r;
855 });
856 (self, rem.into())
857 }
858
859 fn div_mod_knuth(self, mut v: Self, n: usize, m: usize) -> (Self, Self) {
861 debug_assert!(self.bits() >= v.bits() && !v.fits_word());
862 debug_assert!(n + m <= $n_words);
863 let shift = v.0[n - 1].leading_zeros();
868 v <<= shift;
869 let mut u = self.full_shl(shift);
871
872 let mut q = Self::zero();
874 let v_n_1 = v.0[n - 1];
875 let v_n_2 = v.0[n - 2];
876
877 for j in (0..=m).rev() {
880 let u_jn = u[j + n];
881
882 let mut q_hat = if u_jn < v_n_1 {
888 let (mut q_hat, mut r_hat) = Self::div_mod_word(u_jn, u[j + n - 1], v_n_1);
889 loop {
891 let (hi, lo) = Self::split_u128(u128::from(q_hat) * u128::from(v_n_2));
893 if (hi, lo) <= (r_hat, u[j + n - 2]) {
894 break;
895 }
896 q_hat -= 1;
898 let (new_r_hat, overflow) = r_hat.overflowing_add(v_n_1);
899 r_hat = new_r_hat;
900 if overflow {
902 break;
903 }
904 }
905 q_hat
906 } else {
907 u64::max_value()
909 };
910
911 let q_hat_v = v.full_mul_u64(q_hat);
919 let c = Self::sub_slice(&mut u[j..], &q_hat_v[..n + 1]);
921
922 if c {
926 q_hat -= 1;
927 let c = Self::add_slice(&mut u[j..], &v.0[..n]);
929 u[j + n] = u[j + n].wrapping_add(u64::from(c));
930 }
931
932 q.0[j] = q_hat;
934 }
935
936 let remainder = Self::full_shr(u, shift);
938
939 (q, remainder)
940 }
941
942 fn words(bits: usize) -> usize {
944 debug_assert!(bits > 0);
945 1 + (bits - 1) / Self::WORD_BITS
946 }
947
948 pub fn div_mod(mut self, mut other: Self) -> (Self, Self) {
954 use $crate::core_::cmp::Ordering;
955
956 let my_bits = self.bits();
957 let your_bits = other.bits();
958
959 assert!(your_bits != 0, "division by zero");
960
961 if my_bits < your_bits {
963 return (Self::zero(), self);
964 }
965
966 if your_bits <= Self::WORD_BITS {
967 return self.div_mod_small(other.low_u64());
968 }
969
970 let (n, m) = {
971 let my_words = Self::words(my_bits);
972 let your_words = Self::words(your_bits);
973 (your_words, my_words - your_words)
974 };
975
976 self.div_mod_knuth(other, n, m)
977 }
978
979 pub fn pow(self, expon: Self) -> Self {
986 if expon.is_zero() {
987 return Self::one()
988 }
989 let is_even = |x : &Self| x.low_u64() & 1 == 0;
990
991 let u_one = Self::one();
992 let mut y = u_one;
993 let mut n = expon;
994 let mut x = self;
995 while n > u_one {
996 if is_even(&n) {
997 x = x * x;
998 n = n >> 1usize;
999 } else {
1000 y = x * y;
1001 x = x * x;
1002 n.0[$n_words-1] = n.0[$n_words-1] & ((!0u64)>>1);
1004 n = n >> 1usize;
1005 }
1006 }
1007 x * y
1008 }
1009
1010 pub fn overflowing_pow(self, expon: Self) -> (Self, bool) {
1012 if expon.is_zero() { return (Self::one(), false) }
1013
1014 let is_even = |x : &Self| x.low_u64() & 1 == 0;
1015
1016 let u_one = Self::one();
1017 let mut y = u_one;
1018 let mut n = expon;
1019 let mut x = self;
1020 let mut overflow = false;
1021
1022 while n > u_one {
1023 if is_even(&n) {
1024 x = $crate::overflowing!(x.overflowing_mul(x), overflow);
1025 n = n >> 1usize;
1026 } else {
1027 y = $crate::overflowing!(x.overflowing_mul(y), overflow);
1028 x = $crate::overflowing!(x.overflowing_mul(x), overflow);
1029 n = (n - u_one) >> 1usize;
1030 }
1031 }
1032 let res = $crate::overflowing!(x.overflowing_mul(y), overflow);
1033 (res, overflow)
1034 }
1035
1036 pub fn checked_pow(self, expon: $name) -> Option<$name> {
1038 match self.overflowing_pow(expon) {
1039 (_, true) => None,
1040 (val, _) => Some(val),
1041 }
1042 }
1043
1044 #[inline(always)]
1046 pub fn overflowing_add(self, other: $name) -> ($name, bool) {
1047 $crate::uint_overflowing_binop!(
1048 $name,
1049 $n_words,
1050 self,
1051 other,
1052 u64::overflowing_add
1053 )
1054 }
1055
1056 pub fn saturating_add(self, other: $name) -> $name {
1058 match self.overflowing_add(other) {
1059 (_, true) => $name::max_value(),
1060 (val, false) => val,
1061 }
1062 }
1063
1064 pub fn checked_add(self, other: $name) -> Option<$name> {
1066 match self.overflowing_add(other) {
1067 (_, true) => None,
1068 (val, _) => Some(val),
1069 }
1070 }
1071
1072 #[inline(always)]
1074 pub fn overflowing_sub(self, other: $name) -> ($name, bool) {
1075 $crate::uint_overflowing_binop!(
1076 $name,
1077 $n_words,
1078 self,
1079 other,
1080 u64::overflowing_sub
1081 )
1082 }
1083
1084 pub fn saturating_sub(self, other: $name) -> $name {
1086 match self.overflowing_sub(other) {
1087 (_, true) => $name::zero(),
1088 (val, false) => val,
1089 }
1090 }
1091
1092 pub fn checked_sub(self, other: $name) -> Option<$name> {
1094 match self.overflowing_sub(other) {
1095 (_, true) => None,
1096 (val, _) => Some(val),
1097 }
1098 }
1099
1100 #[inline(always)]
1102 pub fn overflowing_mul(self, other: $name) -> ($name, bool) {
1103 $crate::uint_overflowing_mul!($name, $n_words, self, other)
1104 }
1105
1106 pub fn saturating_mul(self, other: $name) -> $name {
1108 match self.overflowing_mul(other) {
1109 (_, true) => $name::max_value(),
1110 (val, false) => val,
1111 }
1112 }
1113
1114 pub fn checked_mul(self, other: $name) -> Option<$name> {
1116 match self.overflowing_mul(other) {
1117 (_, true) => None,
1118 (val, _) => Some(val),
1119 }
1120 }
1121
1122 pub fn checked_div(self, other: $name) -> Option<$name> {
1124 if other.is_zero() {
1125 None
1126 } else {
1127 Some(self / other)
1128 }
1129 }
1130
1131 pub fn checked_rem(self, other: $name) -> Option<$name> {
1133 if other.is_zero() {
1134 None
1135 } else {
1136 Some(self % other)
1137 }
1138 }
1139
1140 pub fn overflowing_neg(self) -> ($name, bool) {
1142 if self.is_zero() {
1143 (self, false)
1144 } else {
1145 (!self, true)
1146 }
1147 }
1148
1149 pub fn checked_neg(self) -> Option<$name> {
1151 match self.overflowing_neg() {
1152 (_, true) => None,
1153 (zero, false) => Some(zero),
1154 }
1155 }
1156
1157 #[inline(always)]
1158 fn div_mod_word(hi: u64, lo: u64, y: u64) -> (u64, u64) {
1159 debug_assert!(hi < y);
1160 const TWO32: u64 = 1 << 32;
1166 let s = y.leading_zeros();
1167 let y = y << s;
1168 let (yn1, yn0) = Self::split(y);
1169 let un32 = (hi << s) | lo.checked_shr(64 - s).unwrap_or(0);
1170 let un10 = lo << s;
1171 let (un1, un0) = Self::split(un10);
1172 let mut q1 = un32 / yn1;
1173 let mut rhat = un32 - q1 * yn1;
1174
1175 while q1 >= TWO32 || q1 * yn0 > TWO32 * rhat + un1 {
1176 q1 -= 1;
1177 rhat += yn1;
1178 if rhat >= TWO32 {
1179 break;
1180 }
1181 }
1182
1183 let un21 = un32.wrapping_mul(TWO32).wrapping_add(un1).wrapping_sub(q1.wrapping_mul(y));
1184 let mut q0 = un21 / yn1;
1185 rhat = un21.wrapping_sub(q0.wrapping_mul(yn1));
1186
1187 while q0 >= TWO32 || q0 * yn0 > TWO32 * rhat + un0 {
1188 q0 -= 1;
1189 rhat += yn1;
1190 if rhat >= TWO32 {
1191 break;
1192 }
1193 }
1194
1195 let rem = un21.wrapping_mul(TWO32).wrapping_add(un0).wrapping_sub(y.wrapping_mul(q0));
1196 (q1 * TWO32 + q0, rem >> s)
1197 }
1198
1199 #[inline(always)]
1200 fn add_slice(a: &mut [u64], b: &[u64]) -> bool {
1201 Self::binop_slice(a, b, u64::overflowing_add)
1202 }
1203
1204 #[inline(always)]
1205 fn sub_slice(a: &mut [u64], b: &[u64]) -> bool {
1206 Self::binop_slice(a, b, u64::overflowing_sub)
1207 }
1208
1209 #[inline(always)]
1210 fn binop_slice(a: &mut [u64], b: &[u64], binop: impl Fn(u64, u64) -> (u64, bool) + Copy) -> bool {
1211 let mut c = false;
1212 a.iter_mut().zip(b.iter()).for_each(|(x, y)| {
1213 let (res, carry) = Self::binop_carry(*x, *y, c, binop);
1214 *x = res;
1215 c = carry;
1216 });
1217 c
1218 }
1219
1220 #[inline(always)]
1221 fn binop_carry(a: u64, b: u64, c: bool, binop: impl Fn(u64, u64) -> (u64, bool)) -> (u64, bool) {
1222 let (res1, overflow1) = b.overflowing_add(u64::from(c));
1223 let (res2, overflow2) = binop(a, res1);
1224 (res2, overflow1 || overflow2)
1225 }
1226
1227 #[inline(always)]
1228 const fn mul_u64(a: u64, b: u64, carry: u64) -> (u64, u64) {
1229 let (hi, lo) = Self::split_u128(a as u128 * b as u128 + carry as u128);
1230 (lo, hi)
1231 }
1232
1233 #[inline(always)]
1234 const fn split(a: u64) -> (u64, u64) {
1235 (a >> 32, a & 0xFFFF_FFFF)
1236 }
1237
1238 #[inline(always)]
1239 const fn split_u128(a: u128) -> (u64, u64) {
1240 ((a >> 64) as _, (a & 0xFFFFFFFFFFFFFFFF) as _)
1241 }
1242
1243
1244 fn overflowing_mul_u64(mut self, other: u64) -> (Self, u64) {
1247 let mut carry = 0u64;
1248
1249 for d in self.0.iter_mut() {
1250 let (res, c) = Self::mul_u64(*d, other, carry);
1251 *d = res;
1252 carry = c;
1253 }
1254
1255 (self, carry)
1256 }
1257
1258 pub fn from_big_endian(slice: &[u8]) -> Self {
1260 use $crate::byteorder::{ByteOrder, BigEndian};
1261 assert!($n_words * 8 >= slice.len());
1262
1263 let mut padded = [0u8; $n_words * 8];
1264 padded[$n_words * 8 - slice.len() .. $n_words * 8].copy_from_slice(&slice);
1265
1266 let mut ret = [0; $n_words];
1267 for i in 0..$n_words {
1268 ret[$n_words - i - 1] = BigEndian::read_u64(&padded[8 * i..]);
1269 }
1270
1271 $name(ret)
1272 }
1273
1274 pub fn from_little_endian(slice: &[u8]) -> Self {
1276 use $crate::byteorder::{ByteOrder, LittleEndian};
1277 assert!($n_words * 8 >= slice.len());
1278
1279 let mut padded = [0u8; $n_words * 8];
1280 padded[0..slice.len()].copy_from_slice(&slice);
1281
1282 let mut ret = [0; $n_words];
1283 for i in 0..$n_words {
1284 ret[i] = LittleEndian::read_u64(&padded[8 * i..]);
1285 }
1286
1287 $name(ret)
1288 }
1289 }
1290
1291 impl $crate::core_::convert::From<$name> for [u8; $n_words * 8] {
1292 fn from(number: $name) -> Self {
1293 let mut arr = [0u8; $n_words * 8];
1294 number.to_big_endian(&mut arr);
1295 arr
1296 }
1297 }
1298
1299 impl $crate::core_::convert::From<[u8; $n_words * 8]> for $name {
1300 fn from(bytes: [u8; $n_words * 8]) -> Self {
1301 Self::from(&bytes)
1302 }
1303 }
1304
1305 impl<'a> $crate::core_::convert::From<&'a [u8; $n_words * 8]> for $name {
1306 fn from(bytes: &[u8; $n_words * 8]) -> Self {
1307 Self::from(&bytes[..])
1308 }
1309 }
1310
1311 impl $crate::core_::default::Default for $name {
1312 fn default() -> Self {
1313 $name::zero()
1314 }
1315 }
1316
1317 impl $crate::core_::convert::From<u64> for $name {
1318 fn from(value: u64) -> $name {
1319 let mut ret = [0; $n_words];
1320 ret[0] = value;
1321 $name(ret)
1322 }
1323 }
1324
1325 $crate::impl_map_from!($name, u8, u64);
1326 $crate::impl_map_from!($name, u16, u64);
1327 $crate::impl_map_from!($name, u32, u64);
1328 $crate::impl_map_from!($name, usize, u64);
1329
1330 impl $crate::core_::convert::From<i64> for $name {
1331 fn from(value: i64) -> $name {
1332 match value >= 0 {
1333 true => From::from(value as u64),
1334 false => { panic!("Unsigned integer can't be created from negative value"); }
1335 }
1336 }
1337 }
1338
1339 $crate::impl_map_from!($name, i8, i64);
1340 $crate::impl_map_from!($name, i16, i64);
1341 $crate::impl_map_from!($name, i32, i64);
1342 $crate::impl_map_from!($name, isize, i64);
1343
1344 impl<'a> $crate::core_::convert::From<&'a [u8]> for $name {
1346 fn from(bytes: &[u8]) -> $name {
1347 Self::from_big_endian(bytes)
1348 }
1349 }
1350
1351 $crate::impl_try_from_for_primitive!($name, u8);
1352 $crate::impl_try_from_for_primitive!($name, u16);
1353 $crate::impl_try_from_for_primitive!($name, u32);
1354 $crate::impl_try_from_for_primitive!($name, usize);
1355 $crate::impl_try_from_for_primitive!($name, u64);
1356 $crate::impl_try_from_for_primitive!($name, i8);
1357 $crate::impl_try_from_for_primitive!($name, i16);
1358 $crate::impl_try_from_for_primitive!($name, i32);
1359 $crate::impl_try_from_for_primitive!($name, isize);
1360 $crate::impl_try_from_for_primitive!($name, i64);
1361
1362 impl<T> $crate::core_::ops::Add<T> for $name where T: Into<$name> {
1363 type Output = $name;
1364
1365 fn add(self, other: T) -> $name {
1366 let (result, overflow) = self.overflowing_add(other.into());
1367 $crate::panic_on_overflow!(overflow);
1368 result
1369 }
1370 }
1371
1372 impl<'a, T> $crate::core_::ops::Add<T> for &'a $name where T: Into<$name> {
1373 type Output = $name;
1374
1375 fn add(self, other: T) -> $name {
1376 *self + other
1377 }
1378 }
1379
1380 impl $crate::core_::ops::AddAssign<$name> for $name {
1381 fn add_assign(&mut self, other: $name) {
1382 let (result, overflow) = self.overflowing_add(other);
1383 $crate::panic_on_overflow!(overflow);
1384 *self = result
1385 }
1386 }
1387
1388 impl<T> $crate::core_::ops::Sub<T> for $name where T: Into<$name> {
1389 type Output = $name;
1390
1391 #[inline]
1392 fn sub(self, other: T) -> $name {
1393 let (result, overflow) = self.overflowing_sub(other.into());
1394 $crate::panic_on_overflow!(overflow);
1395 result
1396 }
1397 }
1398
1399 impl<'a, T> $crate::core_::ops::Sub<T> for &'a $name where T: Into<$name> {
1400 type Output = $name;
1401
1402 fn sub(self, other: T) -> $name {
1403 *self - other
1404 }
1405 }
1406
1407 impl $crate::core_::ops::SubAssign<$name> for $name {
1408 fn sub_assign(&mut self, other: $name) {
1409 let (result, overflow) = self.overflowing_sub(other);
1410 $crate::panic_on_overflow!(overflow);
1411 *self = result
1412 }
1413 }
1414
1415 $crate::impl_mul_from!($name, $name);
1417 $crate::impl_mul_for_primitive!($name, u8);
1418 $crate::impl_mul_for_primitive!($name, u16);
1419 $crate::impl_mul_for_primitive!($name, u32);
1420 $crate::impl_mul_for_primitive!($name, u64);
1421 $crate::impl_mul_for_primitive!($name, usize);
1422 $crate::impl_mul_for_primitive!($name, i8);
1423 $crate::impl_mul_for_primitive!($name, i16);
1424 $crate::impl_mul_for_primitive!($name, i32);
1425 $crate::impl_mul_for_primitive!($name, i64);
1426 $crate::impl_mul_for_primitive!($name, isize);
1427
1428 impl<T> $crate::core_::ops::Div<T> for $name where T: Into<$name> {
1429 type Output = $name;
1430
1431 fn div(self, other: T) -> $name {
1432 let other: Self = other.into();
1433 self.div_mod(other).0
1434 }
1435 }
1436
1437 impl<'a, T> $crate::core_::ops::Div<T> for &'a $name where T: Into<$name> {
1438 type Output = $name;
1439
1440 fn div(self, other: T) -> $name {
1441 *self / other
1442 }
1443 }
1444
1445 impl<T> $crate::core_::ops::DivAssign<T> for $name where T: Into<$name> {
1446 fn div_assign(&mut self, other: T) {
1447 *self = *self / other.into();
1448 }
1449 }
1450
1451 impl<T> $crate::core_::ops::Rem<T> for $name where T: Into<$name> + Copy {
1452 type Output = $name;
1453
1454 fn rem(self, other: T) -> $name {
1455 let mut sub_copy = self;
1456 sub_copy %= other;
1457 sub_copy
1458 }
1459 }
1460
1461 impl<'a, T> $crate::core_::ops::Rem<T> for &'a $name where T: Into<$name> + Copy {
1462 type Output = $name;
1463
1464 fn rem(self, other: T) -> $name {
1465 *self % other
1466 }
1467 }
1468
1469 impl<T> $crate::core_::ops::RemAssign<T> for $name where T: Into<$name> + Copy {
1470 fn rem_assign(&mut self, other: T) {
1471 let other: Self = other.into();
1472 let rem = self.div_mod(other).1;
1473 *self = rem;
1474 }
1475 }
1476
1477 impl $crate::core_::ops::BitAnd<$name> for $name {
1478 type Output = $name;
1479
1480 #[inline]
1481 fn bitand(self, other: $name) -> $name {
1482 let $name(ref arr1) = self;
1483 let $name(ref arr2) = other;
1484 let mut ret = [0u64; $n_words];
1485 for i in 0..$n_words {
1486 ret[i] = arr1[i] & arr2[i];
1487 }
1488 $name(ret)
1489 }
1490 }
1491
1492 impl $crate::core_::ops::BitXor<$name> for $name {
1493 type Output = $name;
1494
1495 #[inline]
1496 fn bitxor(self, other: $name) -> $name {
1497 let $name(ref arr1) = self;
1498 let $name(ref arr2) = other;
1499 let mut ret = [0u64; $n_words];
1500 for i in 0..$n_words {
1501 ret[i] = arr1[i] ^ arr2[i];
1502 }
1503 $name(ret)
1504 }
1505 }
1506
1507 impl $crate::core_::ops::BitOr<$name> for $name {
1508 type Output = $name;
1509
1510 #[inline]
1511 fn bitor(self, other: $name) -> $name {
1512 let $name(ref arr1) = self;
1513 let $name(ref arr2) = other;
1514 let mut ret = [0u64; $n_words];
1515 for i in 0..$n_words {
1516 ret[i] = arr1[i] | arr2[i];
1517 }
1518 $name(ret)
1519 }
1520 }
1521
1522 impl $crate::core_::ops::Not for $name {
1523 type Output = $name;
1524
1525 #[inline]
1526 fn not(self) -> $name {
1527 let $name(ref arr) = self;
1528 let mut ret = [0u64; $n_words];
1529 for i in 0..$n_words {
1530 ret[i] = !arr[i];
1531 }
1532 $name(ret)
1533 }
1534 }
1535
1536 impl<T> $crate::core_::ops::Shl<T> for $name where T: Into<$name> {
1537 type Output = $name;
1538
1539 fn shl(self, shift: T) -> $name {
1540 let shift = shift.into().as_usize();
1541 let $name(ref original) = self;
1542 let mut ret = [0u64; $n_words];
1543 let word_shift = shift / 64;
1544 let bit_shift = shift % 64;
1545
1546 for i in word_shift..$n_words {
1548 ret[i] = original[i - word_shift] << bit_shift;
1549 }
1550 if bit_shift > 0 {
1552 for i in word_shift+1..$n_words {
1553 ret[i] += original[i - 1 - word_shift] >> (64 - bit_shift);
1554 }
1555 }
1556 $name(ret)
1557 }
1558 }
1559
1560 impl<'a, T> $crate::core_::ops::Shl<T> for &'a $name where T: Into<$name> {
1561 type Output = $name;
1562 fn shl(self, shift: T) -> $name {
1563 *self << shift
1564 }
1565 }
1566
1567 impl<T> $crate::core_::ops::ShlAssign<T> for $name where T: Into<$name> {
1568 fn shl_assign(&mut self, shift: T) {
1569 *self = *self << shift;
1570 }
1571 }
1572
1573 impl<T> $crate::core_::ops::Shr<T> for $name where T: Into<$name> {
1574 type Output = $name;
1575
1576 fn shr(self, shift: T) -> $name {
1577 let shift = shift.into().as_usize();
1578 let $name(ref original) = self;
1579 let mut ret = [0u64; $n_words];
1580 let word_shift = shift / 64;
1581 let bit_shift = shift % 64;
1582
1583 for i in word_shift..$n_words {
1585 ret[i - word_shift] = original[i] >> bit_shift;
1586 }
1587
1588 if bit_shift > 0 {
1590 for i in word_shift+1..$n_words {
1591 ret[i - word_shift - 1] += original[i] << (64 - bit_shift);
1592 }
1593 }
1594
1595 $name(ret)
1596 }
1597 }
1598
1599 impl<'a, T> $crate::core_::ops::Shr<T> for &'a $name where T: Into<$name> {
1600 type Output = $name;
1601 fn shr(self, shift: T) -> $name {
1602 *self >> shift
1603 }
1604 }
1605
1606 impl<T> $crate::core_::ops::ShrAssign<T> for $name where T: Into<$name> {
1607 fn shr_assign(&mut self, shift: T) {
1608 *self = *self >> shift;
1609 }
1610 }
1611
1612 impl $crate::core_::cmp::Ord for $name {
1613 fn cmp(&self, other: &$name) -> $crate::core_::cmp::Ordering {
1614 self.as_ref().iter().rev().cmp(other.as_ref().iter().rev())
1615 }
1616 }
1617
1618 impl $crate::core_::cmp::PartialOrd for $name {
1619 fn partial_cmp(&self, other: &$name) -> Option<$crate::core_::cmp::Ordering> {
1620 Some(self.cmp(other))
1621 }
1622 }
1623
1624 impl $crate::core_::fmt::Debug for $name {
1625 fn fmt(&self, f: &mut $crate::core_::fmt::Formatter) -> $crate::core_::fmt::Result {
1626 $crate::core_::fmt::Display::fmt(self, f)
1627 }
1628 }
1629
1630 impl $crate::core_::fmt::Display for $name {
1631 fn fmt(&self, f: &mut $crate::core_::fmt::Formatter) -> $crate::core_::fmt::Result {
1632 if self.is_zero() {
1633 return $crate::core_::write!(f, "0");
1634 }
1635
1636 let mut buf = [0_u8; $n_words*20];
1637 let mut i = buf.len() - 1;
1638 let mut current = *self;
1639 let ten = $name::from(10);
1640
1641 loop {
1642 let digit = (current % ten).low_u64() as u8;
1643 buf[i] = digit + b'0';
1644 current = current / ten;
1645 if current.is_zero() {
1646 break;
1647 }
1648 i -= 1;
1649 }
1650
1651 let s = unsafe {
1653 $crate::core_::str::from_utf8_unchecked(&buf[i..])
1654 };
1655 f.write_str(s)
1656 }
1657 }
1658
1659 impl $crate::core_::fmt::LowerHex for $name {
1660 fn fmt(&self, f: &mut $crate::core_::fmt::Formatter) -> $crate::core_::fmt::Result {
1661 let &$name(ref data) = self;
1662 if f.alternate() {
1663 $crate::core_::write!(f, "0x")?;
1664 }
1665 if self.is_zero() {
1667 return $crate::core_::write!(f, "0");
1668 }
1669
1670 let mut latch = false;
1671 for ch in data.iter().rev() {
1672 for x in 0..16 {
1673 let nibble = (ch & (15u64 << ((15 - x) * 4) as u64)) >> (((15 - x) * 4) as u64);
1674 if !latch {
1675 latch = nibble != 0;
1676 }
1677
1678 if latch {
1679 $crate::core_::write!(f, "{:x}", nibble)?;
1680 }
1681 }
1682 }
1683 Ok(())
1684 }
1685 }
1686
1687 impl $crate::core_::str::FromStr for $name {
1688 type Err = $crate::FromHexError;
1689
1690 fn from_str(value: &str) -> $crate::core_::result::Result<$name, Self::Err> {
1691 let value = value.strip_prefix("0x").unwrap_or(value);
1692 const BYTES_LEN: usize = $n_words * 8;
1693 const MAX_ENCODED_LEN: usize = BYTES_LEN * 2;
1694
1695 let mut bytes = [0_u8; BYTES_LEN];
1696
1697 let encoded = value.as_bytes();
1698
1699 if encoded.len() > MAX_ENCODED_LEN {
1700 return Err($crate::hex::FromHexError::InvalidStringLength.into());
1701 }
1702
1703 if encoded.len() % 2 == 0 {
1704 let out = &mut bytes[BYTES_LEN - encoded.len() / 2..];
1705
1706 $crate::hex::decode_to_slice(encoded, out).map_err(Self::Err::from)?;
1707 } else {
1708 let mut s = [b'0'; MAX_ENCODED_LEN];
1710 s[MAX_ENCODED_LEN - encoded.len()..].copy_from_slice(encoded);
1711 let encoded = &s[MAX_ENCODED_LEN - encoded.len() - 1..];
1712
1713 let out = &mut bytes[BYTES_LEN - encoded.len() / 2..];
1714
1715 $crate::hex::decode_to_slice(encoded, out).map_err(Self::Err::from)?;
1716 }
1717
1718 let bytes_ref: &[u8] = &bytes;
1719 Ok(From::from(bytes_ref))
1720 }
1721 }
1722
1723 impl $crate::core_::convert::From<&'static str> for $name {
1724 fn from(s: &'static str) -> Self {
1725 s.parse().unwrap()
1726 }
1727 }
1728
1729 $crate::impl_quickcheck_arbitrary_for_uint!($name, ($n_words * 8));
1732 $crate::impl_arbitrary_for_uint!($name, ($n_words * 8));
1733 }
1734}
1735
1736#[cfg(feature = "quickcheck")]
1737#[macro_export]
1738#[doc(hidden)]
1739macro_rules! impl_quickcheck_arbitrary_for_uint {
1740 ($uint: ty, $n_bytes: tt) => {
1741 impl $crate::qc::Arbitrary for $uint {
1742 fn arbitrary<G: $crate::qc::Gen>(g: &mut G) -> Self {
1743 let mut res = [0u8; $n_bytes];
1744
1745 use $crate::rand07::Rng;
1746 let p: f64 = $crate::rand07::rngs::OsRng.gen();
1747 let range =
1750 if p < 0.1 {
1752 $n_bytes
1753 } else if p < 0.2 {
1755 $n_bytes / 2
1756 } else {
1758 $n_bytes / 5
1759 };
1760
1761 let size = g.gen_range(0, range);
1762 g.fill_bytes(&mut res[..size]);
1763
1764 res.as_ref().into()
1765 }
1766 }
1767 };
1768}
1769
1770#[cfg(not(feature = "quickcheck"))]
1771#[macro_export]
1772#[doc(hidden)]
1773macro_rules! impl_quickcheck_arbitrary_for_uint {
1774 ($uint: ty, $n_bytes: tt) => {};
1775}
1776
1777
1778#[cfg(feature = "arbitrary")]
1779#[macro_export]
1780#[doc(hidden)]
1781macro_rules! impl_arbitrary_for_uint {
1782 ($uint: ty, $n_bytes: tt) => {
1783 impl $crate::arbitrary::Arbitrary for $uint {
1784 fn arbitrary(u: &mut $crate::arbitrary::Unstructured<'_>) -> $crate::arbitrary::Result<Self> {
1785 let mut res = [0u8; $n_bytes];
1786 u.fill_buffer(&mut res)?;
1787 Ok(Self::from(res))
1788 }
1789 }
1790 };
1791}
1792
1793#[cfg(not(feature = "arbitrary"))]
1794#[macro_export]
1795#[doc(hidden)]
1796macro_rules! impl_arbitrary_for_uint {
1797 ($uint: ty, $n_bytes: tt) => {};
1798}