]> git.lizzy.rs Git - rust.git/blob - src/libcore/num/mod.rs
Rollup merge of #53413 - eddyb:featured-in-the-latest-edition, r=varkor
[rust.git] / src / libcore / num / mod.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Numeric traits and functions for the built-in numeric types.
12
13 #![stable(feature = "rust1", since = "1.0.0")]
14
15 use convert::TryFrom;
16 use fmt;
17 use intrinsics;
18 use mem;
19 use nonzero::NonZero;
20 use ops;
21 use str::FromStr;
22
23 macro_rules! impl_nonzero_fmt {
24     ( ( $( $Trait: ident ),+ ) for $Ty: ident ) => {
25         $(
26             #[stable(feature = "nonzero", since = "1.28.0")]
27             impl fmt::$Trait for $Ty {
28                 #[inline]
29                 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
30                     self.get().fmt(f)
31                 }
32             }
33         )+
34     }
35 }
36
37 macro_rules! nonzero_integers {
38     ( $( $Ty: ident($Int: ty); )+ ) => {
39         $(
40             /// An integer that is known not to equal zero.
41             ///
42             /// This enables some memory layout optimization.
43             /// For example, `Option<NonZeroU32>` is the same size as `u32`:
44             ///
45             /// ```rust
46             /// use std::mem::size_of;
47             /// assert_eq!(size_of::<Option<std::num::NonZeroU32>>(), size_of::<u32>());
48             /// ```
49             #[stable(feature = "nonzero", since = "1.28.0")]
50             #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
51             #[repr(transparent)]
52             pub struct $Ty(NonZero<$Int>);
53
54             impl $Ty {
55                 /// Create a non-zero without checking the value.
56                 ///
57                 /// # Safety
58                 ///
59                 /// The value must not be zero.
60                 #[stable(feature = "nonzero", since = "1.28.0")]
61                 #[inline]
62                 pub const unsafe fn new_unchecked(n: $Int) -> Self {
63                     $Ty(NonZero(n))
64                 }
65
66                 /// Create a non-zero if the given value is not zero.
67                 #[stable(feature = "nonzero", since = "1.28.0")]
68                 #[inline]
69                 pub fn new(n: $Int) -> Option<Self> {
70                     if n != 0 {
71                         Some($Ty(NonZero(n)))
72                     } else {
73                         None
74                     }
75                 }
76
77                 /// Returns the value as a primitive type.
78                 #[stable(feature = "nonzero", since = "1.28.0")]
79                 #[inline]
80                 pub fn get(self) -> $Int {
81                     self.0 .0
82                 }
83
84             }
85
86             impl_nonzero_fmt! {
87                 (Debug, Display, Binary, Octal, LowerHex, UpperHex) for $Ty
88             }
89         )+
90     }
91 }
92
93 nonzero_integers! {
94     NonZeroU8(u8);
95     NonZeroU16(u16);
96     NonZeroU32(u32);
97     NonZeroU64(u64);
98     NonZeroU128(u128);
99     NonZeroUsize(usize);
100 }
101
102 /// Provides intentionally-wrapped arithmetic on `T`.
103 ///
104 /// Operations like `+` on `u32` values is intended to never overflow,
105 /// and in some debug configurations overflow is detected and results
106 /// in a panic. While most arithmetic falls into this category, some
107 /// code explicitly expects and relies upon modular arithmetic (e.g.,
108 /// hashing).
109 ///
110 /// Wrapping arithmetic can be achieved either through methods like
111 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
112 /// all standard arithmetic operations on the underlying value are
113 /// intended to have wrapping semantics.
114 ///
115 /// # Examples
116 ///
117 /// ```
118 /// use std::num::Wrapping;
119 ///
120 /// let zero = Wrapping(0u32);
121 /// let one = Wrapping(1u32);
122 ///
123 /// assert_eq!(std::u32::MAX, (zero - one).0);
124 /// ```
125 #[stable(feature = "rust1", since = "1.0.0")]
126 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
127 #[repr(transparent)]
128 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")]
129                        pub T);
130
131 #[stable(feature = "rust1", since = "1.0.0")]
132 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
133     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
134         self.0.fmt(f)
135     }
136 }
137
138 #[stable(feature = "wrapping_display", since = "1.10.0")]
139 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
140     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
141         self.0.fmt(f)
142     }
143 }
144
145 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
146 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
147     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
148         self.0.fmt(f)
149     }
150 }
151
152 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
153 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
154     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
155         self.0.fmt(f)
156     }
157 }
158
159 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
160 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
161     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
162         self.0.fmt(f)
163     }
164 }
165
166 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
167 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
168     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
169         self.0.fmt(f)
170     }
171 }
172
173 // All these modules are technically private and only exposed for coretests:
174 pub mod flt2dec;
175 pub mod dec2flt;
176 pub mod bignum;
177 pub mod diy_float;
178
179 macro_rules! doc_comment {
180     ($x:expr, $($tt:tt)*) => {
181         #[doc = $x]
182         $($tt)*
183     };
184 }
185
186 mod wrapping;
187
188 // `Int` + `SignedInt` implemented for signed integers
189 macro_rules! int_impl {
190     ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr, $Min:expr, $Max:expr, $Feature:expr,
191      $EndFeature:expr, $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
192      $reversed:expr) => {
193         doc_comment! {
194             concat!("Returns the smallest value that can be represented by this integer type.
195
196 # Examples
197
198 Basic usage:
199
200 ```
201 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), ", stringify!($Min), ");",
202 $EndFeature, "
203 ```"),
204             #[stable(feature = "rust1", since = "1.0.0")]
205             #[inline]
206             pub const fn min_value() -> Self {
207                 !0 ^ ((!0 as $UnsignedT) >> 1) as Self
208             }
209         }
210
211         doc_comment! {
212             concat!("Returns the largest value that can be represented by this integer type.
213
214 # Examples
215
216 Basic usage:
217
218 ```
219 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ", stringify!($Max), ");",
220 $EndFeature, "
221 ```"),
222             #[stable(feature = "rust1", since = "1.0.0")]
223             #[inline]
224             pub const fn max_value() -> Self {
225                 !Self::min_value()
226             }
227         }
228
229         doc_comment! {
230             concat!("Converts a string slice in a given base to an integer.
231
232 The string is expected to be an optional `+` or `-` sign followed by digits.
233 Leading and trailing whitespace represent an error. Digits are a subset of these characters,
234 depending on `radix`:
235
236  * `0-9`
237  * `a-z`
238  * `A-Z`
239
240 # Panics
241
242 This function panics if `radix` is not in the range from 2 to 36.
243
244 # Examples
245
246 Basic usage:
247
248 ```
249 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
250 $EndFeature, "
251 ```"),
252             #[stable(feature = "rust1", since = "1.0.0")]
253             pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
254                 from_str_radix(src, radix)
255             }
256         }
257
258         doc_comment! {
259             concat!("Returns the number of ones in the binary representation of `self`.
260
261 # Examples
262
263 Basic usage:
264
265 ```
266 ", $Feature, "let n = 0b100_0000", stringify!($SelfT), ";
267
268 assert_eq!(n.count_ones(), 1);",
269 $EndFeature, "
270 ```
271 "),
272             #[stable(feature = "rust1", since = "1.0.0")]
273             #[rustc_const_unstable(feature = "const_int_ops")]
274             #[inline]
275             pub const fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
276         }
277
278         doc_comment! {
279             concat!("Returns the number of zeros in the binary representation of `self`.
280
281 # Examples
282
283 Basic usage:
284
285 ```
286 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 1);", $EndFeature, "
287 ```"),
288             #[stable(feature = "rust1", since = "1.0.0")]
289             #[rustc_const_unstable(feature = "const_int_ops")]
290             #[inline]
291             pub const fn count_zeros(self) -> u32 {
292                 (!self).count_ones()
293             }
294         }
295
296         doc_comment! {
297             concat!("Returns the number of leading zeros in the binary representation of `self`.
298
299 # Examples
300
301 Basic usage:
302
303 ```
304 ", $Feature, "let n = -1", stringify!($SelfT), ";
305
306 assert_eq!(n.leading_zeros(), 0);",
307 $EndFeature, "
308 ```"),
309             #[stable(feature = "rust1", since = "1.0.0")]
310             #[rustc_const_unstable(feature = "const_int_ops")]
311             #[inline]
312             pub const fn leading_zeros(self) -> u32 {
313                 (self as $UnsignedT).leading_zeros()
314             }
315         }
316
317         doc_comment! {
318             concat!("Returns the number of trailing zeros in the binary representation of `self`.
319
320 # Examples
321
322 Basic usage:
323
324 ```
325 ", $Feature, "let n = -4", stringify!($SelfT), ";
326
327 assert_eq!(n.trailing_zeros(), 2);",
328 $EndFeature, "
329 ```"),
330             #[stable(feature = "rust1", since = "1.0.0")]
331             #[rustc_const_unstable(feature = "const_int_ops")]
332             #[inline]
333             pub const fn trailing_zeros(self) -> u32 {
334                 (self as $UnsignedT).trailing_zeros()
335             }
336         }
337
338         doc_comment! {
339             concat!("Shifts the bits to the left by a specified amount, `n`,
340 wrapping the truncated bits to the end of the resulting integer.
341
342 Please note this isn't the same operation as `<<`!
343
344 # Examples
345
346 Basic usage:
347
348 ```
349 let n = ", $rot_op, stringify!($SelfT), ";
350 let m = ", $rot_result, ";
351
352 assert_eq!(n.rotate_left(", $rot, "), m);
353 ```"),
354             #[stable(feature = "rust1", since = "1.0.0")]
355             #[inline]
356             pub fn rotate_left(self, n: u32) -> Self {
357                 (self as $UnsignedT).rotate_left(n) as Self
358             }
359         }
360
361         doc_comment! {
362             concat!("Shifts the bits to the right by a specified amount, `n`,
363 wrapping the truncated bits to the beginning of the resulting
364 integer.
365
366 Please note this isn't the same operation as `>>`!
367
368 # Examples
369
370 Basic usage:
371
372 ```
373 let n = ", $rot_result, stringify!($SelfT), ";
374 let m = ", $rot_op, ";
375
376 assert_eq!(n.rotate_right(", $rot, "), m);
377 ```"),
378             #[stable(feature = "rust1", since = "1.0.0")]
379             #[inline]
380             pub fn rotate_right(self, n: u32) -> Self {
381                 (self as $UnsignedT).rotate_right(n) as Self
382             }
383         }
384         doc_comment! {
385             concat!("Reverses the byte order of the integer.
386
387 # Examples
388
389 Basic usage:
390
391 ```
392 let n = ", $swap_op, stringify!($SelfT), ";
393
394 let m = n.swap_bytes();
395
396 assert_eq!(m, ", $swapped, ");
397 ```"),
398             #[stable(feature = "rust1", since = "1.0.0")]
399             #[rustc_const_unstable(feature = "const_int_ops")]
400             #[inline]
401             pub const fn swap_bytes(self) -> Self {
402                 (self as $UnsignedT).swap_bytes() as Self
403             }
404         }
405
406         doc_comment! {
407             concat!("Reverses the bit pattern of the integer.
408
409 # Examples
410
411 Basic usage:
412
413 ```
414 #![feature(reverse_bits)]
415
416 let n = ", $swap_op, stringify!($SelfT), ";
417 let m = n.reverse_bits();
418
419 assert_eq!(m, ", $reversed, ");
420 ```"),
421             #[unstable(feature = "reverse_bits", issue = "48763")]
422             #[inline]
423             pub fn reverse_bits(self) -> Self {
424                 (self as $UnsignedT).reverse_bits() as Self
425             }
426         }
427
428         doc_comment! {
429             concat!("Converts an integer from big endian to the target's endianness.
430
431 On big endian this is a no-op. On little endian the bytes are swapped.
432
433 # Examples
434
435 Basic usage:
436
437 ```
438 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
439
440 if cfg!(target_endian = \"big\") {
441     assert_eq!(", stringify!($SelfT), "::from_be(n), n)
442 } else {
443     assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
444 }",
445 $EndFeature, "
446 ```"),
447             #[stable(feature = "rust1", since = "1.0.0")]
448             #[rustc_const_unstable(feature = "const_int_ops")]
449             #[inline]
450             pub const fn from_be(x: Self) -> Self {
451                 #[cfg(target_endian = "big")]
452                 {
453                     x
454                 }
455                 #[cfg(not(target_endian = "big"))]
456                 {
457                     x.swap_bytes()
458                 }
459             }
460         }
461
462         doc_comment! {
463             concat!("Converts an integer from little endian to the target's endianness.
464
465 On little endian this is a no-op. On big endian the bytes are swapped.
466
467 # Examples
468
469 Basic usage:
470
471 ```
472 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
473
474 if cfg!(target_endian = \"little\") {
475     assert_eq!(", stringify!($SelfT), "::from_le(n), n)
476 } else {
477     assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
478 }",
479 $EndFeature, "
480 ```"),
481             #[stable(feature = "rust1", since = "1.0.0")]
482             #[rustc_const_unstable(feature = "const_int_ops")]
483             #[inline]
484             pub const fn from_le(x: Self) -> Self {
485                 #[cfg(target_endian = "little")]
486                 {
487                     x
488                 }
489                 #[cfg(not(target_endian = "little"))]
490                 {
491                     x.swap_bytes()
492                 }
493             }
494         }
495
496         doc_comment! {
497             concat!("Converts `self` to big endian from the target's endianness.
498
499 On big endian this is a no-op. On little endian the bytes are swapped.
500
501 # Examples
502
503 Basic usage:
504
505 ```
506 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
507
508 if cfg!(target_endian = \"big\") {
509     assert_eq!(n.to_be(), n)
510 } else {
511     assert_eq!(n.to_be(), n.swap_bytes())
512 }",
513 $EndFeature, "
514 ```"),
515             #[stable(feature = "rust1", since = "1.0.0")]
516             #[rustc_const_unstable(feature = "const_int_ops")]
517             #[inline]
518             pub const fn to_be(self) -> Self { // or not to be?
519                 #[cfg(target_endian = "big")]
520                 {
521                     self
522                 }
523                 #[cfg(not(target_endian = "big"))]
524                 {
525                     self.swap_bytes()
526                 }
527             }
528         }
529
530         doc_comment! {
531             concat!("Converts `self` to little endian from the target's endianness.
532
533 On little endian this is a no-op. On big endian the bytes are swapped.
534
535 # Examples
536
537 Basic usage:
538
539 ```
540 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
541
542 if cfg!(target_endian = \"little\") {
543     assert_eq!(n.to_le(), n)
544 } else {
545     assert_eq!(n.to_le(), n.swap_bytes())
546 }",
547 $EndFeature, "
548 ```"),
549             #[stable(feature = "rust1", since = "1.0.0")]
550             #[rustc_const_unstable(feature = "const_int_ops")]
551             #[inline]
552             pub const fn to_le(self) -> Self {
553                 #[cfg(target_endian = "little")]
554                 {
555                     self
556                 }
557                 #[cfg(not(target_endian = "little"))]
558                 {
559                     self.swap_bytes()
560                 }
561             }
562         }
563
564         doc_comment! {
565             concat!("Checked integer addition. Computes `self + rhs`, returning `None`
566 if overflow occurred.
567
568 # Examples
569
570 Basic usage:
571
572 ```
573 ", $Feature, "assert_eq!((", stringify!($SelfT),
574 "::max_value() - 2).checked_add(1), Some(", stringify!($SelfT), "::max_value() - 1));
575 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);",
576 $EndFeature, "
577 ```"),
578             #[stable(feature = "rust1", since = "1.0.0")]
579             #[inline]
580             pub fn checked_add(self, rhs: Self) -> Option<Self> {
581                 let (a, b) = self.overflowing_add(rhs);
582                 if b {None} else {Some(a)}
583             }
584         }
585
586         doc_comment! {
587             concat!("Checked integer subtraction. Computes `self - rhs`, returning `None` if
588 overflow occurred.
589
590 # Examples
591
592 Basic usage:
593
594 ```
595 ", $Feature, "assert_eq!((", stringify!($SelfT),
596 "::min_value() + 2).checked_sub(1), Some(", stringify!($SelfT), "::min_value() + 1));
597 assert_eq!((", stringify!($SelfT), "::min_value() + 2).checked_sub(3), None);",
598 $EndFeature, "
599 ```"),
600             #[stable(feature = "rust1", since = "1.0.0")]
601             #[inline]
602             pub fn checked_sub(self, rhs: Self) -> Option<Self> {
603                 let (a, b) = self.overflowing_sub(rhs);
604                 if b {None} else {Some(a)}
605             }
606         }
607
608         doc_comment! {
609             concat!("Checked integer multiplication. Computes `self * rhs`, returning `None` if
610 overflow occurred.
611
612 # Examples
613
614 Basic usage:
615
616 ```
617 ", $Feature, "assert_eq!(", stringify!($SelfT),
618 "::max_value().checked_mul(1), Some(", stringify!($SelfT), "::max_value()));
619 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);",
620 $EndFeature, "
621 ```"),
622             #[stable(feature = "rust1", since = "1.0.0")]
623             #[inline]
624             pub fn checked_mul(self, rhs: Self) -> Option<Self> {
625                 let (a, b) = self.overflowing_mul(rhs);
626                 if b {None} else {Some(a)}
627             }
628         }
629
630         doc_comment! {
631             concat!("Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
632 or the division results in overflow.
633
634 # Examples
635
636 Basic usage:
637
638 ```
639 ", $Feature, "assert_eq!((", stringify!($SelfT),
640 "::min_value() + 1).checked_div(-1), Some(", stringify!($Max), "));
641 assert_eq!(", stringify!($SelfT), "::min_value().checked_div(-1), None);
642 assert_eq!((1", stringify!($SelfT), ").checked_div(0), None);",
643 $EndFeature, "
644 ```"),
645             #[stable(feature = "rust1", since = "1.0.0")]
646             #[inline]
647             pub fn checked_div(self, rhs: Self) -> Option<Self> {
648                 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
649                     None
650                 } else {
651                     Some(unsafe { intrinsics::unchecked_div(self, rhs) })
652                 }
653             }
654         }
655
656         doc_comment! {
657             concat!("Checked Euclidean division. Computes `self.div_euc(rhs)`,
658 returning `None` if `rhs == 0` or the division results in overflow.
659
660 # Examples
661
662 Basic usage:
663
664 ```
665 #![feature(euclidean_division)]
666 assert_eq!((", stringify!($SelfT),
667 "::min_value() + 1).checked_div_euc(-1), Some(", stringify!($Max), "));
668 assert_eq!(", stringify!($SelfT), "::min_value().checked_div_euc(-1), None);
669 assert_eq!((1", stringify!($SelfT), ").checked_div_euc(0), None);
670 ```"),
671             #[unstable(feature = "euclidean_division", issue = "49048")]
672             #[inline]
673             pub fn checked_div_euc(self, rhs: Self) -> Option<Self> {
674                 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
675                     None
676                 } else {
677                     Some(self.div_euc(rhs))
678                 }
679             }
680         }
681
682         doc_comment! {
683             concat!("Checked integer remainder. Computes `self % rhs`, returning `None` if
684 `rhs == 0` or the division results in overflow.
685
686 # Examples
687
688 Basic usage:
689
690 ```
691 ", $Feature, "use std::", stringify!($SelfT), ";
692
693 assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
694 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);
695 assert_eq!(", stringify!($SelfT), "::MIN.checked_rem(-1), None);",
696 $EndFeature, "
697 ```"),
698             #[stable(feature = "wrapping", since = "1.7.0")]
699             #[inline]
700             pub fn checked_rem(self, rhs: Self) -> Option<Self> {
701                 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
702                     None
703                 } else {
704                     Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
705                 }
706             }
707         }
708
709         doc_comment! {
710             concat!("Checked Euclidean modulo. Computes `self.mod_euc(rhs)`, returning `None` if
711 `rhs == 0` or the division results in overflow.
712
713 # Examples
714
715 Basic usage:
716
717 ```
718 #![feature(euclidean_division)]
719 use std::", stringify!($SelfT), ";
720
721 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1));
722 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None);
723 assert_eq!(", stringify!($SelfT), "::MIN.checked_mod_euc(-1), None);
724 ```"),
725             #[unstable(feature = "euclidean_division", issue = "49048")]
726             #[inline]
727             pub fn checked_mod_euc(self, rhs: Self) -> Option<Self> {
728                 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
729                     None
730                 } else {
731                     Some(self.mod_euc(rhs))
732                 }
733             }
734         }
735
736         doc_comment! {
737             concat!("Checked negation. Computes `-self`, returning `None` if `self == MIN`.
738
739 # Examples
740
741 Basic usage:
742
743 ```
744 ", $Feature, "use std::", stringify!($SelfT), ";
745
746 assert_eq!(5", stringify!($SelfT), ".checked_neg(), Some(-5));
747 assert_eq!(", stringify!($SelfT), "::MIN.checked_neg(), None);",
748 $EndFeature, "
749 ```"),
750             #[stable(feature = "wrapping", since = "1.7.0")]
751             #[inline]
752             pub fn checked_neg(self) -> Option<Self> {
753                 let (a, b) = self.overflowing_neg();
754                 if b {None} else {Some(a)}
755             }
756         }
757
758         doc_comment! {
759             concat!("Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
760 than or equal to the number of bits in `self`.
761
762 # Examples
763
764 Basic usage:
765
766 ```
767 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
768 assert_eq!(0x1", stringify!($SelfT), ".checked_shl(129), None);",
769 $EndFeature, "
770 ```"),
771             #[stable(feature = "wrapping", since = "1.7.0")]
772             #[inline]
773             pub fn checked_shl(self, rhs: u32) -> Option<Self> {
774                 let (a, b) = self.overflowing_shl(rhs);
775                 if b {None} else {Some(a)}
776             }
777         }
778
779         doc_comment! {
780             concat!("Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
781 larger than or equal to the number of bits in `self`.
782
783 # Examples
784
785 Basic usage:
786
787 ```
788 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
789 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(128), None);",
790 $EndFeature, "
791 ```"),
792             #[stable(feature = "wrapping", since = "1.7.0")]
793             #[inline]
794             pub fn checked_shr(self, rhs: u32) -> Option<Self> {
795                 let (a, b) = self.overflowing_shr(rhs);
796                 if b {None} else {Some(a)}
797             }
798         }
799
800         doc_comment! {
801             concat!("Checked absolute value. Computes `self.abs()`, returning `None` if
802 `self == MIN`.
803
804 # Examples
805
806 Basic usage:
807
808 ```
809 ", $Feature, "use std::", stringify!($SelfT), ";
810
811 assert_eq!((-5", stringify!($SelfT), ").checked_abs(), Some(5));
812 assert_eq!(", stringify!($SelfT), "::MIN.checked_abs(), None);",
813 $EndFeature, "
814 ```"),
815             #[stable(feature = "no_panic_abs", since = "1.13.0")]
816             #[inline]
817             pub fn checked_abs(self) -> Option<Self> {
818                 if self.is_negative() {
819                     self.checked_neg()
820                 } else {
821                     Some(self)
822                 }
823             }
824         }
825
826         doc_comment! {
827             concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
828 overflow occurred.
829
830 # Examples
831
832 Basic usage:
833
834 ```
835 #![feature(no_panic_pow)]
836 ", $Feature, "assert_eq!(8", stringify!($SelfT), ".checked_pow(2), Some(64));
837 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);",
838 $EndFeature, "
839 ```"),
840
841             #[unstable(feature = "no_panic_pow", issue = "48320")]
842             #[inline]
843             pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
844                 let mut base = self;
845                 let mut acc: Self = 1;
846
847                 while exp > 1 {
848                     if (exp & 1) == 1 {
849                         acc = acc.checked_mul(base)?;
850                     }
851                     exp /= 2;
852                     base = base.checked_mul(base)?;
853                 }
854
855                 // Deal with the final bit of the exponent separately, since
856                 // squaring the base afterwards is not necessary and may cause a
857                 // needless overflow.
858                 if exp == 1 {
859                     acc = acc.checked_mul(base)?;
860                 }
861
862                 Some(acc)
863             }
864         }
865
866         doc_comment! {
867             concat!("Saturating integer addition. Computes `self + rhs`, saturating at the numeric
868 bounds instead of overflowing.
869
870 # Examples
871
872 Basic usage:
873
874 ```
875 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
876 assert_eq!(", stringify!($SelfT), "::max_value().saturating_add(100), ", stringify!($SelfT),
877 "::max_value());",
878 $EndFeature, "
879 ```"),
880             #[stable(feature = "rust1", since = "1.0.0")]
881             #[inline]
882             pub fn saturating_add(self, rhs: Self) -> Self {
883                 match self.checked_add(rhs) {
884                     Some(x) => x,
885                     None if rhs >= 0 => Self::max_value(),
886                     None => Self::min_value(),
887                 }
888             }
889         }
890
891         doc_comment! {
892             concat!("Saturating integer subtraction. Computes `self - rhs`, saturating at the
893 numeric bounds instead of overflowing.
894
895 # Examples
896
897 Basic usage:
898
899 ```
900 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(127), -27);
901 assert_eq!(", stringify!($SelfT), "::min_value().saturating_sub(100), ", stringify!($SelfT),
902 "::min_value());",
903 $EndFeature, "
904 ```"),
905             #[stable(feature = "rust1", since = "1.0.0")]
906             #[inline]
907             pub fn saturating_sub(self, rhs: Self) -> Self {
908                 match self.checked_sub(rhs) {
909                     Some(x) => x,
910                     None if rhs >= 0 => Self::min_value(),
911                     None => Self::max_value(),
912                 }
913             }
914         }
915
916         doc_comment! {
917             concat!("Saturating integer multiplication. Computes `self * rhs`, saturating at the
918 numeric bounds instead of overflowing.
919
920 # Examples
921
922 Basic usage:
923
924 ```
925 ", $Feature, "use std::", stringify!($SelfT), ";
926
927 assert_eq!(10", stringify!($SelfT), ".saturating_mul(12), 120);
928 assert_eq!(", stringify!($SelfT), "::MAX.saturating_mul(10), ", stringify!($SelfT), "::MAX);
929 assert_eq!(", stringify!($SelfT), "::MIN.saturating_mul(10), ", stringify!($SelfT), "::MIN);",
930 $EndFeature, "
931 ```"),
932             #[stable(feature = "wrapping", since = "1.7.0")]
933             #[inline]
934             pub fn saturating_mul(self, rhs: Self) -> Self {
935                 self.checked_mul(rhs).unwrap_or_else(|| {
936                     if (self < 0 && rhs < 0) || (self > 0 && rhs > 0) {
937                         Self::max_value()
938                     } else {
939                         Self::min_value()
940                     }
941                 })
942             }
943         }
944
945         doc_comment! {
946             concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
947 saturating at the numeric bounds instead of overflowing.
948
949 # Examples
950
951 Basic usage:
952
953 ```
954 #![feature(no_panic_pow)]
955 ", $Feature, "use std::", stringify!($SelfT), ";
956
957 assert_eq!((-4", stringify!($SelfT), ").saturating_pow(3), -64);
958 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(2), ", stringify!($SelfT), "::MAX);
959 assert_eq!(", stringify!($SelfT), "::MIN.saturating_pow(3), ", stringify!($SelfT), "::MIN);",
960 $EndFeature, "
961 ```"),
962             #[unstable(feature = "no_panic_pow", issue = "48320")]
963             #[inline]
964             pub fn saturating_pow(self, exp: u32) -> Self {
965                 match self.checked_pow(exp) {
966                     Some(x) => x,
967                     None if self < 0 && exp % 2 == 1 => Self::min_value(),
968                     None => Self::max_value(),
969                 }
970             }
971         }
972
973         doc_comment! {
974             concat!("Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
975 boundary of the type.
976
977 # Examples
978
979 Basic usage:
980
981 ```
982 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_add(27), 127);
983 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_add(2), ", stringify!($SelfT),
984 "::min_value() + 1);",
985 $EndFeature, "
986 ```"),
987             #[stable(feature = "rust1", since = "1.0.0")]
988             #[inline]
989             pub fn wrapping_add(self, rhs: Self) -> Self {
990                 unsafe {
991                     intrinsics::overflowing_add(self, rhs)
992                 }
993             }
994         }
995
996         doc_comment! {
997             concat!("Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
998 boundary of the type.
999
1000 # Examples
1001
1002 Basic usage:
1003
1004 ```
1005 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".wrapping_sub(127), -127);
1006 assert_eq!((-2", stringify!($SelfT), ").wrapping_sub(", stringify!($SelfT), "::max_value()), ",
1007 stringify!($SelfT), "::max_value());",
1008 $EndFeature, "
1009 ```"),
1010             #[stable(feature = "rust1", since = "1.0.0")]
1011             #[inline]
1012             pub fn wrapping_sub(self, rhs: Self) -> Self {
1013                 unsafe {
1014                     intrinsics::overflowing_sub(self, rhs)
1015                 }
1016             }
1017         }
1018
1019         doc_comment! {
1020             concat!("Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
1021 the boundary of the type.
1022
1023 # Examples
1024
1025 Basic usage:
1026
1027 ```
1028 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".wrapping_mul(12), 120);
1029 assert_eq!(11i8.wrapping_mul(12), -124);",
1030 $EndFeature, "
1031 ```"),
1032             #[stable(feature = "rust1", since = "1.0.0")]
1033             #[inline]
1034             pub fn wrapping_mul(self, rhs: Self) -> Self {
1035                 unsafe {
1036                     intrinsics::overflowing_mul(self, rhs)
1037                 }
1038             }
1039         }
1040
1041         doc_comment! {
1042             concat!("Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
1043 boundary of the type.
1044
1045 The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
1046 `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
1047 that is too large to represent in the type. In such a case, this function returns `MIN` itself.
1048
1049 # Panics
1050
1051 This function will panic if `rhs` is 0.
1052
1053 # Examples
1054
1055 Basic usage:
1056
1057 ```
1058 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);
1059 assert_eq!((-128i8).wrapping_div(-1), -128);",
1060 $EndFeature, "
1061 ```"),
1062             #[stable(feature = "num_wrapping", since = "1.2.0")]
1063             #[inline]
1064             pub fn wrapping_div(self, rhs: Self) -> Self {
1065                 self.overflowing_div(rhs).0
1066             }
1067         }
1068
1069         doc_comment! {
1070             concat!("Wrapping Euclidean division. Computes `self.div_euc(rhs)`,
1071 wrapping around at the boundary of the type.
1072
1073 Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value
1074 for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
1075 type. In this case, this method returns `MIN` itself.
1076
1077 # Panics
1078
1079 This function will panic if `rhs` is 0.
1080
1081 # Examples
1082
1083 Basic usage:
1084
1085 ```
1086 #![feature(euclidean_division)]
1087 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10);
1088 assert_eq!((-128i8).wrapping_div_euc(-1), -128);
1089 ```"),
1090             #[unstable(feature = "euclidean_division", issue = "49048")]
1091             #[inline]
1092             pub fn wrapping_div_euc(self, rhs: Self) -> Self {
1093                 self.overflowing_div_euc(rhs).0
1094             }
1095         }
1096
1097         doc_comment! {
1098             concat!("Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
1099 boundary of the type.
1100
1101 Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
1102 invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case,
1103 this function returns `0`.
1104
1105 # Panics
1106
1107 This function will panic if `rhs` is 0.
1108
1109 # Examples
1110
1111 Basic usage:
1112
1113 ```
1114 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);
1115 assert_eq!((-128i8).wrapping_rem(-1), 0);",
1116 $EndFeature, "
1117 ```"),
1118             #[stable(feature = "num_wrapping", since = "1.2.0")]
1119             #[inline]
1120             pub fn wrapping_rem(self, rhs: Self) -> Self {
1121                 self.overflowing_rem(rhs).0
1122             }
1123         }
1124
1125         doc_comment! {
1126             concat!("Wrapping Euclidean modulo. Computes `self.mod_euc(rhs)`, wrapping around at the
1127 boundary of the type.
1128
1129 Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value
1130 for the type). In this case, this method returns 0.
1131
1132 # Panics
1133
1134 This function will panic if `rhs` is 0.
1135
1136 # Examples
1137
1138 Basic usage:
1139
1140 ```
1141 #![feature(euclidean_division)]
1142 assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0);
1143 assert_eq!((-128i8).wrapping_mod_euc(-1), 0);
1144 ```"),
1145             #[unstable(feature = "euclidean_division", issue = "49048")]
1146             #[inline]
1147             pub fn wrapping_mod_euc(self, rhs: Self) -> Self {
1148                 self.overflowing_mod_euc(rhs).0
1149             }
1150         }
1151
1152         doc_comment! {
1153             concat!("Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
1154 of the type.
1155
1156 The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN`
1157 is the negative minimal value for the type); this is a positive value that is too large to represent
1158 in the type. In such a case, this function returns `MIN` itself.
1159
1160 # Examples
1161
1162 Basic usage:
1163
1164 ```
1165 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_neg(), -100);
1166 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_neg(), ", stringify!($SelfT),
1167 "::min_value());",
1168 $EndFeature, "
1169 ```"),
1170             #[stable(feature = "num_wrapping", since = "1.2.0")]
1171             #[inline]
1172             pub fn wrapping_neg(self) -> Self {
1173                 self.overflowing_neg().0
1174             }
1175         }
1176
1177         doc_comment! {
1178             concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
1179 any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1180
1181 Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
1182 the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
1183 The primitive integer types all implement a `rotate_left` function, which may be what you want
1184 instead.
1185
1186 # Examples
1187
1188 Basic usage:
1189
1190 ```
1191 ", $Feature, "assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(7), -128);
1192 assert_eq!((-1", stringify!($SelfT), ").wrapping_shl(128), -1);",
1193 $EndFeature, "
1194 ```"),
1195             #[stable(feature = "num_wrapping", since = "1.2.0")]
1196             #[inline]
1197             pub fn wrapping_shl(self, rhs: u32) -> Self {
1198                 unsafe {
1199                     intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1200                 }
1201             }
1202         }
1203
1204         doc_comment! {
1205             concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
1206 removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
1207
1208 Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
1209 to the range of the type, rather than the bits shifted out of the LHS being returned to the other
1210 end. The primitive integer types all implement a `rotate_right` function, which may be what you want
1211 instead.
1212
1213 # Examples
1214
1215 Basic usage:
1216
1217 ```
1218 ", $Feature, "assert_eq!((-128", stringify!($SelfT), ").wrapping_shr(7), -1);
1219 assert_eq!((-128i16).wrapping_shr(64), -128);",
1220 $EndFeature, "
1221 ```"),
1222             #[stable(feature = "num_wrapping", since = "1.2.0")]
1223             #[inline]
1224             pub fn wrapping_shr(self, rhs: u32) -> Self {
1225                 unsafe {
1226                     intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1227                 }
1228             }
1229         }
1230
1231         doc_comment! {
1232             concat!("Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
1233 the boundary of the type.
1234
1235 The only case where such wrapping can occur is when one takes the absolute value of the negative
1236 minimal value for the type this is a positive value that is too large to represent in the type. In
1237 such a case, this function returns `MIN` itself.
1238
1239 # Examples
1240
1241 Basic usage:
1242
1243 ```
1244 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_abs(), 100);
1245 assert_eq!((-100", stringify!($SelfT), ").wrapping_abs(), 100);
1246 assert_eq!(", stringify!($SelfT), "::min_value().wrapping_abs(), ", stringify!($SelfT),
1247 "::min_value());
1248 assert_eq!((-128i8).wrapping_abs() as u8, 128);",
1249 $EndFeature, "
1250 ```"),
1251             #[stable(feature = "no_panic_abs", since = "1.13.0")]
1252             #[inline]
1253             pub fn wrapping_abs(self) -> Self {
1254                 if self.is_negative() {
1255                     self.wrapping_neg()
1256                 } else {
1257                     self
1258                 }
1259             }
1260         }
1261
1262         doc_comment! {
1263             concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
1264 wrapping around at the boundary of the type.
1265
1266 # Examples
1267
1268 Basic usage:
1269
1270 ```
1271 #![feature(no_panic_pow)]
1272 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(4), 81);
1273 assert_eq!(3i8.wrapping_pow(5), -13);
1274 assert_eq!(3i8.wrapping_pow(6), -39);",
1275 $EndFeature, "
1276 ```"),
1277             #[unstable(feature = "no_panic_pow", issue = "48320")]
1278             #[inline]
1279             pub fn wrapping_pow(self, mut exp: u32) -> Self {
1280                 let mut base = self;
1281                 let mut acc: Self = 1;
1282
1283                 while exp > 1 {
1284                     if (exp & 1) == 1 {
1285                         acc = acc.wrapping_mul(base);
1286                     }
1287                     exp /= 2;
1288                     base = base.wrapping_mul(base);
1289                 }
1290
1291                 // Deal with the final bit of the exponent separately, since
1292                 // squaring the base afterwards is not necessary and may cause a
1293                 // needless overflow.
1294                 if exp == 1 {
1295                     acc = acc.wrapping_mul(base);
1296                 }
1297
1298                 acc
1299             }
1300         }
1301
1302         doc_comment! {
1303             concat!("Calculates `self` + `rhs`
1304
1305 Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
1306 occur. If an overflow would have occurred then the wrapped value is returned.
1307
1308 # Examples
1309
1310 Basic usage:
1311
1312 ```
1313 ", $Feature, "use std::", stringify!($SelfT), ";
1314
1315 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
1316 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (", stringify!($SelfT),
1317 "::MIN, true));", $EndFeature, "
1318 ```"),
1319             #[inline]
1320             #[stable(feature = "wrapping", since = "1.7.0")]
1321             pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1322                 let (a, b) = unsafe {
1323                     intrinsics::add_with_overflow(self as $ActualT,
1324                                                   rhs as $ActualT)
1325                 };
1326                 (a as Self, b)
1327             }
1328         }
1329
1330         doc_comment! {
1331             concat!("Calculates `self` - `rhs`
1332
1333 Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
1334 would occur. If an overflow would have occurred then the wrapped value is returned.
1335
1336 # Examples
1337
1338 Basic usage:
1339
1340 ```
1341 ", $Feature, "use std::", stringify!($SelfT), ";
1342
1343 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
1344 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_sub(1), (", stringify!($SelfT),
1345 "::MAX, true));", $EndFeature, "
1346 ```"),
1347             #[inline]
1348             #[stable(feature = "wrapping", since = "1.7.0")]
1349             pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1350                 let (a, b) = unsafe {
1351                     intrinsics::sub_with_overflow(self as $ActualT,
1352                                                   rhs as $ActualT)
1353                 };
1354                 (a as Self, b)
1355             }
1356         }
1357
1358         doc_comment! {
1359             concat!("Calculates the multiplication of `self` and `rhs`.
1360
1361 Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
1362 would occur. If an overflow would have occurred then the wrapped value is returned.
1363
1364 # Examples
1365
1366 Basic usage:
1367
1368 ```
1369 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_mul(2), (10, false));
1370 assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));",
1371 $EndFeature, "
1372 ```"),
1373             #[inline]
1374             #[stable(feature = "wrapping", since = "1.7.0")]
1375             pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
1376                 let (a, b) = unsafe {
1377                     intrinsics::mul_with_overflow(self as $ActualT,
1378                                                   rhs as $ActualT)
1379                 };
1380                 (a as Self, b)
1381             }
1382         }
1383
1384         doc_comment! {
1385             concat!("Calculates the divisor when `self` is divided by `rhs`.
1386
1387 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1388 occur. If an overflow would occur then self is returned.
1389
1390 # Panics
1391
1392 This function will panic if `rhs` is 0.
1393
1394 # Examples
1395
1396 Basic usage:
1397
1398 ```
1399 ", $Feature, "use std::", stringify!($SelfT), ";
1400
1401 assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));
1402 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div(-1), (", stringify!($SelfT),
1403 "::MIN, true));",
1404 $EndFeature, "
1405 ```"),
1406             #[inline]
1407             #[stable(feature = "wrapping", since = "1.7.0")]
1408             pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1409                 if self == Self::min_value() && rhs == -1 {
1410                     (self, true)
1411                 } else {
1412                     (self / rhs, false)
1413                 }
1414             }
1415         }
1416
1417         doc_comment! {
1418             concat!("Calculates the quotient of Euclidean division `self.div_euc(rhs)`.
1419
1420 Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
1421 occur. If an overflow would occur then `self` is returned.
1422
1423 # Panics
1424
1425 This function will panic if `rhs` is 0.
1426
1427 # Examples
1428
1429 Basic usage:
1430
1431 ```
1432 #![feature(euclidean_division)]
1433 use std::", stringify!($SelfT), ";
1434
1435 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false));
1436 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_div_euc(-1), (", stringify!($SelfT),
1437 "::MIN, true));
1438 ```"),
1439             #[inline]
1440             #[unstable(feature = "euclidean_division", issue = "49048")]
1441             pub fn overflowing_div_euc(self, rhs: Self) -> (Self, bool) {
1442                 if self == Self::min_value() && rhs == -1 {
1443                     (self, true)
1444                 } else {
1445                     (self.div_euc(rhs), false)
1446                 }
1447             }
1448         }
1449
1450         doc_comment! {
1451             concat!("Calculates the remainder when `self` is divided by `rhs`.
1452
1453 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1454 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1455
1456 # Panics
1457
1458 This function will panic if `rhs` is 0.
1459
1460 # Examples
1461
1462 Basic usage:
1463
1464 ```
1465 ", $Feature, "use std::", stringify!($SelfT), ";
1466
1467 assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));
1468 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));",
1469 $EndFeature, "
1470 ```"),
1471             #[inline]
1472             #[stable(feature = "wrapping", since = "1.7.0")]
1473             pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1474                 if self == Self::min_value() && rhs == -1 {
1475                     (0, true)
1476                 } else {
1477                     (self % rhs, false)
1478                 }
1479             }
1480         }
1481
1482
1483         doc_comment! {
1484             concat!("Calculates the remainder `self.mod_euc(rhs)` by Euclidean division.
1485
1486 Returns a tuple of the remainder after dividing along with a boolean indicating whether an
1487 arithmetic overflow would occur. If an overflow would occur then 0 is returned.
1488
1489 # Panics
1490
1491 This function will panic if `rhs` is 0.
1492
1493 # Examples
1494
1495 Basic usage:
1496
1497 ```
1498 #![feature(euclidean_division)]
1499 use std::", stringify!($SelfT), ";
1500
1501 assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false));
1502 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_mod_euc(-1), (0, true));
1503 ```"),
1504             #[unstable(feature = "euclidean_division", issue = "49048")]
1505             #[inline]
1506             pub fn overflowing_mod_euc(self, rhs: Self) -> (Self, bool) {
1507                 if self == Self::min_value() && rhs == -1 {
1508                     (0, true)
1509                 } else {
1510                     (self.mod_euc(rhs), false)
1511                 }
1512             }
1513         }
1514
1515
1516         doc_comment! {
1517             concat!("Negates self, overflowing if this is equal to the minimum value.
1518
1519 Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
1520 happened. If `self` is the minimum value (e.g. `i32::MIN` for values of type `i32`), then the
1521 minimum value will be returned again and `true` will be returned for an overflow happening.
1522
1523 # Examples
1524
1525 Basic usage:
1526
1527 ```
1528 ", $Feature, "use std::", stringify!($SelfT), ";
1529
1530 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2, false));
1531 assert_eq!(", stringify!($SelfT), "::MIN.overflowing_neg(), (", stringify!($SelfT),
1532 "::MIN, true));", $EndFeature, "
1533 ```"),
1534             #[inline]
1535             #[stable(feature = "wrapping", since = "1.7.0")]
1536             pub fn overflowing_neg(self) -> (Self, bool) {
1537                 if self == Self::min_value() {
1538                     (Self::min_value(), true)
1539                 } else {
1540                     (-self, false)
1541                 }
1542             }
1543         }
1544
1545         doc_comment! {
1546             concat!("Shifts self left by `rhs` bits.
1547
1548 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1549 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1550 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1551
1552 # Examples
1553
1554 Basic usage:
1555
1556 ```
1557 ", $Feature, "assert_eq!(0x1", stringify!($SelfT),".overflowing_shl(4), (0x10, false));
1558 assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));",
1559 $EndFeature, "
1560 ```"),
1561             #[inline]
1562             #[stable(feature = "wrapping", since = "1.7.0")]
1563             pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1564                 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1565             }
1566         }
1567
1568         doc_comment! {
1569             concat!("Shifts self right by `rhs` bits.
1570
1571 Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
1572 value was larger than or equal to the number of bits. If the shift value is too large, then value is
1573 masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
1574
1575 # Examples
1576
1577 Basic usage:
1578
1579 ```
1580 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
1581 assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));",
1582 $EndFeature, "
1583 ```"),
1584             #[inline]
1585             #[stable(feature = "wrapping", since = "1.7.0")]
1586             pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1587                 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1588             }
1589         }
1590
1591         doc_comment! {
1592             concat!("Computes the absolute value of `self`.
1593
1594 Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
1595 happened. If self is the minimum value (e.g. ", stringify!($SelfT), "::MIN for values of type
1596  ", stringify!($SelfT), "), then the minimum value will be returned again and true will be returned
1597 for an overflow happening.
1598
1599 # Examples
1600
1601 Basic usage:
1602
1603 ```
1604 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".overflowing_abs(), (10, false));
1605 assert_eq!((-10", stringify!($SelfT), ").overflowing_abs(), (10, false));
1606 assert_eq!((", stringify!($SelfT), "::min_value()).overflowing_abs(), (", stringify!($SelfT),
1607 "::min_value(), true));",
1608 $EndFeature, "
1609 ```"),
1610             #[stable(feature = "no_panic_abs", since = "1.13.0")]
1611             #[inline]
1612             pub fn overflowing_abs(self) -> (Self, bool) {
1613                 if self.is_negative() {
1614                     self.overflowing_neg()
1615                 } else {
1616                     (self, false)
1617                 }
1618             }
1619         }
1620
1621         doc_comment! {
1622             concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1623
1624 Returns a tuple of the exponentiation along with a bool indicating
1625 whether an overflow happened.
1626
1627 # Examples
1628
1629 Basic usage:
1630
1631 ```
1632 #![feature(no_panic_pow)]
1633 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(4), (81, false));
1634 assert_eq!(3i8.overflowing_pow(5), (-13, true));",
1635 $EndFeature, "
1636 ```"),
1637             #[unstable(feature = "no_panic_pow", issue = "48320")]
1638             #[inline]
1639             pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
1640                 let mut base = self;
1641                 let mut acc: Self = 1;
1642                 let mut overflown = false;
1643                 // Scratch space for storing results of overflowing_mul.
1644                 let mut r;
1645
1646                 while exp > 1 {
1647                     if (exp & 1) == 1 {
1648                         r = acc.overflowing_mul(base);
1649                         acc = r.0;
1650                         overflown |= r.1;
1651                     }
1652                     exp /= 2;
1653                     r = base.overflowing_mul(base);
1654                     base = r.0;
1655                     overflown |= r.1;
1656                 }
1657
1658                 // Deal with the final bit of the exponent separately, since
1659                 // squaring the base afterwards is not necessary and may cause a
1660                 // needless overflow.
1661                 if exp == 1 {
1662                     r = acc.overflowing_mul(base);
1663                     acc = r.0;
1664                     overflown |= r.1;
1665                 }
1666
1667                 (acc, overflown)
1668             }
1669         }
1670
1671         doc_comment! {
1672             concat!("Raises self to the power of `exp`, using exponentiation by squaring.
1673
1674 # Examples
1675
1676 Basic usage:
1677
1678 ```
1679 ", $Feature, "let x: ", stringify!($SelfT), " = 2; // or any other integer type
1680
1681 assert_eq!(x.pow(5), 32);",
1682 $EndFeature, "
1683 ```"),
1684             #[stable(feature = "rust1", since = "1.0.0")]
1685             #[inline]
1686             #[rustc_inherit_overflow_checks]
1687             pub fn pow(self, mut exp: u32) -> Self {
1688                 let mut base = self;
1689                 let mut acc = 1;
1690
1691                 while exp > 1 {
1692                     if (exp & 1) == 1 {
1693                         acc = acc * base;
1694                     }
1695                     exp /= 2;
1696                     base = base * base;
1697                 }
1698
1699                 // Deal with the final bit of the exponent separately, since
1700                 // squaring the base afterwards is not necessary and may cause a
1701                 // needless overflow.
1702                 if exp == 1 {
1703                     acc = acc * base;
1704                 }
1705
1706                 acc
1707             }
1708         }
1709
1710         doc_comment! {
1711             concat!("Calculates the quotient of Euclidean division of `self` by `rhs`.
1712
1713 This computes the integer `n` such that `self = n * rhs + self.mod_euc(rhs)`.
1714 In other words, the result is `self / rhs` rounded to the integer `n`
1715 such that `self >= n * rhs`.
1716
1717 # Panics
1718
1719 This function will panic if `rhs` is 0.
1720
1721 # Examples
1722
1723 Basic usage:
1724
1725 ```
1726 #![feature(euclidean_division)]
1727 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1728 let b = 4;
1729
1730 assert_eq!(a.div_euc(b), 1); // 7 >= 4 * 1
1731 assert_eq!(a.div_euc(-b), -1); // 7 >= -4 * -1
1732 assert_eq!((-a).div_euc(b), -2); // -7 >= 4 * -2
1733 assert_eq!((-a).div_euc(-b), 2); // -7 >= -4 * 2
1734 ```"),
1735             #[unstable(feature = "euclidean_division", issue = "49048")]
1736             #[inline]
1737             #[rustc_inherit_overflow_checks]
1738             pub fn div_euc(self, rhs: Self) -> Self {
1739                 let q = self / rhs;
1740                 if self % rhs < 0 {
1741                     return if rhs > 0 { q - 1 } else { q + 1 }
1742                 }
1743                 q
1744             }
1745         }
1746
1747
1748         doc_comment! {
1749             concat!("Calculates the remainder `self mod rhs` by Euclidean division.
1750
1751 In particular, the result `n` satisfies `0 <= n < rhs.abs()`.
1752
1753 # Panics
1754
1755 This function will panic if `rhs` is 0.
1756
1757 # Examples
1758
1759 Basic usage:
1760
1761 ```
1762 #![feature(euclidean_division)]
1763 let a: ", stringify!($SelfT), " = 7; // or any other integer type
1764 let b = 4;
1765
1766 assert_eq!(a.mod_euc(b), 3);
1767 assert_eq!((-a).mod_euc(b), 1);
1768 assert_eq!(a.mod_euc(-b), 3);
1769 assert_eq!((-a).mod_euc(-b), 1);
1770 ```"),
1771             #[unstable(feature = "euclidean_division", issue = "49048")]
1772             #[inline]
1773             #[rustc_inherit_overflow_checks]
1774             pub fn mod_euc(self, rhs: Self) -> Self {
1775                 let r = self % rhs;
1776                 if r < 0 {
1777                     if rhs < 0 {
1778                         r - rhs
1779                     } else {
1780                         r + rhs
1781                     }
1782                 } else {
1783                     r
1784                 }
1785             }
1786         }
1787
1788         doc_comment! {
1789             concat!("Computes the absolute value of `self`.
1790
1791 # Overflow behavior
1792
1793 The absolute value of `", stringify!($SelfT), "::min_value()` cannot be represented as an
1794 `", stringify!($SelfT), "`, and attempting to calculate it will cause an overflow. This means that
1795 code in debug mode will trigger a panic on this case and optimized code will return `",
1796 stringify!($SelfT), "::min_value()` without a panic.
1797
1798 # Examples
1799
1800 Basic usage:
1801
1802 ```
1803 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".abs(), 10);
1804 assert_eq!((-10", stringify!($SelfT), ").abs(), 10);",
1805 $EndFeature, "
1806 ```"),
1807             #[stable(feature = "rust1", since = "1.0.0")]
1808             #[inline]
1809             #[rustc_inherit_overflow_checks]
1810             pub fn abs(self) -> Self {
1811                 if self.is_negative() {
1812                     // Note that the #[inline] above means that the overflow
1813                     // semantics of this negation depend on the crate we're being
1814                     // inlined into.
1815                     -self
1816                 } else {
1817                     self
1818                 }
1819             }
1820         }
1821
1822         doc_comment! {
1823             concat!("Returns a number representing sign of `self`.
1824
1825  - `0` if the number is zero
1826  - `1` if the number is positive
1827  - `-1` if the number is negative
1828
1829 # Examples
1830
1831 Basic usage:
1832
1833 ```
1834 ", $Feature, "assert_eq!(10", stringify!($SelfT), ".signum(), 1);
1835 assert_eq!(0", stringify!($SelfT), ".signum(), 0);
1836 assert_eq!((-10", stringify!($SelfT), ").signum(), -1);",
1837 $EndFeature, "
1838 ```"),
1839             #[stable(feature = "rust1", since = "1.0.0")]
1840             #[inline]
1841             pub fn signum(self) -> Self {
1842                 match self {
1843                     n if n > 0 =>  1,
1844                     0          =>  0,
1845                     _          => -1,
1846                 }
1847             }
1848         }
1849
1850         doc_comment! {
1851             concat!("Returns `true` if `self` is positive and `false` if the number is zero or
1852 negative.
1853
1854 # Examples
1855
1856 Basic usage:
1857
1858 ```
1859 ", $Feature, "assert!(10", stringify!($SelfT), ".is_positive());
1860 assert!(!(-10", stringify!($SelfT), ").is_positive());",
1861 $EndFeature, "
1862 ```"),
1863             #[stable(feature = "rust1", since = "1.0.0")]
1864             #[inline]
1865             pub fn is_positive(self) -> bool { self > 0 }
1866         }
1867
1868         doc_comment! {
1869             concat!("Returns `true` if `self` is negative and `false` if the number is zero or
1870 positive.
1871
1872 # Examples
1873
1874 Basic usage:
1875
1876 ```
1877 ", $Feature, "assert!((-10", stringify!($SelfT), ").is_negative());
1878 assert!(!10", stringify!($SelfT), ".is_negative());",
1879 $EndFeature, "
1880 ```"),
1881             #[stable(feature = "rust1", since = "1.0.0")]
1882             #[inline]
1883             pub fn is_negative(self) -> bool { self < 0 }
1884         }
1885
1886         /// Return the memory representation of this integer as a byte array in
1887         /// big-endian (network) byte order.
1888         ///
1889         /// # Examples
1890         ///
1891         /// ```
1892         /// #![feature(int_to_from_bytes)]
1893         ///
1894         /// let bytes = 0x12_34_56_78_i32.to_be_bytes();
1895         /// assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78]);
1896         /// ```
1897         #[unstable(feature = "int_to_from_bytes", issue = "52963")]
1898         #[inline]
1899         pub fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
1900             self.to_be().to_ne_bytes()
1901         }
1902
1903         /// Return the memory representation of this integer as a byte array in
1904         /// little-endian byte order.
1905         ///
1906         /// # Examples
1907         ///
1908         /// ```
1909         /// #![feature(int_to_from_bytes)]
1910         ///
1911         /// let bytes =  0x12_34_56_78_i32.to_le_bytes();
1912         /// assert_eq!(bytes, [0x78, 0x56, 0x34, 0x12]);
1913         /// ```
1914         #[unstable(feature = "int_to_from_bytes", issue = "52963")]
1915         #[inline]
1916         pub fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
1917             self.to_le().to_ne_bytes()
1918         }
1919
1920         /// Return the memory representation of this integer as a byte array in
1921         /// native byte order.
1922         ///
1923         /// As the target platform's native endianness is used, portable code
1924         /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
1925         /// instead.
1926         ///
1927         /// [`to_be_bytes`]: #method.to_be_bytes
1928         /// [`to_le_bytes`]: #method.to_le_bytes
1929         ///
1930         /// # Examples
1931         ///
1932         /// ```
1933         /// #![feature(int_to_from_bytes)]
1934         ///
1935         /// let bytes = i32::min_value().to_be().to_ne_bytes();
1936         /// assert_eq!(bytes, [0x80, 0, 0, 0]);
1937         /// ```
1938         #[unstable(feature = "int_to_from_bytes", issue = "52963")]
1939         #[inline]
1940         pub fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
1941             unsafe { mem::transmute(self) }
1942         }
1943
1944         /// Create an integer value from its representation as a byte array in
1945         /// big endian.
1946         ///
1947         /// # Examples
1948         ///
1949         /// ```
1950         /// #![feature(int_to_from_bytes)]
1951         ///
1952         /// let int = i32::from_be_bytes([0x12, 0x34, 0x56, 0x78]);
1953         /// assert_eq!(int, 0x12_34_56_78);
1954         /// ```
1955         #[unstable(feature = "int_to_from_bytes", issue = "52963")]
1956         #[inline]
1957         pub fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
1958             Self::from_be(Self::from_ne_bytes(bytes))
1959         }
1960
1961         /// Create an integer value from its representation as a byte array in
1962         /// little endian.
1963         ///
1964         /// # Examples
1965         ///
1966         /// ```
1967         /// #![feature(int_to_from_bytes)]
1968         ///
1969         /// let int = i32::from_le_bytes([0x12, 0x34, 0x56, 0x78]);
1970         /// assert_eq!(int, 0x78_56_34_12);
1971         /// ```
1972         #[unstable(feature = "int_to_from_bytes", issue = "52963")]
1973         #[inline]
1974         pub fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
1975             Self::from_le(Self::from_ne_bytes(bytes))
1976         }
1977
1978         /// Create an integer value from its memory representation as a byte
1979         /// array in native endianness.
1980         ///
1981         /// As the target platform's native endianness is used, portable code
1982         /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
1983         /// appropriate instead.
1984         ///
1985         /// [`from_be_bytes`]: #method.from_be_bytes
1986         /// [`from_le_bytes`]: #method.from_le_bytes
1987         ///
1988         /// # Examples
1989         ///
1990         /// ```
1991         /// #![feature(int_to_from_bytes)]
1992         ///
1993         /// let int = i32::from_be(i32::from_ne_bytes([0x80, 0, 0, 0]));
1994         /// assert_eq!(int, i32::min_value());
1995         /// ```
1996         #[unstable(feature = "int_to_from_bytes", issue = "52963")]
1997         #[inline]
1998         pub fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
1999             unsafe { mem::transmute(bytes) }
2000         }
2001     }
2002 }
2003
2004 #[lang = "i8"]
2005 impl i8 {
2006     int_impl! { i8, i8, u8, 8, -128, 127, "", "", 2, "-0x7e", "0xa", "0x12", "0x12", "0x48" }
2007 }
2008
2009 #[lang = "i16"]
2010 impl i16 {
2011     int_impl! { i16, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234", "0x3412",
2012         "0x2c48" }
2013 }
2014
2015 #[lang = "i32"]
2016 impl i32 {
2017     int_impl! { i32, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2018         "0x12345678", "0x78563412", "0x1e6a2c48" }
2019 }
2020
2021 #[lang = "i64"]
2022 impl i64 {
2023     int_impl! { i64, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "", 12,
2024          "0xaa00000000006e1", "0x6e10aa", "0x1234567890123456", "0x5634129078563412",
2025          "0x6a2c48091e6a2c48" }
2026 }
2027
2028 #[lang = "i128"]
2029 impl i128 {
2030     int_impl! { i128, i128, u128, 128, -170141183460469231731687303715884105728,
2031         170141183460469231731687303715884105727, "", "", 16,
2032         "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
2033         "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48"
2034     }
2035 }
2036
2037 #[cfg(target_pointer_width = "16")]
2038 #[lang = "isize"]
2039 impl isize {
2040     int_impl! { isize, i16, u16, 16, -32768, 32767, "", "", 4, "-0x5ffd", "0x3a", "0x1234",
2041         "0x3412", "0x2c48" }
2042 }
2043
2044 #[cfg(target_pointer_width = "32")]
2045 #[lang = "isize"]
2046 impl isize {
2047     int_impl! { isize, i32, u32, 32, -2147483648, 2147483647, "", "", 8, "0x10000b3", "0xb301",
2048         "0x12345678", "0x78563412", "0x1e6a2c48" }
2049 }
2050
2051 #[cfg(target_pointer_width = "64")]
2052 #[lang = "isize"]
2053 impl isize {
2054     int_impl! { isize, i64, u64, 64, -9223372036854775808, 9223372036854775807, "", "",
2055         12, "0xaa00000000006e1", "0x6e10aa",  "0x1234567890123456", "0x5634129078563412",
2056          "0x6a2c48091e6a2c48" }
2057 }
2058
2059 // Emits the correct `cttz` call, depending on the size of the type.
2060 macro_rules! uint_cttz_call {
2061     // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
2062     // emits two conditional moves on x86_64. By promoting the value to
2063     // u16 and setting bit 8, we get better code without any conditional
2064     // operations.
2065     // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
2066     // pending, remove this workaround once LLVM generates better code
2067     // for cttz8.
2068     ($value:expr, 8) => { intrinsics::cttz($value as u16 | 0x100) };
2069     ($value:expr, $_BITS:expr) => { intrinsics::cttz($value) }
2070 }
2071
2072 // `Int` + `UnsignedInt` implemented for unsigned integers
2073 macro_rules! uint_impl {
2074     ($SelfT:ty, $ActualT:ty, $BITS:expr, $MaxV:expr, $Feature:expr, $EndFeature:expr,
2075         $rot:expr, $rot_op:expr, $rot_result:expr, $swap_op:expr, $swapped:expr,
2076         $reversed:expr ) => {
2077         doc_comment! {
2078             concat!("Returns the smallest value that can be represented by this integer type.
2079
2080 # Examples
2081
2082 Basic usage:
2083
2084 ```
2085 ", $Feature, "assert_eq!(", stringify!($SelfT), "::min_value(), 0);", $EndFeature, "
2086 ```"),
2087             #[stable(feature = "rust1", since = "1.0.0")]
2088             #[inline]
2089             pub const fn min_value() -> Self { 0 }
2090         }
2091
2092         doc_comment! {
2093             concat!("Returns the largest value that can be represented by this integer type.
2094
2095 # Examples
2096
2097 Basic usage:
2098
2099 ```
2100 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value(), ",
2101 stringify!($MaxV), ");", $EndFeature, "
2102 ```"),
2103             #[stable(feature = "rust1", since = "1.0.0")]
2104             #[inline]
2105             pub const fn max_value() -> Self { !0 }
2106         }
2107
2108         doc_comment! {
2109             concat!("Converts a string slice in a given base to an integer.
2110
2111 The string is expected to be an optional `+` sign
2112 followed by digits.
2113 Leading and trailing whitespace represent an error.
2114 Digits are a subset of these characters, depending on `radix`:
2115
2116 * `0-9`
2117 * `a-z`
2118 * `A-Z`
2119
2120 # Panics
2121
2122 This function panics if `radix` is not in the range from 2 to 36.
2123
2124 # Examples
2125
2126 Basic usage:
2127
2128 ```
2129 ", $Feature, "assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));",
2130 $EndFeature, "
2131 ```"),
2132             #[stable(feature = "rust1", since = "1.0.0")]
2133             pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
2134                 from_str_radix(src, radix)
2135             }
2136         }
2137
2138         doc_comment! {
2139             concat!("Returns the number of ones in the binary representation of `self`.
2140
2141 # Examples
2142
2143 Basic usage:
2144
2145 ```
2146 ", $Feature, "let n = 0b01001100", stringify!($SelfT), ";
2147
2148 assert_eq!(n.count_ones(), 3);", $EndFeature, "
2149 ```"),
2150             #[stable(feature = "rust1", since = "1.0.0")]
2151             #[rustc_const_unstable(feature = "const_int_ops")]
2152             #[inline]
2153             pub const fn count_ones(self) -> u32 {
2154                 unsafe { intrinsics::ctpop(self as $ActualT) as u32 }
2155             }
2156         }
2157
2158         doc_comment! {
2159             concat!("Returns the number of zeros in the binary representation of `self`.
2160
2161 # Examples
2162
2163 Basic usage:
2164
2165 ```
2166 ", $Feature, "assert_eq!(", stringify!($SelfT), "::max_value().count_zeros(), 0);", $EndFeature, "
2167 ```"),
2168             #[stable(feature = "rust1", since = "1.0.0")]
2169             #[rustc_const_unstable(feature = "const_int_ops")]
2170             #[inline]
2171             pub const fn count_zeros(self) -> u32 {
2172                 (!self).count_ones()
2173             }
2174         }
2175
2176         doc_comment! {
2177             concat!("Returns the number of leading zeros in the binary representation of `self`.
2178
2179 # Examples
2180
2181 Basic usage:
2182
2183 ```
2184 ", $Feature, "let n = ", stringify!($SelfT), "::max_value() >> 2;
2185
2186 assert_eq!(n.leading_zeros(), 2);", $EndFeature, "
2187 ```"),
2188             #[stable(feature = "rust1", since = "1.0.0")]
2189             #[rustc_const_unstable(feature = "const_int_ops")]
2190             #[inline]
2191             pub const fn leading_zeros(self) -> u32 {
2192                 unsafe { intrinsics::ctlz(self as $ActualT) as u32 }
2193             }
2194         }
2195
2196         doc_comment! {
2197             concat!("Returns the number of trailing zeros in the binary representation
2198 of `self`.
2199
2200 # Examples
2201
2202 Basic usage:
2203
2204 ```
2205 ", $Feature, "let n = 0b0101000", stringify!($SelfT), ";
2206
2207 assert_eq!(n.trailing_zeros(), 3);", $EndFeature, "
2208 ```"),
2209             #[stable(feature = "rust1", since = "1.0.0")]
2210             #[rustc_const_unstable(feature = "const_int_ops")]
2211             #[inline]
2212             pub const fn trailing_zeros(self) -> u32 {
2213                 unsafe { uint_cttz_call!(self, $BITS) as u32 }
2214             }
2215         }
2216
2217         doc_comment! {
2218             concat!("Shifts the bits to the left by a specified amount, `n`,
2219 wrapping the truncated bits to the end of the resulting integer.
2220
2221 Please note this isn't the same operation as `<<`!
2222
2223 # Examples
2224
2225 Basic usage:
2226
2227 ```
2228 let n = ", $rot_op, stringify!($SelfT), ";
2229 let m = ", $rot_result, ";
2230
2231 assert_eq!(n.rotate_left(", $rot, "), m);
2232 ```"),
2233             #[stable(feature = "rust1", since = "1.0.0")]
2234             #[inline]
2235             pub fn rotate_left(self, n: u32) -> Self {
2236                 // Protect against undefined behaviour for over-long bit shifts
2237                 let n = n % $BITS;
2238                 (self << n) | (self >> (($BITS - n) % $BITS))
2239             }
2240         }
2241
2242         doc_comment! {
2243             concat!("Shifts the bits to the right by a specified amount, `n`,
2244 wrapping the truncated bits to the beginning of the resulting
2245 integer.
2246
2247 Please note this isn't the same operation as `>>`!
2248
2249 # Examples
2250
2251 Basic usage:
2252
2253 ```
2254 let n = ", $rot_result, stringify!($SelfT), ";
2255 let m = ", $rot_op, ";
2256
2257 assert_eq!(n.rotate_right(", $rot, "), m);
2258 ```"),
2259             #[stable(feature = "rust1", since = "1.0.0")]
2260             #[inline]
2261             pub fn rotate_right(self, n: u32) -> Self {
2262                 // Protect against undefined behaviour for over-long bit shifts
2263                 let n = n % $BITS;
2264                 (self >> n) | (self << (($BITS - n) % $BITS))
2265             }
2266         }
2267
2268         doc_comment! {
2269             concat!("
2270 Reverses the byte order of the integer.
2271
2272 # Examples
2273
2274 Basic usage:
2275
2276 ```
2277 let n = ", $swap_op, stringify!($SelfT), ";
2278 let m = n.swap_bytes();
2279
2280 assert_eq!(m, ", $swapped, ");
2281 ```"),
2282             #[stable(feature = "rust1", since = "1.0.0")]
2283             #[rustc_const_unstable(feature = "const_int_ops")]
2284             #[inline]
2285             pub const fn swap_bytes(self) -> Self {
2286                 unsafe { intrinsics::bswap(self as $ActualT) as Self }
2287             }
2288         }
2289
2290         doc_comment! {
2291             concat!("Reverses the bit pattern of the integer.
2292
2293 # Examples
2294
2295 Basic usage:
2296
2297 ```
2298 #![feature(reverse_bits)]
2299
2300 let n = ", $swap_op, stringify!($SelfT), ";
2301 let m = n.reverse_bits();
2302
2303 assert_eq!(m, ", $reversed, ");
2304 ```"),
2305             #[unstable(feature = "reverse_bits", issue = "48763")]
2306             #[inline]
2307             pub fn reverse_bits(self) -> Self {
2308                 unsafe { intrinsics::bitreverse(self as $ActualT) as Self }
2309             }
2310         }
2311
2312         doc_comment! {
2313             concat!("Converts an integer from big endian to the target's endianness.
2314
2315 On big endian this is a no-op. On little endian the bytes are
2316 swapped.
2317
2318 # Examples
2319
2320 Basic usage:
2321
2322 ```
2323 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2324
2325 if cfg!(target_endian = \"big\") {
2326     assert_eq!(", stringify!($SelfT), "::from_be(n), n)
2327 } else {
2328     assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())
2329 }", $EndFeature, "
2330 ```"),
2331             #[stable(feature = "rust1", since = "1.0.0")]
2332             #[rustc_const_unstable(feature = "const_int_ops")]
2333             #[inline]
2334             pub const fn from_be(x: Self) -> Self {
2335                 #[cfg(target_endian = "big")]
2336                 {
2337                     x
2338                 }
2339                 #[cfg(not(target_endian = "big"))]
2340                 {
2341                     x.swap_bytes()
2342                 }
2343             }
2344         }
2345
2346         doc_comment! {
2347             concat!("Converts an integer from little endian to the target's endianness.
2348
2349 On little endian this is a no-op. On big endian the bytes are
2350 swapped.
2351
2352 # Examples
2353
2354 Basic usage:
2355
2356 ```
2357 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2358
2359 if cfg!(target_endian = \"little\") {
2360     assert_eq!(", stringify!($SelfT), "::from_le(n), n)
2361 } else {
2362     assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())
2363 }", $EndFeature, "
2364 ```"),
2365             #[stable(feature = "rust1", since = "1.0.0")]
2366             #[rustc_const_unstable(feature = "const_int_ops")]
2367             #[inline]
2368             pub const fn from_le(x: Self) -> Self {
2369                 #[cfg(target_endian = "little")]
2370                 {
2371                     x
2372                 }
2373                 #[cfg(not(target_endian = "little"))]
2374                 {
2375                     x.swap_bytes()
2376                 }
2377             }
2378         }
2379
2380         doc_comment! {
2381             concat!("Converts `self` to big endian from the target's endianness.
2382
2383 On big endian this is a no-op. On little endian the bytes are
2384 swapped.
2385
2386 # Examples
2387
2388 Basic usage:
2389
2390 ```
2391 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2392
2393 if cfg!(target_endian = \"big\") {
2394     assert_eq!(n.to_be(), n)
2395 } else {
2396     assert_eq!(n.to_be(), n.swap_bytes())
2397 }", $EndFeature, "
2398 ```"),
2399             #[stable(feature = "rust1", since = "1.0.0")]
2400             #[rustc_const_unstable(feature = "const_int_ops")]
2401             #[inline]
2402             pub const fn to_be(self) -> Self { // or not to be?
2403                 #[cfg(target_endian = "big")]
2404                 {
2405                     self
2406                 }
2407                 #[cfg(not(target_endian = "big"))]
2408                 {
2409                     self.swap_bytes()
2410                 }
2411             }
2412         }
2413
2414         doc_comment! {
2415             concat!("Converts `self` to little endian from the target's endianness.
2416
2417 On little endian this is a no-op. On big endian the bytes are
2418 swapped.
2419
2420 # Examples
2421
2422 Basic usage:
2423
2424 ```
2425 ", $Feature, "let n = 0x1A", stringify!($SelfT), ";
2426
2427 if cfg!(target_endian = \"little\") {
2428     assert_eq!(n.to_le(), n)
2429 } else {
2430     assert_eq!(n.to_le(), n.swap_bytes())
2431 }", $EndFeature, "
2432 ```"),
2433             #[stable(feature = "rust1", since = "1.0.0")]
2434             #[rustc_const_unstable(feature = "const_int_ops")]
2435             #[inline]
2436             pub const fn to_le(self) -> Self {
2437                 #[cfg(target_endian = "little")]
2438                 {
2439                     self
2440                 }
2441                 #[cfg(not(target_endian = "little"))]
2442                 {
2443                     self.swap_bytes()
2444                 }
2445             }
2446         }
2447
2448         doc_comment! {
2449             concat!("Checked integer addition. Computes `self + rhs`, returning `None`
2450 if overflow occurred.
2451
2452 # Examples
2453
2454 Basic usage:
2455
2456 ```
2457 ", $Feature, "assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(1), ",
2458 "Some(", stringify!($SelfT), "::max_value() - 1));
2459 assert_eq!((", stringify!($SelfT), "::max_value() - 2).checked_add(3), None);", $EndFeature, "
2460 ```"),
2461             #[stable(feature = "rust1", since = "1.0.0")]
2462             #[inline]
2463             pub fn checked_add(self, rhs: Self) -> Option<Self> {
2464                 let (a, b) = self.overflowing_add(rhs);
2465                 if b {None} else {Some(a)}
2466             }
2467         }
2468
2469         doc_comment! {
2470             concat!("Checked integer subtraction. Computes `self - rhs`, returning
2471 `None` if overflow occurred.
2472
2473 # Examples
2474
2475 Basic usage:
2476
2477 ```
2478 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));
2479 assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);", $EndFeature, "
2480 ```"),
2481             #[stable(feature = "rust1", since = "1.0.0")]
2482             #[inline]
2483             pub fn checked_sub(self, rhs: Self) -> Option<Self> {
2484                 let (a, b) = self.overflowing_sub(rhs);
2485                 if b {None} else {Some(a)}
2486             }
2487         }
2488
2489         doc_comment! {
2490             concat!("Checked integer multiplication. Computes `self * rhs`, returning
2491 `None` if overflow occurred.
2492
2493 # Examples
2494
2495 Basic usage:
2496
2497 ```
2498 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));
2499 assert_eq!(", stringify!($SelfT), "::max_value().checked_mul(2), None);", $EndFeature, "
2500 ```"),
2501             #[stable(feature = "rust1", since = "1.0.0")]
2502             #[inline]
2503             pub fn checked_mul(self, rhs: Self) -> Option<Self> {
2504                 let (a, b) = self.overflowing_mul(rhs);
2505                 if b {None} else {Some(a)}
2506             }
2507         }
2508
2509         doc_comment! {
2510             concat!("Checked integer division. Computes `self / rhs`, returning `None`
2511 if `rhs == 0`.
2512
2513 # Examples
2514
2515 Basic usage:
2516
2517 ```
2518 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2519 assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);", $EndFeature, "
2520 ```"),
2521             #[stable(feature = "rust1", since = "1.0.0")]
2522             #[inline]
2523             pub fn checked_div(self, rhs: Self) -> Option<Self> {
2524                 match rhs {
2525                     0 => None,
2526                     rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
2527                 }
2528             }
2529         }
2530
2531         doc_comment! {
2532             concat!("Checked Euclidean division. Computes `self.div_euc(rhs)`, returning `None`
2533 if `rhs == 0`.
2534
2535 # Examples
2536
2537 Basic usage:
2538
2539 ```
2540 #![feature(euclidean_division)]
2541 assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));
2542 assert_eq!(1", stringify!($SelfT), ".checked_div_euc(0), None);
2543 ```"),
2544             #[unstable(feature = "euclidean_division", issue = "49048")]
2545             #[inline]
2546             pub fn checked_div_euc(self, rhs: Self) -> Option<Self> {
2547                 if rhs == 0 {
2548                     None
2549                 } else {
2550                     Some(self.div_euc(rhs))
2551                 }
2552             }
2553         }
2554
2555
2556         doc_comment! {
2557             concat!("Checked integer remainder. Computes `self % rhs`, returning `None`
2558 if `rhs == 0`.
2559
2560 # Examples
2561
2562 Basic usage:
2563
2564 ```
2565 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));
2566 assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);", $EndFeature, "
2567 ```"),
2568             #[stable(feature = "wrapping", since = "1.7.0")]
2569             #[inline]
2570             pub fn checked_rem(self, rhs: Self) -> Option<Self> {
2571                 if rhs == 0 {
2572                     None
2573                 } else {
2574                     Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
2575                 }
2576             }
2577         }
2578
2579         doc_comment! {
2580             concat!("Checked Euclidean modulo. Computes `self.mod_euc(rhs)`, returning `None`
2581 if `rhs == 0`.
2582
2583 # Examples
2584
2585 Basic usage:
2586
2587 ```
2588 #![feature(euclidean_division)]
2589 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(2), Some(1));
2590 assert_eq!(5", stringify!($SelfT), ".checked_mod_euc(0), None);
2591 ```"),
2592             #[unstable(feature = "euclidean_division", issue = "49048")]
2593             #[inline]
2594             pub fn checked_mod_euc(self, rhs: Self) -> Option<Self> {
2595                 if rhs == 0 {
2596                     None
2597                 } else {
2598                     Some(self.mod_euc(rhs))
2599                 }
2600             }
2601         }
2602
2603         doc_comment! {
2604             concat!("Checked negation. Computes `-self`, returning `None` unless `self ==
2605 0`.
2606
2607 Note that negating any positive integer will overflow.
2608
2609 # Examples
2610
2611 Basic usage:
2612
2613 ```
2614 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));
2615 assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);", $EndFeature, "
2616 ```"),
2617             #[stable(feature = "wrapping", since = "1.7.0")]
2618             #[inline]
2619             pub fn checked_neg(self) -> Option<Self> {
2620                 let (a, b) = self.overflowing_neg();
2621                 if b {None} else {Some(a)}
2622             }
2623         }
2624
2625         doc_comment! {
2626             concat!("Checked shift left. Computes `self << rhs`, returning `None`
2627 if `rhs` is larger than or equal to the number of bits in `self`.
2628
2629 # Examples
2630
2631 Basic usage:
2632
2633 ```
2634 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));
2635 assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);", $EndFeature, "
2636 ```"),
2637             #[stable(feature = "wrapping", since = "1.7.0")]
2638             #[inline]
2639             pub fn checked_shl(self, rhs: u32) -> Option<Self> {
2640                 let (a, b) = self.overflowing_shl(rhs);
2641                 if b {None} else {Some(a)}
2642             }
2643         }
2644
2645         doc_comment! {
2646             concat!("Checked shift right. Computes `self >> rhs`, returning `None`
2647 if `rhs` is larger than or equal to the number of bits in `self`.
2648
2649 # Examples
2650
2651 Basic usage:
2652
2653 ```
2654 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));
2655 assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);", $EndFeature, "
2656 ```"),
2657             #[stable(feature = "wrapping", since = "1.7.0")]
2658             #[inline]
2659             pub fn checked_shr(self, rhs: u32) -> Option<Self> {
2660                 let (a, b) = self.overflowing_shr(rhs);
2661                 if b {None} else {Some(a)}
2662             }
2663         }
2664
2665         doc_comment! {
2666             concat!("Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2667 overflow occurred.
2668
2669 # Examples
2670
2671 Basic usage:
2672
2673 ```
2674 #![feature(no_panic_pow)]
2675 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));
2676 assert_eq!(", stringify!($SelfT), "::max_value().checked_pow(2), None);", $EndFeature, "
2677 ```"),
2678             #[unstable(feature = "no_panic_pow", issue = "48320")]
2679             #[inline]
2680             pub fn checked_pow(self, mut exp: u32) -> Option<Self> {
2681                 let mut base = self;
2682                 let mut acc: Self = 1;
2683
2684                 while exp > 1 {
2685                     if (exp & 1) == 1 {
2686                         acc = acc.checked_mul(base)?;
2687                     }
2688                     exp /= 2;
2689                     base = base.checked_mul(base)?;
2690                 }
2691
2692                 // Deal with the final bit of the exponent separately, since
2693                 // squaring the base afterwards is not necessary and may cause a
2694                 // needless overflow.
2695                 if exp == 1 {
2696                     acc = acc.checked_mul(base)?;
2697                 }
2698
2699                 Some(acc)
2700             }
2701         }
2702
2703         doc_comment! {
2704             concat!("Saturating integer addition. Computes `self + rhs`, saturating at
2705 the numeric bounds instead of overflowing.
2706
2707 # Examples
2708
2709 Basic usage:
2710
2711 ```
2712 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);
2713 assert_eq!(200u8.saturating_add(127), 255);", $EndFeature, "
2714 ```"),
2715             #[stable(feature = "rust1", since = "1.0.0")]
2716             #[inline]
2717             pub fn saturating_add(self, rhs: Self) -> Self {
2718                 match self.checked_add(rhs) {
2719                     Some(x) => x,
2720                     None => Self::max_value(),
2721                 }
2722             }
2723         }
2724
2725         doc_comment! {
2726             concat!("Saturating integer subtraction. Computes `self - rhs`, saturating
2727 at the numeric bounds instead of overflowing.
2728
2729 # Examples
2730
2731 Basic usage:
2732
2733 ```
2734 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);
2735 assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);", $EndFeature, "
2736 ```"),
2737             #[stable(feature = "rust1", since = "1.0.0")]
2738             #[inline]
2739             pub fn saturating_sub(self, rhs: Self) -> Self {
2740                 match self.checked_sub(rhs) {
2741                     Some(x) => x,
2742                     None => Self::min_value(),
2743                 }
2744             }
2745         }
2746
2747         doc_comment! {
2748             concat!("Saturating integer multiplication. Computes `self * rhs`,
2749 saturating at the numeric bounds instead of overflowing.
2750
2751 # Examples
2752
2753 Basic usage:
2754
2755 ```
2756 ", $Feature, "use std::", stringify!($SelfT), ";
2757
2758 assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);
2759 assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),
2760 "::MAX);", $EndFeature, "
2761 ```"),
2762             #[stable(feature = "wrapping", since = "1.7.0")]
2763             #[inline]
2764             pub fn saturating_mul(self, rhs: Self) -> Self {
2765                 self.checked_mul(rhs).unwrap_or(Self::max_value())
2766             }
2767         }
2768
2769         doc_comment! {
2770             concat!("Saturating integer exponentiation. Computes `self.pow(exp)`,
2771 saturating at the numeric bounds instead of overflowing.
2772
2773 # Examples
2774
2775 Basic usage:
2776
2777 ```
2778 #![feature(no_panic_pow)]
2779 ", $Feature, "use std::", stringify!($SelfT), ";
2780
2781 assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);
2782 assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);",
2783 $EndFeature, "
2784 ```"),
2785             #[unstable(feature = "no_panic_pow", issue = "48320")]
2786             #[inline]
2787             pub fn saturating_pow(self, exp: u32) -> Self {
2788                 match self.checked_pow(exp) {
2789                     Some(x) => x,
2790                     None => Self::max_value(),
2791                 }
2792             }
2793         }
2794
2795         doc_comment! {
2796             concat!("Wrapping (modular) addition. Computes `self + rhs`,
2797 wrapping around at the boundary of the type.
2798
2799 # Examples
2800
2801 Basic usage:
2802
2803 ```
2804 ", $Feature, "assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);
2805 assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::max_value()), 199);",
2806 $EndFeature, "
2807 ```"),
2808             #[stable(feature = "rust1", since = "1.0.0")]
2809             #[inline]
2810             pub fn wrapping_add(self, rhs: Self) -> Self {
2811                 unsafe {
2812                     intrinsics::overflowing_add(self, rhs)
2813                 }
2814             }
2815         }
2816
2817         doc_comment! {
2818             concat!("Wrapping (modular) subtraction. Computes `self - rhs`,
2819 wrapping around at the boundary of the type.
2820
2821 # Examples
2822
2823 Basic usage:
2824
2825 ```
2826 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);
2827 assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::max_value()), 101);",
2828 $EndFeature, "
2829 ```"),
2830             #[stable(feature = "rust1", since = "1.0.0")]
2831             #[inline]
2832             pub fn wrapping_sub(self, rhs: Self) -> Self {
2833                 unsafe {
2834                     intrinsics::overflowing_sub(self, rhs)
2835                 }
2836             }
2837         }
2838
2839         /// Wrapping (modular) multiplication. Computes `self *
2840         /// rhs`, wrapping around at the boundary of the type.
2841         ///
2842         /// # Examples
2843         ///
2844         /// Basic usage:
2845         ///
2846         /// Please note that this example is shared between integer types.
2847         /// Which explains why `u8` is used here.
2848         ///
2849         /// ```
2850         /// assert_eq!(10u8.wrapping_mul(12), 120);
2851         /// assert_eq!(25u8.wrapping_mul(12), 44);
2852         /// ```
2853         #[stable(feature = "rust1", since = "1.0.0")]
2854         #[inline]
2855         pub fn wrapping_mul(self, rhs: Self) -> Self {
2856             unsafe {
2857                 intrinsics::overflowing_mul(self, rhs)
2858             }
2859         }
2860
2861         doc_comment! {
2862             concat!("Wrapping (modular) division. Computes `self / rhs`.
2863 Wrapped division on unsigned types is just normal division.
2864 There's no way wrapping could ever happen.
2865 This function exists, so that all operations
2866 are accounted for in the wrapping operations.
2867
2868 # Examples
2869
2870 Basic usage:
2871
2872 ```
2873 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);", $EndFeature, "
2874 ```"),
2875             #[stable(feature = "num_wrapping", since = "1.2.0")]
2876             #[inline]
2877             pub fn wrapping_div(self, rhs: Self) -> Self {
2878                 self / rhs
2879             }
2880         }
2881
2882         doc_comment! {
2883             concat!("Wrapping Euclidean division. Computes `self.div_euc(rhs)`.
2884 Wrapped division on unsigned types is just normal division.
2885 There's no way wrapping could ever happen.
2886 This function exists, so that all operations
2887 are accounted for in the wrapping operations.
2888
2889 # Examples
2890
2891 Basic usage:
2892
2893 ```
2894 #![feature(euclidean_division)]
2895 assert_eq!(100", stringify!($SelfT), ".wrapping_div_euc(10), 10);
2896 ```"),
2897             #[unstable(feature = "euclidean_division", issue = "49048")]
2898             #[inline]
2899             pub fn wrapping_div_euc(self, rhs: Self) -> Self {
2900                 self / rhs
2901             }
2902         }
2903
2904         doc_comment! {
2905             concat!("Wrapping (modular) remainder. Computes `self % rhs`.
2906 Wrapped remainder calculation on unsigned types is
2907 just the regular remainder calculation.
2908 There's no way wrapping could ever happen.
2909 This function exists, so that all operations
2910 are accounted for in the wrapping operations.
2911
2912 # Examples
2913
2914 Basic usage:
2915
2916 ```
2917 ", $Feature, "assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);", $EndFeature, "
2918 ```"),
2919             #[stable(feature = "num_wrapping", since = "1.2.0")]
2920             #[inline]
2921             pub fn wrapping_rem(self, rhs: Self) -> Self {
2922                 self % rhs
2923             }
2924         }
2925
2926         doc_comment! {
2927             concat!("Wrapping Euclidean modulo. Computes `self.mod_euc(rhs)`.
2928 Wrapped modulo calculation on unsigned types is
2929 just the regular remainder calculation.
2930 There's no way wrapping could ever happen.
2931 This function exists, so that all operations
2932 are accounted for in the wrapping operations.
2933
2934 # Examples
2935
2936 Basic usage:
2937
2938 ```
2939 #![feature(euclidean_division)]
2940 assert_eq!(100", stringify!($SelfT), ".wrapping_mod_euc(10), 0);
2941 ```"),
2942             #[unstable(feature = "euclidean_division", issue = "49048")]
2943             #[inline]
2944             pub fn wrapping_mod_euc(self, rhs: Self) -> Self {
2945                 self % rhs
2946             }
2947         }
2948
2949         /// Wrapping (modular) negation. Computes `-self`,
2950         /// wrapping around at the boundary of the type.
2951         ///
2952         /// Since unsigned types do not have negative equivalents
2953         /// all applications of this function will wrap (except for `-0`).
2954         /// For values smaller than the corresponding signed type's maximum
2955         /// the result is the same as casting the corresponding signed value.
2956         /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
2957         /// `MAX` is the corresponding signed type's maximum.
2958         ///
2959         /// # Examples
2960         ///
2961         /// Basic usage:
2962         ///
2963         /// Please note that this example is shared between integer types.
2964         /// Which explains why `i8` is used here.
2965         ///
2966         /// ```
2967         /// assert_eq!(100i8.wrapping_neg(), -100);
2968         /// assert_eq!((-128i8).wrapping_neg(), -128);
2969         /// ```
2970         #[stable(feature = "num_wrapping", since = "1.2.0")]
2971         #[inline]
2972         pub fn wrapping_neg(self) -> Self {
2973             self.overflowing_neg().0
2974         }
2975
2976         doc_comment! {
2977             concat!("Panic-free bitwise shift-left; yields `self << mask(rhs)`,
2978 where `mask` removes any high-order bits of `rhs` that
2979 would cause the shift to exceed the bitwidth of the type.
2980
2981 Note that this is *not* the same as a rotate-left; the
2982 RHS of a wrapping shift-left is restricted to the range
2983 of the type, rather than the bits shifted out of the LHS
2984 being returned to the other end. The primitive integer
2985 types all implement a `rotate_left` function, which may
2986 be what you want instead.
2987
2988 # Examples
2989
2990 Basic usage:
2991
2992 ```
2993 ", $Feature, "assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);
2994 assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);", $EndFeature, "
2995 ```"),
2996             #[stable(feature = "num_wrapping", since = "1.2.0")]
2997             #[inline]
2998             pub fn wrapping_shl(self, rhs: u32) -> Self {
2999                 unsafe {
3000                     intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
3001                 }
3002             }
3003         }
3004
3005         doc_comment! {
3006             concat!("Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
3007 where `mask` removes any high-order bits of `rhs` that
3008 would cause the shift to exceed the bitwidth of the type.
3009
3010 Note that this is *not* the same as a rotate-right; the
3011 RHS of a wrapping shift-right is restricted to the range
3012 of the type, rather than the bits shifted out of the LHS
3013 being returned to the other end. The primitive integer
3014 types all implement a `rotate_right` function, which may
3015 be what you want instead.
3016
3017 # Examples
3018
3019 Basic usage:
3020
3021 ```
3022 ", $Feature, "assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);
3023 assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);", $EndFeature, "
3024 ```"),
3025             #[stable(feature = "num_wrapping", since = "1.2.0")]
3026             #[inline]
3027             pub fn wrapping_shr(self, rhs: u32) -> Self {
3028                 unsafe {
3029                     intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
3030                 }
3031             }
3032         }
3033
3034         doc_comment! {
3035             concat!("Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
3036 wrapping around at the boundary of the type.
3037
3038 # Examples
3039
3040 Basic usage:
3041
3042 ```
3043 #![feature(no_panic_pow)]
3044 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);
3045 assert_eq!(3u8.wrapping_pow(6), 217);", $EndFeature, "
3046 ```"),
3047             #[unstable(feature = "no_panic_pow", issue = "48320")]
3048             #[inline]
3049             pub fn wrapping_pow(self, mut exp: u32) -> Self {
3050                 let mut base = self;
3051                 let mut acc: Self = 1;
3052
3053                 while exp > 1 {
3054                     if (exp & 1) == 1 {
3055                         acc = acc.wrapping_mul(base);
3056                     }
3057                     exp /= 2;
3058                     base = base.wrapping_mul(base);
3059                 }
3060
3061                 // Deal with the final bit of the exponent separately, since
3062                 // squaring the base afterwards is not necessary and may cause a
3063                 // needless overflow.
3064                 if exp == 1 {
3065                     acc = acc.wrapping_mul(base);
3066                 }
3067
3068                 acc
3069             }
3070         }
3071
3072         doc_comment! {
3073             concat!("Calculates `self` + `rhs`
3074
3075 Returns a tuple of the addition along with a boolean indicating
3076 whether an arithmetic overflow would occur. If an overflow would
3077 have occurred then the wrapped value is returned.
3078
3079 # Examples
3080
3081 Basic usage
3082
3083 ```
3084 ", $Feature, "use std::", stringify!($SelfT), ";
3085
3086 assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));
3087 assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));", $EndFeature, "
3088 ```"),
3089             #[inline]
3090             #[stable(feature = "wrapping", since = "1.7.0")]
3091             pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
3092                 let (a, b) = unsafe {
3093                     intrinsics::add_with_overflow(self as $ActualT,
3094                                                   rhs as $ActualT)
3095                 };
3096                 (a as Self, b)
3097             }
3098         }
3099
3100         doc_comment! {
3101             concat!("Calculates `self` - `rhs`
3102
3103 Returns a tuple of the subtraction along with a boolean indicating
3104 whether an arithmetic overflow would occur. If an overflow would
3105 have occurred then the wrapped value is returned.
3106
3107 # Examples
3108
3109 Basic usage
3110
3111 ```
3112 ", $Feature, "use std::", stringify!($SelfT), ";
3113
3114 assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));
3115 assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));",
3116 $EndFeature, "
3117 ```"),
3118             #[inline]
3119             #[stable(feature = "wrapping", since = "1.7.0")]
3120             pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
3121                 let (a, b) = unsafe {
3122                     intrinsics::sub_with_overflow(self as $ActualT,
3123                                                   rhs as $ActualT)
3124                 };
3125                 (a as Self, b)
3126             }
3127         }
3128
3129         /// Calculates the multiplication of `self` and `rhs`.
3130         ///
3131         /// Returns a tuple of the multiplication along with a boolean
3132         /// indicating whether an arithmetic overflow would occur. If an
3133         /// overflow would have occurred then the wrapped value is returned.
3134         ///
3135         /// # Examples
3136         ///
3137         /// Basic usage:
3138         ///
3139         /// Please note that this example is shared between integer types.
3140         /// Which explains why `u32` is used here.
3141         ///
3142         /// ```
3143         /// assert_eq!(5u32.overflowing_mul(2), (10, false));
3144         /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
3145         /// ```
3146         #[inline]
3147         #[stable(feature = "wrapping", since = "1.7.0")]
3148         pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
3149             let (a, b) = unsafe {
3150                 intrinsics::mul_with_overflow(self as $ActualT,
3151                                               rhs as $ActualT)
3152             };
3153             (a as Self, b)
3154         }
3155
3156         doc_comment! {
3157             concat!("Calculates the divisor when `self` is divided by `rhs`.
3158
3159 Returns a tuple of the divisor along with a boolean indicating
3160 whether an arithmetic overflow would occur. Note that for unsigned
3161 integers overflow never occurs, so the second value is always
3162 `false`.
3163
3164 # Panics
3165
3166 This function will panic if `rhs` is 0.
3167
3168 # Examples
3169
3170 Basic usage
3171
3172 ```
3173 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));", $EndFeature, "
3174 ```"),
3175             #[inline]
3176             #[stable(feature = "wrapping", since = "1.7.0")]
3177             pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3178                 (self / rhs, false)
3179             }
3180         }
3181
3182         doc_comment! {
3183             concat!("Calculates the quotient of Euclidean division `self.div_euc(rhs)`.
3184
3185 Returns a tuple of the divisor along with a boolean indicating
3186 whether an arithmetic overflow would occur. Note that for unsigned
3187 integers overflow never occurs, so the second value is always
3188 `false`.
3189
3190 # Panics
3191
3192 This function will panic if `rhs` is 0.
3193
3194 # Examples
3195
3196 Basic usage
3197
3198 ```
3199 #![feature(euclidean_division)]
3200 assert_eq!(5", stringify!($SelfT), ".overflowing_div_euc(2), (2, false));
3201 ```"),
3202             #[inline]
3203             #[unstable(feature = "euclidean_division", issue = "49048")]
3204             pub fn overflowing_div_euc(self, rhs: Self) -> (Self, bool) {
3205                 (self / rhs, false)
3206             }
3207         }
3208
3209         doc_comment! {
3210             concat!("Calculates the remainder when `self` is divided by `rhs`.
3211
3212 Returns a tuple of the remainder after dividing along with a boolean
3213 indicating whether an arithmetic overflow would occur. Note that for
3214 unsigned integers overflow never occurs, so the second value is
3215 always `false`.
3216
3217 # Panics
3218
3219 This function will panic if `rhs` is 0.
3220
3221 # Examples
3222
3223 Basic usage
3224
3225 ```
3226 ", $Feature, "assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));", $EndFeature, "
3227 ```"),
3228             #[inline]
3229             #[stable(feature = "wrapping", since = "1.7.0")]
3230             pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3231                 (self % rhs, false)
3232             }
3233         }
3234
3235         doc_comment! {
3236             concat!("Calculates the remainder `self.mod_euc(rhs)` by Euclidean division.
3237
3238 Returns a tuple of the modulo after dividing along with a boolean
3239 indicating whether an arithmetic overflow would occur. Note that for
3240 unsigned integers overflow never occurs, so the second value is
3241 always `false`.
3242
3243 # Panics
3244
3245 This function will panic if `rhs` is 0.
3246
3247 # Examples
3248
3249 Basic usage
3250
3251 ```
3252 #![feature(euclidean_division)]
3253 assert_eq!(5", stringify!($SelfT), ".overflowing_mod_euc(2), (1, false));
3254 ```"),
3255             #[inline]
3256             #[unstable(feature = "euclidean_division", issue = "49048")]
3257             pub fn overflowing_mod_euc(self, rhs: Self) -> (Self, bool) {
3258                 (self % rhs, false)
3259             }
3260         }
3261
3262         doc_comment! {
3263             concat!("Negates self in an overflowing fashion.
3264
3265 Returns `!self + 1` using wrapping operations to return the value
3266 that represents the negation of this unsigned value. Note that for
3267 positive unsigned values overflow always occurs, but negating 0 does
3268 not overflow.
3269
3270 # Examples
3271
3272 Basic usage
3273
3274 ```
3275 ", $Feature, "assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));
3276 assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT),
3277 ", true));", $EndFeature, "
3278 ```"),
3279             #[inline]
3280             #[stable(feature = "wrapping", since = "1.7.0")]
3281             pub fn overflowing_neg(self) -> (Self, bool) {
3282                 ((!self).wrapping_add(1), self != 0)
3283             }
3284         }
3285
3286         doc_comment! {
3287             concat!("Shifts self left by `rhs` bits.
3288
3289 Returns a tuple of the shifted version of self along with a boolean
3290 indicating whether the shift value was larger than or equal to the
3291 number of bits. If the shift value is too large, then value is
3292 masked (N-1) where N is the number of bits, and this value is then
3293 used to perform the shift.
3294
3295 # Examples
3296
3297 Basic usage
3298
3299 ```
3300 ", $Feature, "assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));
3301 assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));", $EndFeature, "
3302 ```"),
3303             #[inline]
3304             #[stable(feature = "wrapping", since = "1.7.0")]
3305             pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3306                 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
3307             }
3308         }
3309
3310         doc_comment! {
3311             concat!("Shifts self right by `rhs` bits.
3312
3313 Returns a tuple of the shifted version of self along with a boolean
3314 indicating whether the shift value was larger than or equal to the
3315 number of bits. If the shift value is too large, then value is
3316 masked (N-1) where N is the number of bits, and this value is then
3317 used to perform the shift.
3318
3319 # Examples
3320
3321 Basic usage
3322
3323 ```
3324 ", $Feature, "assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));
3325 assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));", $EndFeature, "
3326 ```"),
3327             #[inline]
3328             #[stable(feature = "wrapping", since = "1.7.0")]
3329             pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3330                 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
3331             }
3332         }
3333
3334         doc_comment! {
3335             concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3336
3337 Returns a tuple of the exponentiation along with a bool indicating
3338 whether an overflow happened.
3339
3340 # Examples
3341
3342 Basic usage:
3343
3344 ```
3345 #![feature(no_panic_pow)]
3346 ", $Feature, "assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));
3347 assert_eq!(3u8.overflowing_pow(6), (217, true));", $EndFeature, "
3348 ```"),
3349             #[unstable(feature = "no_panic_pow", issue = "48320")]
3350             #[inline]
3351             pub fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3352                 let mut base = self;
3353                 let mut acc: Self = 1;
3354                 let mut overflown = false;
3355                 // Scratch space for storing results of overflowing_mul.
3356                 let mut r;
3357
3358                 while exp > 1 {
3359                     if (exp & 1) == 1 {
3360                         r = acc.overflowing_mul(base);
3361                         acc = r.0;
3362                         overflown |= r.1;
3363                     }
3364                     exp /= 2;
3365                     r = base.overflowing_mul(base);
3366                     base = r.0;
3367                     overflown |= r.1;
3368                 }
3369
3370                 // Deal with the final bit of the exponent separately, since
3371                 // squaring the base afterwards is not necessary and may cause a
3372                 // needless overflow.
3373                 if exp == 1 {
3374                     r = acc.overflowing_mul(base);
3375                     acc = r.0;
3376                     overflown |= r.1;
3377                 }
3378
3379                 (acc, overflown)
3380             }
3381         }
3382
3383         doc_comment! {
3384             concat!("Raises self to the power of `exp`, using exponentiation by squaring.
3385
3386 # Examples
3387
3388 Basic usage:
3389
3390 ```
3391 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".pow(5), 32);", $EndFeature, "
3392 ```"),
3393         #[stable(feature = "rust1", since = "1.0.0")]
3394         #[inline]
3395         #[rustc_inherit_overflow_checks]
3396         pub fn pow(self, mut exp: u32) -> Self {
3397             let mut base = self;
3398             let mut acc = 1;
3399
3400             while exp > 1 {
3401                 if (exp & 1) == 1 {
3402                     acc = acc * base;
3403                 }
3404                 exp /= 2;
3405                 base = base * base;
3406             }
3407
3408             // Deal with the final bit of the exponent separately, since
3409             // squaring the base afterwards is not necessary and may cause a
3410             // needless overflow.
3411             if exp == 1 {
3412                 acc = acc * base;
3413             }
3414
3415             acc
3416         }
3417     }
3418
3419             doc_comment! {
3420             concat!("Performs Euclidean division.
3421
3422 For unsigned types, this is just the same as `self / rhs`.
3423
3424 # Examples
3425
3426 Basic usage:
3427
3428 ```
3429 #![feature(euclidean_division)]
3430 assert_eq!(7", stringify!($SelfT), ".div_euc(4), 1); // or any other integer type
3431 ```"),
3432             #[unstable(feature = "euclidean_division", issue = "49048")]
3433             #[inline]
3434             #[rustc_inherit_overflow_checks]
3435             pub fn div_euc(self, rhs: Self) -> Self {
3436                 self / rhs
3437             }
3438         }
3439
3440
3441         doc_comment! {
3442             concat!("Calculates the remainder `self mod rhs` by Euclidean division.
3443
3444 For unsigned types, this is just the same as `self % rhs`.
3445
3446 # Examples
3447
3448 Basic usage:
3449
3450 ```
3451 #![feature(euclidean_division)]
3452 assert_eq!(7", stringify!($SelfT), ".mod_euc(4), 3); // or any other integer type
3453 ```"),
3454             #[unstable(feature = "euclidean_division", issue = "49048")]
3455             #[inline]
3456             #[rustc_inherit_overflow_checks]
3457             pub fn mod_euc(self, rhs: Self) -> Self {
3458                 self % rhs
3459             }
3460         }
3461
3462         doc_comment! {
3463             concat!("Returns `true` if and only if `self == 2^k` for some `k`.
3464
3465 # Examples
3466
3467 Basic usage:
3468
3469 ```
3470 ", $Feature, "assert!(16", stringify!($SelfT), ".is_power_of_two());
3471 assert!(!10", stringify!($SelfT), ".is_power_of_two());", $EndFeature, "
3472 ```"),
3473             #[stable(feature = "rust1", since = "1.0.0")]
3474             #[inline]
3475             pub fn is_power_of_two(self) -> bool {
3476                 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
3477             }
3478         }
3479
3480         // Returns one less than next power of two.
3481         // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
3482         //
3483         // 8u8.one_less_than_next_power_of_two() == 7
3484         // 6u8.one_less_than_next_power_of_two() == 7
3485         //
3486         // This method cannot overflow, as in the `next_power_of_two`
3487         // overflow cases it instead ends up returning the maximum value
3488         // of the type, and can return 0 for 0.
3489         #[inline]
3490         fn one_less_than_next_power_of_two(self) -> Self {
3491             if self <= 1 { return 0; }
3492
3493             // Because `p > 0`, it cannot consist entirely of leading zeros.
3494             // That means the shift is always in-bounds, and some processors
3495             // (such as intel pre-haswell) have more efficient ctlz
3496             // intrinsics when the argument is non-zero.
3497             let p = self - 1;
3498             let z = unsafe { intrinsics::ctlz_nonzero(p) };
3499             <$SelfT>::max_value() >> z
3500         }
3501
3502         doc_comment! {
3503             concat!("Returns the smallest power of two greater than or equal to `self`.
3504
3505 When return value overflows (i.e. `self > (1 << (N-1))` for type
3506 `uN`), it panics in debug mode and return value is wrapped to 0 in
3507 release mode (the only situation in which method can return 0).
3508
3509 # Examples
3510
3511 Basic usage:
3512
3513 ```
3514 ", $Feature, "assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);
3515 assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);", $EndFeature, "
3516 ```"),
3517             #[stable(feature = "rust1", since = "1.0.0")]
3518             #[inline]
3519             pub fn next_power_of_two(self) -> Self {
3520                 // Call the trait to get overflow checks
3521                 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
3522             }
3523         }
3524
3525         doc_comment! {
3526             concat!("Returns the smallest power of two greater than or equal to `n`. If
3527 the next power of two is greater than the type's maximum value,
3528 `None` is returned, otherwise the power of two is wrapped in `Some`.
3529
3530 # Examples
3531
3532 Basic usage:
3533
3534 ```
3535 ", $Feature, "assert_eq!(2", stringify!($SelfT),
3536 ".checked_next_power_of_two(), Some(2));
3537 assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));
3538 assert_eq!(", stringify!($SelfT), "::max_value().checked_next_power_of_two(), None);",
3539 $EndFeature, "
3540 ```"),
3541             #[stable(feature = "rust1", since = "1.0.0")]
3542             pub fn checked_next_power_of_two(self) -> Option<Self> {
3543                 self.one_less_than_next_power_of_two().checked_add(1)
3544             }
3545         }
3546
3547         doc_comment! {
3548             concat!("Returns the smallest power of two greater than or equal to `n`. If
3549 the next power of two is greater than the type's maximum value,
3550 the return value is wrapped to `0`.
3551
3552 # Examples
3553
3554 Basic usage:
3555
3556 ```
3557 #![feature(wrapping_next_power_of_two)]
3558 ", $Feature, "
3559 assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);
3560 assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);
3561 assert_eq!(", stringify!($SelfT), "::max_value().wrapping_next_power_of_two(), 0);",
3562 $EndFeature, "
3563 ```"),
3564             #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
3565                        reason = "needs decision on wrapping behaviour")]
3566             pub fn wrapping_next_power_of_two(self) -> Self {
3567                 self.one_less_than_next_power_of_two().wrapping_add(1)
3568             }
3569         }
3570
3571         /// Return the memory representation of this integer as a byte array in
3572         /// big-endian (network) byte order.
3573         ///
3574         /// # Examples
3575         ///
3576         /// ```
3577         /// #![feature(int_to_from_bytes)]
3578         ///
3579         /// let bytes =  0x12_34_56_78_i32.to_be_bytes();
3580         /// assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78]);
3581         /// ```
3582         #[unstable(feature = "int_to_from_bytes", issue = "52963")]
3583         #[inline]
3584         pub fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] {
3585             self.to_be().to_ne_bytes()
3586         }
3587
3588         /// Return the memory representation of this integer as a byte array in
3589         /// little-endian byte order.
3590         ///
3591         /// # Examples
3592         ///
3593         /// ```
3594         /// #![feature(int_to_from_bytes)]
3595         ///
3596         /// let bytes =  0x12_34_56_78_i32.to_le_bytes();
3597         /// assert_eq!(bytes, [0x78, 0x56, 0x34, 0x12]);
3598         /// ```
3599         #[unstable(feature = "int_to_from_bytes", issue = "52963")]
3600         #[inline]
3601         pub fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] {
3602             self.to_le().to_ne_bytes()
3603         }
3604
3605         /// Return the memory representation of this integer as a byte array in
3606         /// native byte order.
3607         ///
3608         /// As the target platform's native endianness is used, portable code
3609         /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
3610         /// instead.
3611         ///
3612         /// [`to_be_bytes`]: #method.to_be_bytes
3613         /// [`to_le_bytes`]: #method.to_le_bytes
3614         ///
3615         /// # Examples
3616         ///
3617         /// ```
3618         /// #![feature(int_to_from_bytes)]
3619         ///
3620         /// let bytes = i32::min_value().to_be().to_ne_bytes();
3621         /// assert_eq!(bytes, [0x80, 0, 0, 0]);
3622         /// ```
3623         #[unstable(feature = "int_to_from_bytes", issue = "52963")]
3624         #[inline]
3625         pub fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] {
3626             unsafe { mem::transmute(self) }
3627         }
3628
3629         /// Create an integer value from its representation as a byte array in
3630         /// big endian.
3631         ///
3632         /// # Examples
3633         ///
3634         /// ```
3635         /// #![feature(int_to_from_bytes)]
3636         ///
3637         /// let int = i32::from_be_bytes([0x12, 0x34, 0x56, 0x78]);
3638         /// assert_eq!(int, 0x12_34_56_78);
3639         /// ```
3640         #[unstable(feature = "int_to_from_bytes", issue = "52963")]
3641         #[inline]
3642         pub fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3643             Self::from_be(Self::from_ne_bytes(bytes))
3644         }
3645
3646         /// Create an integer value from its representation as a byte array in
3647         /// little endian.
3648         ///
3649         /// # Examples
3650         ///
3651         /// ```
3652         /// #![feature(int_to_from_bytes)]
3653         ///
3654         /// let int = i32::from_le_bytes([0x12, 0x34, 0x56, 0x78]);
3655         /// assert_eq!(int, 0x78_56_34_12);
3656         /// ```
3657         #[unstable(feature = "int_to_from_bytes", issue = "52963")]
3658         #[inline]
3659         pub fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3660             Self::from_le(Self::from_ne_bytes(bytes))
3661         }
3662
3663         /// Create an integer value from its memory representation as a byte
3664         /// array in native endianness.
3665         ///
3666         /// As the target platform's native endianness is used, portable code
3667         /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
3668         /// appropriate instead.
3669         ///
3670         /// [`from_be_bytes`]: #method.from_be_bytes
3671         /// [`from_le_bytes`]: #method.from_le_bytes
3672         ///
3673         /// # Examples
3674         ///
3675         /// ```
3676         /// #![feature(int_to_from_bytes)]
3677         ///
3678         /// let int = i32::from_be(i32::from_ne_bytes([0x80, 0, 0, 0]));
3679         /// assert_eq!(int, i32::min_value());
3680         /// ```
3681         #[unstable(feature = "int_to_from_bytes", issue = "52963")]
3682         #[inline]
3683         pub fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self {
3684             unsafe { mem::transmute(bytes) }
3685         }
3686     }
3687 }
3688
3689 #[lang = "u8"]
3690 impl u8 {
3691     uint_impl! { u8, u8, 8, 255, "", "", 2, "0x82", "0xa", "0x12", "0x12", "0x48" }
3692
3693
3694     /// Checks if the value is within the ASCII range.
3695     ///
3696     /// # Examples
3697     ///
3698     /// ```
3699     /// let ascii = 97u8;
3700     /// let non_ascii = 150u8;
3701     ///
3702     /// assert!(ascii.is_ascii());
3703     /// assert!(!non_ascii.is_ascii());
3704     /// ```
3705     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3706     #[inline]
3707     pub fn is_ascii(&self) -> bool {
3708         *self & 128 == 0
3709     }
3710
3711     /// Makes a copy of the value in its ASCII upper case equivalent.
3712     ///
3713     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3714     /// but non-ASCII letters are unchanged.
3715     ///
3716     /// To uppercase the value in-place, use [`make_ascii_uppercase`].
3717     ///
3718     /// # Examples
3719     ///
3720     /// ```
3721     /// let lowercase_a = 97u8;
3722     ///
3723     /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
3724     /// ```
3725     ///
3726     /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
3727     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3728     #[inline]
3729     pub fn to_ascii_uppercase(&self) -> u8 {
3730         ASCII_UPPERCASE_MAP[*self as usize]
3731     }
3732
3733     /// Makes a copy of the value in its ASCII lower case equivalent.
3734     ///
3735     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3736     /// but non-ASCII letters are unchanged.
3737     ///
3738     /// To lowercase the value in-place, use [`make_ascii_lowercase`].
3739     ///
3740     /// # Examples
3741     ///
3742     /// ```
3743     /// let uppercase_a = 65u8;
3744     ///
3745     /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
3746     /// ```
3747     ///
3748     /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
3749     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3750     #[inline]
3751     pub fn to_ascii_lowercase(&self) -> u8 {
3752         ASCII_LOWERCASE_MAP[*self as usize]
3753     }
3754
3755     /// Checks that two values are an ASCII case-insensitive match.
3756     ///
3757     /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
3758     ///
3759     /// # Examples
3760     ///
3761     /// ```
3762     /// let lowercase_a = 97u8;
3763     /// let uppercase_a = 65u8;
3764     ///
3765     /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
3766     /// ```
3767     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3768     #[inline]
3769     pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
3770         self.to_ascii_lowercase() == other.to_ascii_lowercase()
3771     }
3772
3773     /// Converts this value to its ASCII upper case equivalent in-place.
3774     ///
3775     /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
3776     /// but non-ASCII letters are unchanged.
3777     ///
3778     /// To return a new uppercased value without modifying the existing one, use
3779     /// [`to_ascii_uppercase`].
3780     ///
3781     /// # Examples
3782     ///
3783     /// ```
3784     /// let mut byte = b'a';
3785     ///
3786     /// byte.make_ascii_uppercase();
3787     ///
3788     /// assert_eq!(b'A', byte);
3789     /// ```
3790     ///
3791     /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
3792     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3793     #[inline]
3794     pub fn make_ascii_uppercase(&mut self) {
3795         *self = self.to_ascii_uppercase();
3796     }
3797
3798     /// Converts this value to its ASCII lower case equivalent in-place.
3799     ///
3800     /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
3801     /// but non-ASCII letters are unchanged.
3802     ///
3803     /// To return a new lowercased value without modifying the existing one, use
3804     /// [`to_ascii_lowercase`].
3805     ///
3806     /// # Examples
3807     ///
3808     /// ```
3809     /// let mut byte = b'A';
3810     ///
3811     /// byte.make_ascii_lowercase();
3812     ///
3813     /// assert_eq!(b'a', byte);
3814     /// ```
3815     ///
3816     /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
3817     #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
3818     #[inline]
3819     pub fn make_ascii_lowercase(&mut self) {
3820         *self = self.to_ascii_lowercase();
3821     }
3822
3823     /// Checks if the value is an ASCII alphabetic character:
3824     ///
3825     /// - U+0041 'A' ... U+005A 'Z', or
3826     /// - U+0061 'a' ... U+007A 'z'.
3827     ///
3828     /// # Examples
3829     ///
3830     /// ```
3831     /// let uppercase_a = b'A';
3832     /// let uppercase_g = b'G';
3833     /// let a = b'a';
3834     /// let g = b'g';
3835     /// let zero = b'0';
3836     /// let percent = b'%';
3837     /// let space = b' ';
3838     /// let lf = b'\n';
3839     /// let esc = 0x1b_u8;
3840     ///
3841     /// assert!(uppercase_a.is_ascii_alphabetic());
3842     /// assert!(uppercase_g.is_ascii_alphabetic());
3843     /// assert!(a.is_ascii_alphabetic());
3844     /// assert!(g.is_ascii_alphabetic());
3845     /// assert!(!zero.is_ascii_alphabetic());
3846     /// assert!(!percent.is_ascii_alphabetic());
3847     /// assert!(!space.is_ascii_alphabetic());
3848     /// assert!(!lf.is_ascii_alphabetic());
3849     /// assert!(!esc.is_ascii_alphabetic());
3850     /// ```
3851     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3852     #[inline]
3853     pub fn is_ascii_alphabetic(&self) -> bool {
3854         if *self >= 0x80 { return false; }
3855         match ASCII_CHARACTER_CLASS[*self as usize] {
3856             L | Lx | U | Ux => true,
3857             _ => false
3858         }
3859     }
3860
3861     /// Checks if the value is an ASCII uppercase character:
3862     /// U+0041 'A' ... U+005A 'Z'.
3863     ///
3864     /// # Examples
3865     ///
3866     /// ```
3867     /// let uppercase_a = b'A';
3868     /// let uppercase_g = b'G';
3869     /// let a = b'a';
3870     /// let g = b'g';
3871     /// let zero = b'0';
3872     /// let percent = b'%';
3873     /// let space = b' ';
3874     /// let lf = b'\n';
3875     /// let esc = 0x1b_u8;
3876     ///
3877     /// assert!(uppercase_a.is_ascii_uppercase());
3878     /// assert!(uppercase_g.is_ascii_uppercase());
3879     /// assert!(!a.is_ascii_uppercase());
3880     /// assert!(!g.is_ascii_uppercase());
3881     /// assert!(!zero.is_ascii_uppercase());
3882     /// assert!(!percent.is_ascii_uppercase());
3883     /// assert!(!space.is_ascii_uppercase());
3884     /// assert!(!lf.is_ascii_uppercase());
3885     /// assert!(!esc.is_ascii_uppercase());
3886     /// ```
3887     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3888     #[inline]
3889     pub fn is_ascii_uppercase(&self) -> bool {
3890         if *self >= 0x80 { return false }
3891         match ASCII_CHARACTER_CLASS[*self as usize] {
3892             U | Ux => true,
3893             _ => false
3894         }
3895     }
3896
3897     /// Checks if the value is an ASCII lowercase character:
3898     /// U+0061 'a' ... U+007A 'z'.
3899     ///
3900     /// # Examples
3901     ///
3902     /// ```
3903     /// let uppercase_a = b'A';
3904     /// let uppercase_g = b'G';
3905     /// let a = b'a';
3906     /// let g = b'g';
3907     /// let zero = b'0';
3908     /// let percent = b'%';
3909     /// let space = b' ';
3910     /// let lf = b'\n';
3911     /// let esc = 0x1b_u8;
3912     ///
3913     /// assert!(!uppercase_a.is_ascii_lowercase());
3914     /// assert!(!uppercase_g.is_ascii_lowercase());
3915     /// assert!(a.is_ascii_lowercase());
3916     /// assert!(g.is_ascii_lowercase());
3917     /// assert!(!zero.is_ascii_lowercase());
3918     /// assert!(!percent.is_ascii_lowercase());
3919     /// assert!(!space.is_ascii_lowercase());
3920     /// assert!(!lf.is_ascii_lowercase());
3921     /// assert!(!esc.is_ascii_lowercase());
3922     /// ```
3923     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3924     #[inline]
3925     pub fn is_ascii_lowercase(&self) -> bool {
3926         if *self >= 0x80 { return false }
3927         match ASCII_CHARACTER_CLASS[*self as usize] {
3928             L | Lx => true,
3929             _ => false
3930         }
3931     }
3932
3933     /// Checks if the value is an ASCII alphanumeric character:
3934     ///
3935     /// - U+0041 'A' ... U+005A 'Z', or
3936     /// - U+0061 'a' ... U+007A 'z', or
3937     /// - U+0030 '0' ... U+0039 '9'.
3938     ///
3939     /// # Examples
3940     ///
3941     /// ```
3942     /// let uppercase_a = b'A';
3943     /// let uppercase_g = b'G';
3944     /// let a = b'a';
3945     /// let g = b'g';
3946     /// let zero = b'0';
3947     /// let percent = b'%';
3948     /// let space = b' ';
3949     /// let lf = b'\n';
3950     /// let esc = 0x1b_u8;
3951     ///
3952     /// assert!(uppercase_a.is_ascii_alphanumeric());
3953     /// assert!(uppercase_g.is_ascii_alphanumeric());
3954     /// assert!(a.is_ascii_alphanumeric());
3955     /// assert!(g.is_ascii_alphanumeric());
3956     /// assert!(zero.is_ascii_alphanumeric());
3957     /// assert!(!percent.is_ascii_alphanumeric());
3958     /// assert!(!space.is_ascii_alphanumeric());
3959     /// assert!(!lf.is_ascii_alphanumeric());
3960     /// assert!(!esc.is_ascii_alphanumeric());
3961     /// ```
3962     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3963     #[inline]
3964     pub fn is_ascii_alphanumeric(&self) -> bool {
3965         if *self >= 0x80 { return false }
3966         match ASCII_CHARACTER_CLASS[*self as usize] {
3967             D | L | Lx | U | Ux => true,
3968             _ => false
3969         }
3970     }
3971
3972     /// Checks if the value is an ASCII decimal digit:
3973     /// U+0030 '0' ... U+0039 '9'.
3974     ///
3975     /// # Examples
3976     ///
3977     /// ```
3978     /// let uppercase_a = b'A';
3979     /// let uppercase_g = b'G';
3980     /// let a = b'a';
3981     /// let g = b'g';
3982     /// let zero = b'0';
3983     /// let percent = b'%';
3984     /// let space = b' ';
3985     /// let lf = b'\n';
3986     /// let esc = 0x1b_u8;
3987     ///
3988     /// assert!(!uppercase_a.is_ascii_digit());
3989     /// assert!(!uppercase_g.is_ascii_digit());
3990     /// assert!(!a.is_ascii_digit());
3991     /// assert!(!g.is_ascii_digit());
3992     /// assert!(zero.is_ascii_digit());
3993     /// assert!(!percent.is_ascii_digit());
3994     /// assert!(!space.is_ascii_digit());
3995     /// assert!(!lf.is_ascii_digit());
3996     /// assert!(!esc.is_ascii_digit());
3997     /// ```
3998     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
3999     #[inline]
4000     pub fn is_ascii_digit(&self) -> bool {
4001         if *self >= 0x80 { return false }
4002         match ASCII_CHARACTER_CLASS[*self as usize] {
4003             D => true,
4004             _ => false
4005         }
4006     }
4007
4008     /// Checks if the value is an ASCII hexadecimal digit:
4009     ///
4010     /// - U+0030 '0' ... U+0039 '9', or
4011     /// - U+0041 'A' ... U+0046 'F', or
4012     /// - U+0061 'a' ... U+0066 'f'.
4013     ///
4014     /// # Examples
4015     ///
4016     /// ```
4017     /// let uppercase_a = b'A';
4018     /// let uppercase_g = b'G';
4019     /// let a = b'a';
4020     /// let g = b'g';
4021     /// let zero = b'0';
4022     /// let percent = b'%';
4023     /// let space = b' ';
4024     /// let lf = b'\n';
4025     /// let esc = 0x1b_u8;
4026     ///
4027     /// assert!(uppercase_a.is_ascii_hexdigit());
4028     /// assert!(!uppercase_g.is_ascii_hexdigit());
4029     /// assert!(a.is_ascii_hexdigit());
4030     /// assert!(!g.is_ascii_hexdigit());
4031     /// assert!(zero.is_ascii_hexdigit());
4032     /// assert!(!percent.is_ascii_hexdigit());
4033     /// assert!(!space.is_ascii_hexdigit());
4034     /// assert!(!lf.is_ascii_hexdigit());
4035     /// assert!(!esc.is_ascii_hexdigit());
4036     /// ```
4037     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4038     #[inline]
4039     pub fn is_ascii_hexdigit(&self) -> bool {
4040         if *self >= 0x80 { return false }
4041         match ASCII_CHARACTER_CLASS[*self as usize] {
4042             D | Lx | Ux => true,
4043             _ => false
4044         }
4045     }
4046
4047     /// Checks if the value is an ASCII punctuation character:
4048     ///
4049     /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
4050     /// - U+003A ... U+0040 `: ; < = > ? @`, or
4051     /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
4052     /// - U+007B ... U+007E `{ | } ~`
4053     ///
4054     /// # Examples
4055     ///
4056     /// ```
4057     /// let uppercase_a = b'A';
4058     /// let uppercase_g = b'G';
4059     /// let a = b'a';
4060     /// let g = b'g';
4061     /// let zero = b'0';
4062     /// let percent = b'%';
4063     /// let space = b' ';
4064     /// let lf = b'\n';
4065     /// let esc = 0x1b_u8;
4066     ///
4067     /// assert!(!uppercase_a.is_ascii_punctuation());
4068     /// assert!(!uppercase_g.is_ascii_punctuation());
4069     /// assert!(!a.is_ascii_punctuation());
4070     /// assert!(!g.is_ascii_punctuation());
4071     /// assert!(!zero.is_ascii_punctuation());
4072     /// assert!(percent.is_ascii_punctuation());
4073     /// assert!(!space.is_ascii_punctuation());
4074     /// assert!(!lf.is_ascii_punctuation());
4075     /// assert!(!esc.is_ascii_punctuation());
4076     /// ```
4077     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4078     #[inline]
4079     pub fn is_ascii_punctuation(&self) -> bool {
4080         if *self >= 0x80 { return false }
4081         match ASCII_CHARACTER_CLASS[*self as usize] {
4082             P => true,
4083             _ => false
4084         }
4085     }
4086
4087     /// Checks if the value is an ASCII graphic character:
4088     /// U+0021 '!' ... U+007E '~'.
4089     ///
4090     /// # Examples
4091     ///
4092     /// ```
4093     /// let uppercase_a = b'A';
4094     /// let uppercase_g = b'G';
4095     /// let a = b'a';
4096     /// let g = b'g';
4097     /// let zero = b'0';
4098     /// let percent = b'%';
4099     /// let space = b' ';
4100     /// let lf = b'\n';
4101     /// let esc = 0x1b_u8;
4102     ///
4103     /// assert!(uppercase_a.is_ascii_graphic());
4104     /// assert!(uppercase_g.is_ascii_graphic());
4105     /// assert!(a.is_ascii_graphic());
4106     /// assert!(g.is_ascii_graphic());
4107     /// assert!(zero.is_ascii_graphic());
4108     /// assert!(percent.is_ascii_graphic());
4109     /// assert!(!space.is_ascii_graphic());
4110     /// assert!(!lf.is_ascii_graphic());
4111     /// assert!(!esc.is_ascii_graphic());
4112     /// ```
4113     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4114     #[inline]
4115     pub fn is_ascii_graphic(&self) -> bool {
4116         if *self >= 0x80 { return false; }
4117         match ASCII_CHARACTER_CLASS[*self as usize] {
4118             Ux | U | Lx | L | D | P => true,
4119             _ => false
4120         }
4121     }
4122
4123     /// Checks if the value is an ASCII whitespace character:
4124     /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
4125     /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
4126     ///
4127     /// Rust uses the WhatWG Infra Standard's [definition of ASCII
4128     /// whitespace][infra-aw]. There are several other definitions in
4129     /// wide use. For instance, [the POSIX locale][pct] includes
4130     /// U+000B VERTICAL TAB as well as all the above characters,
4131     /// but—from the very same specification—[the default rule for
4132     /// "field splitting" in the Bourne shell][bfs] considers *only*
4133     /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
4134     ///
4135     /// If you are writing a program that will process an existing
4136     /// file format, check what that format's definition of whitespace is
4137     /// before using this function.
4138     ///
4139     /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
4140     /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
4141     /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
4142     ///
4143     /// # Examples
4144     ///
4145     /// ```
4146     /// let uppercase_a = b'A';
4147     /// let uppercase_g = b'G';
4148     /// let a = b'a';
4149     /// let g = b'g';
4150     /// let zero = b'0';
4151     /// let percent = b'%';
4152     /// let space = b' ';
4153     /// let lf = b'\n';
4154     /// let esc = 0x1b_u8;
4155     ///
4156     /// assert!(!uppercase_a.is_ascii_whitespace());
4157     /// assert!(!uppercase_g.is_ascii_whitespace());
4158     /// assert!(!a.is_ascii_whitespace());
4159     /// assert!(!g.is_ascii_whitespace());
4160     /// assert!(!zero.is_ascii_whitespace());
4161     /// assert!(!percent.is_ascii_whitespace());
4162     /// assert!(space.is_ascii_whitespace());
4163     /// assert!(lf.is_ascii_whitespace());
4164     /// assert!(!esc.is_ascii_whitespace());
4165     /// ```
4166     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4167     #[inline]
4168     pub fn is_ascii_whitespace(&self) -> bool {
4169         if *self >= 0x80 { return false; }
4170         match ASCII_CHARACTER_CLASS[*self as usize] {
4171             Cw | W => true,
4172             _ => false
4173         }
4174     }
4175
4176     /// Checks if the value is an ASCII control character:
4177     /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
4178     /// Note that most ASCII whitespace characters are control
4179     /// characters, but SPACE is not.
4180     ///
4181     /// # Examples
4182     ///
4183     /// ```
4184     /// let uppercase_a = b'A';
4185     /// let uppercase_g = b'G';
4186     /// let a = b'a';
4187     /// let g = b'g';
4188     /// let zero = b'0';
4189     /// let percent = b'%';
4190     /// let space = b' ';
4191     /// let lf = b'\n';
4192     /// let esc = 0x1b_u8;
4193     ///
4194     /// assert!(!uppercase_a.is_ascii_control());
4195     /// assert!(!uppercase_g.is_ascii_control());
4196     /// assert!(!a.is_ascii_control());
4197     /// assert!(!g.is_ascii_control());
4198     /// assert!(!zero.is_ascii_control());
4199     /// assert!(!percent.is_ascii_control());
4200     /// assert!(!space.is_ascii_control());
4201     /// assert!(lf.is_ascii_control());
4202     /// assert!(esc.is_ascii_control());
4203     /// ```
4204     #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
4205     #[inline]
4206     pub fn is_ascii_control(&self) -> bool {
4207         if *self >= 0x80 { return false; }
4208         match ASCII_CHARACTER_CLASS[*self as usize] {
4209             C | Cw => true,
4210             _ => false
4211         }
4212     }
4213 }
4214
4215 #[lang = "u16"]
4216 impl u16 {
4217     uint_impl! { u16, u16, 16, 65535, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48" }
4218 }
4219
4220 #[lang = "u32"]
4221 impl u32 {
4222     uint_impl! { u32, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4223         "0x78563412", "0x1e6a2c48" }
4224 }
4225
4226 #[lang = "u64"]
4227 impl u64 {
4228     uint_impl! { u64, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4229         "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48" }
4230 }
4231
4232 #[lang = "u128"]
4233 impl u128 {
4234     uint_impl! { u128, u128, 128, 340282366920938463463374607431768211455, "", "", 16,
4235         "0x13f40000000000000000000000004f76", "0x4f7613f4", "0x12345678901234567890123456789012",
4236         "0x12907856341290785634129078563412", "0x48091e6a2c48091e6a2c48091e6a2c48" }
4237 }
4238
4239 #[cfg(target_pointer_width = "16")]
4240 #[lang = "usize"]
4241 impl usize {
4242     uint_impl! { usize, u16, 16, 65536, "", "", 4, "0xa003", "0x3a", "0x1234", "0x3412", "0x2c48" }
4243 }
4244 #[cfg(target_pointer_width = "32")]
4245 #[lang = "usize"]
4246 impl usize {
4247     uint_impl! { usize, u32, 32, 4294967295, "", "", 8, "0x10000b3", "0xb301", "0x12345678",
4248         "0x78563412", "0x1e6a2c48" }
4249 }
4250
4251 #[cfg(target_pointer_width = "64")]
4252 #[lang = "usize"]
4253 impl usize {
4254     uint_impl! { usize, u64, 64, 18446744073709551615, "", "", 12, "0xaa00000000006e1", "0x6e10aa",
4255         "0x1234567890123456", "0x5634129078563412", "0x6a2c48091e6a2c48" }
4256 }
4257
4258 /// A classification of floating point numbers.
4259 ///
4260 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
4261 /// their documentation for more.
4262 ///
4263 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
4264 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
4265 ///
4266 /// # Examples
4267 ///
4268 /// ```
4269 /// use std::num::FpCategory;
4270 /// use std::f32;
4271 ///
4272 /// let num = 12.4_f32;
4273 /// let inf = f32::INFINITY;
4274 /// let zero = 0f32;
4275 /// let sub: f32 = 1.1754942e-38;
4276 /// let nan = f32::NAN;
4277 ///
4278 /// assert_eq!(num.classify(), FpCategory::Normal);
4279 /// assert_eq!(inf.classify(), FpCategory::Infinite);
4280 /// assert_eq!(zero.classify(), FpCategory::Zero);
4281 /// assert_eq!(nan.classify(), FpCategory::Nan);
4282 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
4283 /// ```
4284 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
4285 #[stable(feature = "rust1", since = "1.0.0")]
4286 pub enum FpCategory {
4287     /// "Not a Number", often obtained by dividing by zero.
4288     #[stable(feature = "rust1", since = "1.0.0")]
4289     Nan,
4290
4291     /// Positive or negative infinity.
4292     #[stable(feature = "rust1", since = "1.0.0")]
4293     Infinite,
4294
4295     /// Positive or negative zero.
4296     #[stable(feature = "rust1", since = "1.0.0")]
4297     Zero,
4298
4299     /// De-normalized floating point representation (less precise than `Normal`).
4300     #[stable(feature = "rust1", since = "1.0.0")]
4301     Subnormal,
4302
4303     /// A regular floating point number.
4304     #[stable(feature = "rust1", since = "1.0.0")]
4305     Normal,
4306 }
4307
4308 macro_rules! from_str_radix_int_impl {
4309     ($($t:ty)*) => {$(
4310         #[stable(feature = "rust1", since = "1.0.0")]
4311         impl FromStr for $t {
4312             type Err = ParseIntError;
4313             fn from_str(src: &str) -> Result<Self, ParseIntError> {
4314                 from_str_radix(src, 10)
4315             }
4316         }
4317     )*}
4318 }
4319 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
4320
4321 /// The error type returned when a checked integral type conversion fails.
4322 #[unstable(feature = "try_from", issue = "33417")]
4323 #[derive(Debug, Copy, Clone)]
4324 pub struct TryFromIntError(());
4325
4326 impl TryFromIntError {
4327     #[unstable(feature = "int_error_internals",
4328                reason = "available through Error trait and this method should \
4329                          not be exposed publicly",
4330                issue = "0")]
4331     #[doc(hidden)]
4332     pub fn __description(&self) -> &str {
4333         "out of range integral type conversion attempted"
4334     }
4335 }
4336
4337 #[unstable(feature = "try_from", issue = "33417")]
4338 impl fmt::Display for TryFromIntError {
4339     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
4340         self.__description().fmt(fmt)
4341     }
4342 }
4343
4344 #[unstable(feature = "try_from", issue = "33417")]
4345 impl From<!> for TryFromIntError {
4346     fn from(never: !) -> TryFromIntError {
4347         never
4348     }
4349 }
4350
4351 // no possible bounds violation
4352 macro_rules! try_from_unbounded {
4353     ($source:ty, $($target:ty),*) => {$(
4354         #[unstable(feature = "try_from", issue = "33417")]
4355         impl TryFrom<$source> for $target {
4356             type Error = TryFromIntError;
4357
4358             #[inline]
4359             fn try_from(value: $source) -> Result<Self, Self::Error> {
4360                 Ok(value as $target)
4361             }
4362         }
4363     )*}
4364 }
4365
4366 // only negative bounds
4367 macro_rules! try_from_lower_bounded {
4368     ($source:ty, $($target:ty),*) => {$(
4369         #[unstable(feature = "try_from", issue = "33417")]
4370         impl TryFrom<$source> for $target {
4371             type Error = TryFromIntError;
4372
4373             #[inline]
4374             fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4375                 if u >= 0 {
4376                     Ok(u as $target)
4377                 } else {
4378                     Err(TryFromIntError(()))
4379                 }
4380             }
4381         }
4382     )*}
4383 }
4384
4385 // unsigned to signed (only positive bound)
4386 macro_rules! try_from_upper_bounded {
4387     ($source:ty, $($target:ty),*) => {$(
4388         #[unstable(feature = "try_from", issue = "33417")]
4389         impl TryFrom<$source> for $target {
4390             type Error = TryFromIntError;
4391
4392             #[inline]
4393             fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4394                 if u > (<$target>::max_value() as $source) {
4395                     Err(TryFromIntError(()))
4396                 } else {
4397                     Ok(u as $target)
4398                 }
4399             }
4400         }
4401     )*}
4402 }
4403
4404 // all other cases
4405 macro_rules! try_from_both_bounded {
4406     ($source:ty, $($target:ty),*) => {$(
4407         #[unstable(feature = "try_from", issue = "33417")]
4408         impl TryFrom<$source> for $target {
4409             type Error = TryFromIntError;
4410
4411             #[inline]
4412             fn try_from(u: $source) -> Result<$target, TryFromIntError> {
4413                 let min = <$target>::min_value() as $source;
4414                 let max = <$target>::max_value() as $source;
4415                 if u < min || u > max {
4416                     Err(TryFromIntError(()))
4417                 } else {
4418                     Ok(u as $target)
4419                 }
4420             }
4421         }
4422     )*}
4423 }
4424
4425 macro_rules! rev {
4426     ($mac:ident, $source:ty, $($target:ty),*) => {$(
4427         $mac!($target, $source);
4428     )*}
4429 }
4430
4431 /// intra-sign conversions
4432 try_from_upper_bounded!(u16, u8);
4433 try_from_upper_bounded!(u32, u16, u8);
4434 try_from_upper_bounded!(u64, u32, u16, u8);
4435 try_from_upper_bounded!(u128, u64, u32, u16, u8);
4436
4437 try_from_both_bounded!(i16, i8);
4438 try_from_both_bounded!(i32, i16, i8);
4439 try_from_both_bounded!(i64, i32, i16, i8);
4440 try_from_both_bounded!(i128, i64, i32, i16, i8);
4441
4442 // unsigned-to-signed
4443 try_from_upper_bounded!(u8, i8);
4444 try_from_upper_bounded!(u16, i8, i16);
4445 try_from_upper_bounded!(u32, i8, i16, i32);
4446 try_from_upper_bounded!(u64, i8, i16, i32, i64);
4447 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
4448
4449 // signed-to-unsigned
4450 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
4451 try_from_lower_bounded!(i16, u16, u32, u64, u128);
4452 try_from_lower_bounded!(i32, u32, u64, u128);
4453 try_from_lower_bounded!(i64, u64, u128);
4454 try_from_lower_bounded!(i128, u128);
4455 try_from_both_bounded!(i16, u8);
4456 try_from_both_bounded!(i32, u16, u8);
4457 try_from_both_bounded!(i64, u32, u16, u8);
4458 try_from_both_bounded!(i128, u64, u32, u16, u8);
4459
4460 // usize/isize
4461 try_from_upper_bounded!(usize, isize);
4462 try_from_lower_bounded!(isize, usize);
4463
4464 #[cfg(target_pointer_width = "16")]
4465 mod ptr_try_from_impls {
4466     use super::TryFromIntError;
4467     use convert::TryFrom;
4468
4469     try_from_upper_bounded!(usize, u8);
4470     try_from_unbounded!(usize, u16, u32, u64, u128);
4471     try_from_upper_bounded!(usize, i8, i16);
4472     try_from_unbounded!(usize, i32, i64, i128);
4473
4474     try_from_both_bounded!(isize, u8);
4475     try_from_lower_bounded!(isize, u16, u32, u64, u128);
4476     try_from_both_bounded!(isize, i8);
4477     try_from_unbounded!(isize, i16, i32, i64, i128);
4478
4479     rev!(try_from_upper_bounded, usize, u32, u64, u128);
4480     rev!(try_from_lower_bounded, usize, i8, i16);
4481     rev!(try_from_both_bounded, usize, i32, i64, i128);
4482
4483     rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
4484     rev!(try_from_both_bounded, isize, i32, i64, i128);
4485 }
4486
4487 #[cfg(target_pointer_width = "32")]
4488 mod ptr_try_from_impls {
4489     use super::TryFromIntError;
4490     use convert::TryFrom;
4491
4492     try_from_upper_bounded!(usize, u8, u16);
4493     try_from_unbounded!(usize, u32, u64, u128);
4494     try_from_upper_bounded!(usize, i8, i16, i32);
4495     try_from_unbounded!(usize, i64, i128);
4496
4497     try_from_both_bounded!(isize, u8, u16);
4498     try_from_lower_bounded!(isize, u32, u64, u128);
4499     try_from_both_bounded!(isize, i8, i16);
4500     try_from_unbounded!(isize, i32, i64, i128);
4501
4502     rev!(try_from_unbounded, usize, u32);
4503     rev!(try_from_upper_bounded, usize, u64, u128);
4504     rev!(try_from_lower_bounded, usize, i8, i16, i32);
4505     rev!(try_from_both_bounded, usize, i64, i128);
4506
4507     rev!(try_from_unbounded, isize, u16);
4508     rev!(try_from_upper_bounded, isize, u32, u64, u128);
4509     rev!(try_from_unbounded, isize, i32);
4510     rev!(try_from_both_bounded, isize, i64, i128);
4511 }
4512
4513 #[cfg(target_pointer_width = "64")]
4514 mod ptr_try_from_impls {
4515     use super::TryFromIntError;
4516     use convert::TryFrom;
4517
4518     try_from_upper_bounded!(usize, u8, u16, u32);
4519     try_from_unbounded!(usize, u64, u128);
4520     try_from_upper_bounded!(usize, i8, i16, i32, i64);
4521     try_from_unbounded!(usize, i128);
4522
4523     try_from_both_bounded!(isize, u8, u16, u32);
4524     try_from_lower_bounded!(isize, u64, u128);
4525     try_from_both_bounded!(isize, i8, i16, i32);
4526     try_from_unbounded!(isize, i64, i128);
4527
4528     rev!(try_from_unbounded, usize, u32, u64);
4529     rev!(try_from_upper_bounded, usize, u128);
4530     rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
4531     rev!(try_from_both_bounded, usize, i128);
4532
4533     rev!(try_from_unbounded, isize, u16, u32);
4534     rev!(try_from_upper_bounded, isize, u64, u128);
4535     rev!(try_from_unbounded, isize, i32, i64);
4536     rev!(try_from_both_bounded, isize, i128);
4537 }
4538
4539 #[doc(hidden)]
4540 trait FromStrRadixHelper: PartialOrd + Copy {
4541     fn min_value() -> Self;
4542     fn max_value() -> Self;
4543     fn from_u32(u: u32) -> Self;
4544     fn checked_mul(&self, other: u32) -> Option<Self>;
4545     fn checked_sub(&self, other: u32) -> Option<Self>;
4546     fn checked_add(&self, other: u32) -> Option<Self>;
4547 }
4548
4549 macro_rules! doit {
4550     ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
4551         #[inline]
4552         fn min_value() -> Self { Self::min_value() }
4553         #[inline]
4554         fn max_value() -> Self { Self::max_value() }
4555         #[inline]
4556         fn from_u32(u: u32) -> Self { u as Self }
4557         #[inline]
4558         fn checked_mul(&self, other: u32) -> Option<Self> {
4559             Self::checked_mul(*self, other as Self)
4560         }
4561         #[inline]
4562         fn checked_sub(&self, other: u32) -> Option<Self> {
4563             Self::checked_sub(*self, other as Self)
4564         }
4565         #[inline]
4566         fn checked_add(&self, other: u32) -> Option<Self> {
4567             Self::checked_add(*self, other as Self)
4568         }
4569     })*)
4570 }
4571 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
4572
4573 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
4574     use self::IntErrorKind::*;
4575     use self::ParseIntError as PIE;
4576
4577     assert!(radix >= 2 && radix <= 36,
4578            "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
4579            radix);
4580
4581     if src.is_empty() {
4582         return Err(PIE { kind: Empty });
4583     }
4584
4585     let is_signed_ty = T::from_u32(0) > T::min_value();
4586
4587     // all valid digits are ascii, so we will just iterate over the utf8 bytes
4588     // and cast them to chars. .to_digit() will safely return None for anything
4589     // other than a valid ascii digit for the given radix, including the first-byte
4590     // of multi-byte sequences
4591     let src = src.as_bytes();
4592
4593     let (is_positive, digits) = match src[0] {
4594         b'+' => (true, &src[1..]),
4595         b'-' if is_signed_ty => (false, &src[1..]),
4596         _ => (true, src),
4597     };
4598
4599     if digits.is_empty() {
4600         return Err(PIE { kind: Empty });
4601     }
4602
4603     let mut result = T::from_u32(0);
4604     if is_positive {
4605         // The number is positive
4606         for &c in digits {
4607             let x = match (c as char).to_digit(radix) {
4608                 Some(x) => x,
4609                 None => return Err(PIE { kind: InvalidDigit }),
4610             };
4611             result = match result.checked_mul(radix) {
4612                 Some(result) => result,
4613                 None => return Err(PIE { kind: Overflow }),
4614             };
4615             result = match result.checked_add(x) {
4616                 Some(result) => result,
4617                 None => return Err(PIE { kind: Overflow }),
4618             };
4619         }
4620     } else {
4621         // The number is negative
4622         for &c in digits {
4623             let x = match (c as char).to_digit(radix) {
4624                 Some(x) => x,
4625                 None => return Err(PIE { kind: InvalidDigit }),
4626             };
4627             result = match result.checked_mul(radix) {
4628                 Some(result) => result,
4629                 None => return Err(PIE { kind: Underflow }),
4630             };
4631             result = match result.checked_sub(x) {
4632                 Some(result) => result,
4633                 None => return Err(PIE { kind: Underflow }),
4634             };
4635         }
4636     }
4637     Ok(result)
4638 }
4639
4640 /// An error which can be returned when parsing an integer.
4641 ///
4642 /// This error is used as the error type for the `from_str_radix()` functions
4643 /// on the primitive integer types, such as [`i8::from_str_radix`].
4644 ///
4645 /// # Potential causes
4646 ///
4647 /// Among other causes, `ParseIntError` can be thrown because of leading or trailing whitespace
4648 /// in the string e.g. when it is obtained from the standard input.
4649 /// Using the [`str.trim()`] method ensures that no whitespace remains before parsing.
4650 ///
4651 /// [`str.trim()`]: ../../std/primitive.str.html#method.trim
4652 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
4653 #[derive(Debug, Clone, PartialEq, Eq)]
4654 #[stable(feature = "rust1", since = "1.0.0")]
4655 pub struct ParseIntError {
4656     kind: IntErrorKind,
4657 }
4658
4659 #[derive(Debug, Clone, PartialEq, Eq)]
4660 enum IntErrorKind {
4661     Empty,
4662     InvalidDigit,
4663     Overflow,
4664     Underflow,
4665 }
4666
4667 impl ParseIntError {
4668     #[unstable(feature = "int_error_internals",
4669                reason = "available through Error trait and this method should \
4670                          not be exposed publicly",
4671                issue = "0")]
4672     #[doc(hidden)]
4673     pub fn __description(&self) -> &str {
4674         match self.kind {
4675             IntErrorKind::Empty => "cannot parse integer from empty string",
4676             IntErrorKind::InvalidDigit => "invalid digit found in string",
4677             IntErrorKind::Overflow => "number too large to fit in target type",
4678             IntErrorKind::Underflow => "number too small to fit in target type",
4679         }
4680     }
4681 }
4682
4683 #[stable(feature = "rust1", since = "1.0.0")]
4684 impl fmt::Display for ParseIntError {
4685     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
4686         self.__description().fmt(f)
4687     }
4688 }
4689
4690 #[stable(feature = "rust1", since = "1.0.0")]
4691 pub use num::dec2flt::ParseFloatError;
4692
4693 // Conversion traits for primitive integer and float types
4694 // Conversions T -> T are covered by a blanket impl and therefore excluded
4695 // Some conversions from and to usize/isize are not implemented due to portability concerns
4696 macro_rules! impl_from {
4697     ($Small: ty, $Large: ty, #[$attr:meta], $doc: expr) => {
4698         #[$attr]
4699         #[doc = $doc]
4700         impl From<$Small> for $Large {
4701             #[inline]
4702             fn from(small: $Small) -> $Large {
4703                 small as $Large
4704             }
4705         }
4706     };
4707     ($Small: ty, $Large: ty, #[$attr:meta]) => {
4708         impl_from!($Small,
4709                    $Large,
4710                    #[$attr],
4711                    concat!("Converts `",
4712                            stringify!($Small),
4713                            "` to `",
4714                            stringify!($Large),
4715                            "` losslessly."));
4716     }
4717 }
4718
4719 macro_rules! impl_from_bool {
4720     ($target: ty, #[$attr:meta]) => {
4721         impl_from!(bool, $target, #[$attr], concat!("Converts a `bool` to a `",
4722             stringify!($target), "`. The resulting value is `0` for `false` and `1` for `true`
4723 values.
4724
4725 # Examples
4726
4727 ```
4728 assert_eq!(", stringify!($target), "::from(true), 1);
4729 assert_eq!(", stringify!($target), "::from(false), 0);
4730 ```"));
4731     };
4732 }
4733
4734 // Bool -> Any
4735 impl_from_bool! { u8, #[stable(feature = "from_bool", since = "1.28.0")] }
4736 impl_from_bool! { u16, #[stable(feature = "from_bool", since = "1.28.0")] }
4737 impl_from_bool! { u32, #[stable(feature = "from_bool", since = "1.28.0")] }
4738 impl_from_bool! { u64, #[stable(feature = "from_bool", since = "1.28.0")] }
4739 impl_from_bool! { u128, #[stable(feature = "from_bool", since = "1.28.0")] }
4740 impl_from_bool! { usize, #[stable(feature = "from_bool", since = "1.28.0")] }
4741 impl_from_bool! { i8, #[stable(feature = "from_bool", since = "1.28.0")] }
4742 impl_from_bool! { i16, #[stable(feature = "from_bool", since = "1.28.0")] }
4743 impl_from_bool! { i32, #[stable(feature = "from_bool", since = "1.28.0")] }
4744 impl_from_bool! { i64, #[stable(feature = "from_bool", since = "1.28.0")] }
4745 impl_from_bool! { i128, #[stable(feature = "from_bool", since = "1.28.0")] }
4746 impl_from_bool! { isize, #[stable(feature = "from_bool", since = "1.28.0")] }
4747
4748 // Unsigned -> Unsigned
4749 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4750 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4751 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4752 impl_from! { u8, u128, #[stable(feature = "i128", since = "1.26.0")] }
4753 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4754 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4755 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4756 impl_from! { u16, u128, #[stable(feature = "i128", since = "1.26.0")] }
4757 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4758 impl_from! { u32, u128, #[stable(feature = "i128", since = "1.26.0")] }
4759 impl_from! { u64, u128, #[stable(feature = "i128", since = "1.26.0")] }
4760
4761 // Signed -> Signed
4762 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4763 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4764 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4765 impl_from! { i8, i128, #[stable(feature = "i128", since = "1.26.0")] }
4766 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4767 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4768 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4769 impl_from! { i16, i128, #[stable(feature = "i128", since = "1.26.0")] }
4770 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4771 impl_from! { i32, i128, #[stable(feature = "i128", since = "1.26.0")] }
4772 impl_from! { i64, i128, #[stable(feature = "i128", since = "1.26.0")] }
4773
4774 // Unsigned -> Signed
4775 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4776 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4777 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4778 impl_from! { u8, i128, #[stable(feature = "i128", since = "1.26.0")] }
4779 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4780 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4781 impl_from! { u16, i128, #[stable(feature = "i128", since = "1.26.0")] }
4782 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
4783 impl_from! { u32, i128, #[stable(feature = "i128", since = "1.26.0")] }
4784 impl_from! { u64, i128, #[stable(feature = "i128", since = "1.26.0")] }
4785
4786 // The C99 standard defines bounds on INTPTR_MIN, INTPTR_MAX, and UINTPTR_MAX
4787 // which imply that pointer-sized integers must be at least 16 bits:
4788 // https://port70.net/~nsz/c/c99/n1256.html#7.18.2.4
4789 impl_from! { u16, usize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
4790 impl_from! { u8, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
4791 impl_from! { i16, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] }
4792
4793 // RISC-V defines the possibility of a 128-bit address space (RV128).
4794
4795 // CHERI proposes 256-bit “capabilities”. Unclear if this would be relevant to usize/isize.
4796 // https://www.cl.cam.ac.uk/research/security/ctsrd/pdfs/20171017a-cheri-poster.pdf
4797 // http://www.csl.sri.com/users/neumann/2012resolve-cheri.pdf
4798
4799
4800 // Note: integers can only be represented with full precision in a float if
4801 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
4802 // Lossy float conversions are not implemented at this time.
4803
4804 // Signed -> Float
4805 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4806 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4807 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4808 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4809 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4810
4811 // Unsigned -> Float
4812 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4813 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4814 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4815 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4816 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4817
4818 // Float -> Float
4819 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
4820
4821 static ASCII_LOWERCASE_MAP: [u8; 256] = [
4822     0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4823     0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4824     0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4825     0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4826     b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4827     b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4828     b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4829     b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4830     b'@',
4831
4832           b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4833     b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4834     b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4835     b'x', b'y', b'z',
4836
4837                       b'[', b'\\', b']', b'^', b'_',
4838     b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g',
4839     b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
4840     b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
4841     b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f,
4842     0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4843     0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4844     0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4845     0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4846     0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4847     0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4848     0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4849     0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4850     0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4851     0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4852     0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4853     0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4854     0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4855     0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4856     0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4857     0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4858 ];
4859
4860 static ASCII_UPPERCASE_MAP: [u8; 256] = [
4861     0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
4862     0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
4863     0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
4864     0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
4865     b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
4866     b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
4867     b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
4868     b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
4869     b'@', b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4870     b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4871     b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4872     b'X', b'Y', b'Z', b'[', b'\\', b']', b'^', b'_',
4873     b'`',
4874
4875           b'A', b'B', b'C', b'D', b'E', b'F', b'G',
4876     b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
4877     b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
4878     b'X', b'Y', b'Z',
4879
4880                       b'{', b'|', b'}', b'~', 0x7f,
4881     0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
4882     0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
4883     0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
4884     0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
4885     0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
4886     0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
4887     0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
4888     0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
4889     0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
4890     0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
4891     0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
4892     0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
4893     0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
4894     0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
4895     0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
4896     0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
4897 ];
4898
4899 enum AsciiCharacterClass {
4900     C,  // control
4901     Cw, // control whitespace
4902     W,  // whitespace
4903     D,  // digit
4904     L,  // lowercase
4905     Lx, // lowercase hex digit
4906     U,  // uppercase
4907     Ux, // uppercase hex digit
4908     P,  // punctuation
4909 }
4910 use self::AsciiCharacterClass::*;
4911
4912 static ASCII_CHARACTER_CLASS: [AsciiCharacterClass; 128] = [
4913 //  _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f
4914     C, C, C, C, C, C, C, C, C, Cw,Cw,C, Cw,Cw,C, C, // 0_
4915     C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, // 1_
4916     W, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, // 2_
4917     D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, P, // 3_
4918     P, Ux,Ux,Ux,Ux,Ux,Ux,U, U, U, U, U, U, U, U, U, // 4_
4919     U, U, U, U, U, U, U, U, U, U, U, P, P, P, P, P, // 5_
4920     P, Lx,Lx,Lx,Lx,Lx,Lx,L, L, L, L, L, L, L, L, L, // 6_
4921     L, L, L, L, L, L, L, L, L, L, L, P, P, P, P, C, // 7_
4922 ];