]> git.proxmox.com Git - rustc.git/blob - src/libcore/num/mod.rs
New upstream version 1.12.0+dfsg1
[rustc.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 char::CharExt;
16 use cmp::PartialOrd;
17 use convert::{From, TryFrom};
18 use fmt;
19 use intrinsics;
20 use marker::{Copy, Sized};
21 use mem::size_of;
22 use option::Option::{self, Some, None};
23 use result::Result::{self, Ok, Err};
24 use str::{FromStr, StrExt};
25 use slice::SliceExt;
26
27 /// Provides intentionally-wrapped arithmetic on `T`.
28 ///
29 /// Operations like `+` on `u32` values is intended to never overflow,
30 /// and in some debug configurations overflow is detected and results
31 /// in a panic. While most arithmetic falls into this category, some
32 /// code explicitly expects and relies upon modular arithmetic (e.g.,
33 /// hashing).
34 ///
35 /// Wrapping arithmetic can be achieved either through methods like
36 /// `wrapping_add`, or through the `Wrapping<T>` type, which says that
37 /// all standard arithmetic operations on the underlying value are
38 /// intended to have wrapping semantics.
39 ///
40 /// # Examples
41 ///
42 /// ```
43 /// use std::num::Wrapping;
44 ///
45 /// let zero = Wrapping(0u32);
46 /// let one = Wrapping(1u32);
47 ///
48 /// assert_eq!(std::u32::MAX, (zero - one).0);
49 /// ```
50 #[stable(feature = "rust1", since = "1.0.0")]
51 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
52 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")] pub T);
53
54 #[stable(feature = "rust1", since = "1.0.0")]
55 impl<T: fmt::Debug> fmt::Debug for Wrapping<T> {
56 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
57 self.0.fmt(f)
58 }
59 }
60
61 #[stable(feature = "wrapping_display", since = "1.10.0")]
62 impl<T: fmt::Display> fmt::Display for Wrapping<T> {
63 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
64 self.0.fmt(f)
65 }
66 }
67
68 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
69 impl<T: fmt::Binary> fmt::Binary for Wrapping<T> {
70 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
71 self.0.fmt(f)
72 }
73 }
74
75 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
76 impl<T: fmt::Octal> fmt::Octal for Wrapping<T> {
77 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
78 self.0.fmt(f)
79 }
80 }
81
82 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
83 impl<T: fmt::LowerHex> fmt::LowerHex for Wrapping<T> {
84 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
85 self.0.fmt(f)
86 }
87 }
88
89 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
90 impl<T: fmt::UpperHex> fmt::UpperHex for Wrapping<T> {
91 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
92 self.0.fmt(f)
93 }
94 }
95
96 mod wrapping;
97
98 // All these modules are technically private and only exposed for libcoretest:
99 pub mod flt2dec;
100 pub mod dec2flt;
101 pub mod bignum;
102 pub mod diy_float;
103
104 /// Types that have a "zero" value.
105 ///
106 /// This trait is intended for use in conjunction with `Add`, as an identity:
107 /// `x + T::zero() == x`.
108 #[unstable(feature = "zero_one",
109 reason = "unsure of placement, wants to use associated constants",
110 issue = "27739")]
111 #[rustc_deprecated(since = "1.11.0", reason = "no longer used for \
112 Iterator::sum")]
113 pub trait Zero: Sized {
114 /// The "zero" (usually, additive identity) for this type.
115 fn zero() -> Self;
116 }
117
118 /// Types that have a "one" value.
119 ///
120 /// This trait is intended for use in conjunction with `Mul`, as an identity:
121 /// `x * T::one() == x`.
122 #[unstable(feature = "zero_one",
123 reason = "unsure of placement, wants to use associated constants",
124 issue = "27739")]
125 #[rustc_deprecated(since = "1.11.0", reason = "no longer used for \
126 Iterator::product")]
127 pub trait One: Sized {
128 /// The "one" (usually, multiplicative identity) for this type.
129 fn one() -> Self;
130 }
131
132 macro_rules! zero_one_impl {
133 ($($t:ty)*) => ($(
134 #[unstable(feature = "zero_one",
135 reason = "unsure of placement, wants to use associated constants",
136 issue = "27739")]
137 #[allow(deprecated)]
138 impl Zero for $t {
139 #[inline]
140 fn zero() -> Self { 0 }
141 }
142 #[unstable(feature = "zero_one",
143 reason = "unsure of placement, wants to use associated constants",
144 issue = "27739")]
145 #[allow(deprecated)]
146 impl One for $t {
147 #[inline]
148 fn one() -> Self { 1 }
149 }
150 )*)
151 }
152 zero_one_impl! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
153
154 macro_rules! zero_one_impl_float {
155 ($($t:ty)*) => ($(
156 #[unstable(feature = "zero_one",
157 reason = "unsure of placement, wants to use associated constants",
158 issue = "27739")]
159 #[allow(deprecated)]
160 impl Zero for $t {
161 #[inline]
162 fn zero() -> Self { 0.0 }
163 }
164 #[unstable(feature = "zero_one",
165 reason = "unsure of placement, wants to use associated constants",
166 issue = "27739")]
167 #[allow(deprecated)]
168 impl One for $t {
169 #[inline]
170 fn one() -> Self { 1.0 }
171 }
172 )*)
173 }
174 zero_one_impl_float! { f32 f64 }
175
176 macro_rules! checked_op {
177 ($U:ty, $op:path, $x:expr, $y:expr) => {{
178 let (result, overflowed) = unsafe { $op($x as $U, $y as $U) };
179 if overflowed { None } else { Some(result as Self) }
180 }}
181 }
182
183 // `Int` + `SignedInt` implemented for signed integers
184 macro_rules! int_impl {
185 ($ActualT:ident, $UnsignedT:ty, $BITS:expr,
186 $add_with_overflow:path,
187 $sub_with_overflow:path,
188 $mul_with_overflow:path) => {
189 /// Returns the smallest value that can be represented by this integer type.
190 ///
191 /// # Examples
192 ///
193 /// ```
194 /// assert_eq!(i8::min_value(), -128);
195 /// ```
196 #[stable(feature = "rust1", since = "1.0.0")]
197 #[inline]
198 pub const fn min_value() -> Self {
199 (-1 as Self) << ($BITS - 1)
200 }
201
202 /// Returns the largest value that can be represented by this integer type.
203 ///
204 /// # Examples
205 ///
206 /// ```
207 /// assert_eq!(i8::max_value(), 127);
208 /// ```
209 #[stable(feature = "rust1", since = "1.0.0")]
210 #[inline]
211 pub const fn max_value() -> Self {
212 !Self::min_value()
213 }
214
215 /// Converts a string slice in a given base to an integer.
216 ///
217 /// Leading and trailing whitespace represent an error.
218 ///
219 /// # Examples
220 ///
221 /// Basic usage:
222 ///
223 /// ```
224 /// assert_eq!(i32::from_str_radix("A", 16), Ok(10));
225 /// ```
226 #[stable(feature = "rust1", since = "1.0.0")]
227 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
228 from_str_radix(src, radix)
229 }
230
231 /// Returns the number of ones in the binary representation of `self`.
232 ///
233 /// # Examples
234 ///
235 /// Basic usage:
236 ///
237 /// ```
238 /// let n = -0b1000_0000i8;
239 ///
240 /// assert_eq!(n.count_ones(), 1);
241 /// ```
242 #[stable(feature = "rust1", since = "1.0.0")]
243 #[inline]
244 pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
245
246 /// Returns the number of zeros in the binary representation of `self`.
247 ///
248 /// # Examples
249 ///
250 /// Basic usage:
251 ///
252 /// ```
253 /// let n = -0b1000_0000i8;
254 ///
255 /// assert_eq!(n.count_zeros(), 7);
256 /// ```
257 #[stable(feature = "rust1", since = "1.0.0")]
258 #[inline]
259 pub fn count_zeros(self) -> u32 {
260 (!self).count_ones()
261 }
262
263 /// Returns the number of leading zeros in the binary representation
264 /// of `self`.
265 ///
266 /// # Examples
267 ///
268 /// Basic usage:
269 ///
270 /// ```
271 /// let n = -1i16;
272 ///
273 /// assert_eq!(n.leading_zeros(), 0);
274 /// ```
275 #[stable(feature = "rust1", since = "1.0.0")]
276 #[inline]
277 pub fn leading_zeros(self) -> u32 {
278 (self as $UnsignedT).leading_zeros()
279 }
280
281 /// Returns the number of trailing zeros in the binary representation
282 /// of `self`.
283 ///
284 /// # Examples
285 ///
286 /// Basic usage:
287 ///
288 /// ```
289 /// let n = -4i8;
290 ///
291 /// assert_eq!(n.trailing_zeros(), 2);
292 /// ```
293 #[stable(feature = "rust1", since = "1.0.0")]
294 #[inline]
295 pub fn trailing_zeros(self) -> u32 {
296 (self as $UnsignedT).trailing_zeros()
297 }
298
299 /// Shifts the bits to the left by a specified amount, `n`,
300 /// wrapping the truncated bits to the end of the resulting integer.
301 ///
302 /// Please note this isn't the same operation as `<<`!
303 ///
304 /// # Examples
305 ///
306 /// Basic usage:
307 ///
308 /// ```
309 /// let n = 0x0123456789ABCDEFi64;
310 /// let m = -0x76543210FEDCBA99i64;
311 ///
312 /// assert_eq!(n.rotate_left(32), m);
313 /// ```
314 #[stable(feature = "rust1", since = "1.0.0")]
315 #[inline]
316 pub fn rotate_left(self, n: u32) -> Self {
317 (self as $UnsignedT).rotate_left(n) as Self
318 }
319
320 /// Shifts the bits to the right by a specified amount, `n`,
321 /// wrapping the truncated bits to the beginning of the resulting
322 /// integer.
323 ///
324 /// Please note this isn't the same operation as `>>`!
325 ///
326 /// # Examples
327 ///
328 /// Basic usage:
329 ///
330 /// ```
331 /// let n = 0x0123456789ABCDEFi64;
332 /// let m = -0xFEDCBA987654322i64;
333 ///
334 /// assert_eq!(n.rotate_right(4), m);
335 /// ```
336 #[stable(feature = "rust1", since = "1.0.0")]
337 #[inline]
338 pub fn rotate_right(self, n: u32) -> Self {
339 (self as $UnsignedT).rotate_right(n) as Self
340 }
341
342 /// Reverses the byte order of the integer.
343 ///
344 /// # Examples
345 ///
346 /// Basic usage:
347 ///
348 /// ```
349 /// let n = 0x0123456789ABCDEFi64;
350 /// let m = -0x1032547698BADCFFi64;
351 ///
352 /// assert_eq!(n.swap_bytes(), m);
353 /// ```
354 #[stable(feature = "rust1", since = "1.0.0")]
355 #[inline]
356 pub fn swap_bytes(self) -> Self {
357 (self as $UnsignedT).swap_bytes() as Self
358 }
359
360 /// Converts an integer from big endian to the target's endianness.
361 ///
362 /// On big endian this is a no-op. On little endian the bytes are
363 /// swapped.
364 ///
365 /// # Examples
366 ///
367 /// Basic usage:
368 ///
369 /// ```
370 /// let n = 0x0123456789ABCDEFi64;
371 ///
372 /// if cfg!(target_endian = "big") {
373 /// assert_eq!(i64::from_be(n), n)
374 /// } else {
375 /// assert_eq!(i64::from_be(n), n.swap_bytes())
376 /// }
377 /// ```
378 #[stable(feature = "rust1", since = "1.0.0")]
379 #[inline]
380 pub fn from_be(x: Self) -> Self {
381 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
382 }
383
384 /// Converts an integer from little endian to the target's endianness.
385 ///
386 /// On little endian this is a no-op. On big endian the bytes are
387 /// swapped.
388 ///
389 /// # Examples
390 ///
391 /// Basic usage:
392 ///
393 /// ```
394 /// let n = 0x0123456789ABCDEFi64;
395 ///
396 /// if cfg!(target_endian = "little") {
397 /// assert_eq!(i64::from_le(n), n)
398 /// } else {
399 /// assert_eq!(i64::from_le(n), n.swap_bytes())
400 /// }
401 /// ```
402 #[stable(feature = "rust1", since = "1.0.0")]
403 #[inline]
404 pub fn from_le(x: Self) -> Self {
405 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
406 }
407
408 /// Converts `self` to big endian from the target's endianness.
409 ///
410 /// On big endian this is a no-op. On little endian the bytes are
411 /// swapped.
412 ///
413 /// # Examples
414 ///
415 /// Basic usage:
416 ///
417 /// ```
418 /// let n = 0x0123456789ABCDEFi64;
419 ///
420 /// if cfg!(target_endian = "big") {
421 /// assert_eq!(n.to_be(), n)
422 /// } else {
423 /// assert_eq!(n.to_be(), n.swap_bytes())
424 /// }
425 /// ```
426 #[stable(feature = "rust1", since = "1.0.0")]
427 #[inline]
428 pub fn to_be(self) -> Self { // or not to be?
429 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
430 }
431
432 /// Converts `self` to little endian from the target's endianness.
433 ///
434 /// On little endian this is a no-op. On big endian the bytes are
435 /// swapped.
436 ///
437 /// # Examples
438 ///
439 /// Basic usage:
440 ///
441 /// ```
442 /// let n = 0x0123456789ABCDEFi64;
443 ///
444 /// if cfg!(target_endian = "little") {
445 /// assert_eq!(n.to_le(), n)
446 /// } else {
447 /// assert_eq!(n.to_le(), n.swap_bytes())
448 /// }
449 /// ```
450 #[stable(feature = "rust1", since = "1.0.0")]
451 #[inline]
452 pub fn to_le(self) -> Self {
453 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
454 }
455
456 /// Checked integer addition. Computes `self + other`, returning `None`
457 /// if overflow occurred.
458 ///
459 /// # Examples
460 ///
461 /// Basic usage:
462 ///
463 /// ```
464 /// assert_eq!(7i16.checked_add(32760), Some(32767));
465 /// assert_eq!(8i16.checked_add(32760), None);
466 /// ```
467 #[stable(feature = "rust1", since = "1.0.0")]
468 #[inline]
469 pub fn checked_add(self, other: Self) -> Option<Self> {
470 let (a, b) = self.overflowing_add(other);
471 if b {None} else {Some(a)}
472 }
473
474 /// Checked integer subtraction. Computes `self - other`, returning
475 /// `None` if underflow occurred.
476 ///
477 /// # Examples
478 ///
479 /// Basic usage:
480 ///
481 /// ```
482 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
483 /// assert_eq!((-128i8).checked_sub(1), None);
484 /// ```
485 #[stable(feature = "rust1", since = "1.0.0")]
486 #[inline]
487 pub fn checked_sub(self, other: Self) -> Option<Self> {
488 let (a, b) = self.overflowing_sub(other);
489 if b {None} else {Some(a)}
490 }
491
492 /// Checked integer multiplication. Computes `self * other`, returning
493 /// `None` if underflow or overflow occurred.
494 ///
495 /// # Examples
496 ///
497 /// Basic usage:
498 ///
499 /// ```
500 /// assert_eq!(6i8.checked_mul(21), Some(126));
501 /// assert_eq!(6i8.checked_mul(22), None);
502 /// ```
503 #[stable(feature = "rust1", since = "1.0.0")]
504 #[inline]
505 pub fn checked_mul(self, other: Self) -> Option<Self> {
506 let (a, b) = self.overflowing_mul(other);
507 if b {None} else {Some(a)}
508 }
509
510 /// Checked integer division. Computes `self / other`, returning `None`
511 /// if `other == 0` or the operation results in underflow or overflow.
512 ///
513 /// # Examples
514 ///
515 /// Basic usage:
516 ///
517 /// ```
518 /// assert_eq!((-127i8).checked_div(-1), Some(127));
519 /// assert_eq!((-128i8).checked_div(-1), None);
520 /// assert_eq!((1i8).checked_div(0), None);
521 /// ```
522 #[stable(feature = "rust1", since = "1.0.0")]
523 #[inline]
524 pub fn checked_div(self, other: Self) -> Option<Self> {
525 if other == 0 {
526 None
527 } else {
528 let (a, b) = self.overflowing_div(other);
529 if b {None} else {Some(a)}
530 }
531 }
532
533 /// Checked integer remainder. Computes `self % other`, returning `None`
534 /// if `other == 0` or the operation results in underflow or overflow.
535 ///
536 /// # Examples
537 ///
538 /// Basic usage:
539 ///
540 /// ```
541 /// use std::i32;
542 ///
543 /// assert_eq!(5i32.checked_rem(2), Some(1));
544 /// assert_eq!(5i32.checked_rem(0), None);
545 /// assert_eq!(i32::MIN.checked_rem(-1), None);
546 /// ```
547 #[stable(feature = "wrapping", since = "1.7.0")]
548 #[inline]
549 pub fn checked_rem(self, other: Self) -> Option<Self> {
550 if other == 0 {
551 None
552 } else {
553 let (a, b) = self.overflowing_rem(other);
554 if b {None} else {Some(a)}
555 }
556 }
557
558 /// Checked negation. Computes `-self`, returning `None` if `self ==
559 /// MIN`.
560 ///
561 /// # Examples
562 ///
563 /// Basic usage:
564 ///
565 /// ```
566 /// use std::i32;
567 ///
568 /// assert_eq!(5i32.checked_neg(), Some(-5));
569 /// assert_eq!(i32::MIN.checked_neg(), None);
570 /// ```
571 #[stable(feature = "wrapping", since = "1.7.0")]
572 #[inline]
573 pub fn checked_neg(self) -> Option<Self> {
574 let (a, b) = self.overflowing_neg();
575 if b {None} else {Some(a)}
576 }
577
578 /// Checked shift left. Computes `self << rhs`, returning `None`
579 /// if `rhs` is larger than or equal to the number of bits in `self`.
580 ///
581 /// # Examples
582 ///
583 /// Basic usage:
584 ///
585 /// ```
586 /// assert_eq!(0x10i32.checked_shl(4), Some(0x100));
587 /// assert_eq!(0x10i32.checked_shl(33), None);
588 /// ```
589 #[stable(feature = "wrapping", since = "1.7.0")]
590 #[inline]
591 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
592 let (a, b) = self.overflowing_shl(rhs);
593 if b {None} else {Some(a)}
594 }
595
596 /// Checked shift right. Computes `self >> rhs`, returning `None`
597 /// if `rhs` is larger than or equal to the number of bits in `self`.
598 ///
599 /// # Examples
600 ///
601 /// Basic usage:
602 ///
603 /// ```
604 /// assert_eq!(0x10i32.checked_shr(4), Some(0x1));
605 /// assert_eq!(0x10i32.checked_shr(33), None);
606 /// ```
607 #[stable(feature = "wrapping", since = "1.7.0")]
608 #[inline]
609 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
610 let (a, b) = self.overflowing_shr(rhs);
611 if b {None} else {Some(a)}
612 }
613
614 /// Checked absolute value. Computes `self.abs()`, returning `None` if
615 /// `self == MIN`.
616 ///
617 /// # Examples
618 ///
619 /// Basic usage:
620 ///
621 /// ```
622 /// # #![feature(no_panic_abs)]
623 ///
624 /// use std::i32;
625 ///
626 /// assert_eq!((-5i32).checked_abs(), Some(5));
627 /// assert_eq!(i32::MIN.checked_abs(), None);
628 /// ```
629 #[unstable(feature = "no_panic_abs", issue = "35057")]
630 #[inline]
631 pub fn checked_abs(self) -> Option<Self> {
632 if self.is_negative() {
633 self.checked_neg()
634 } else {
635 Some(self)
636 }
637 }
638
639 /// Saturating integer addition. Computes `self + other`, saturating at
640 /// the numeric bounds instead of overflowing.
641 ///
642 /// # Examples
643 ///
644 /// Basic usage:
645 ///
646 /// ```
647 /// assert_eq!(100i8.saturating_add(1), 101);
648 /// assert_eq!(100i8.saturating_add(127), 127);
649 /// ```
650 #[stable(feature = "rust1", since = "1.0.0")]
651 #[inline]
652 pub fn saturating_add(self, other: Self) -> Self {
653 match self.checked_add(other) {
654 Some(x) => x,
655 None if other >= 0 => Self::max_value(),
656 None => Self::min_value(),
657 }
658 }
659
660 /// Saturating integer subtraction. Computes `self - other`, saturating
661 /// at the numeric bounds instead of overflowing.
662 ///
663 /// # Examples
664 ///
665 /// Basic usage:
666 ///
667 /// ```
668 /// assert_eq!(100i8.saturating_sub(127), -27);
669 /// assert_eq!((-100i8).saturating_sub(127), -128);
670 /// ```
671 #[stable(feature = "rust1", since = "1.0.0")]
672 #[inline]
673 pub fn saturating_sub(self, other: Self) -> Self {
674 match self.checked_sub(other) {
675 Some(x) => x,
676 None if other >= 0 => Self::min_value(),
677 None => Self::max_value(),
678 }
679 }
680
681 /// Saturating integer multiplication. Computes `self * other`,
682 /// saturating at the numeric bounds instead of overflowing.
683 ///
684 /// # Examples
685 ///
686 /// Basic usage:
687 ///
688 /// ```
689 /// use std::i32;
690 ///
691 /// assert_eq!(100i32.saturating_mul(127), 12700);
692 /// assert_eq!((1i32 << 23).saturating_mul(1 << 23), i32::MAX);
693 /// assert_eq!((-1i32 << 23).saturating_mul(1 << 23), i32::MIN);
694 /// ```
695 #[stable(feature = "wrapping", since = "1.7.0")]
696 #[inline]
697 pub fn saturating_mul(self, other: Self) -> Self {
698 self.checked_mul(other).unwrap_or_else(|| {
699 if (self < 0 && other < 0) || (self > 0 && other > 0) {
700 Self::max_value()
701 } else {
702 Self::min_value()
703 }
704 })
705 }
706
707 /// Wrapping (modular) addition. Computes `self + other`,
708 /// wrapping around at the boundary of the type.
709 ///
710 /// # Examples
711 ///
712 /// Basic usage:
713 ///
714 /// ```
715 /// assert_eq!(100i8.wrapping_add(27), 127);
716 /// assert_eq!(100i8.wrapping_add(127), -29);
717 /// ```
718 #[stable(feature = "rust1", since = "1.0.0")]
719 #[inline]
720 pub fn wrapping_add(self, rhs: Self) -> Self {
721 unsafe {
722 intrinsics::overflowing_add(self, rhs)
723 }
724 }
725
726 /// Wrapping (modular) subtraction. Computes `self - other`,
727 /// wrapping around at the boundary of the type.
728 ///
729 /// # Examples
730 ///
731 /// Basic usage:
732 ///
733 /// ```
734 /// assert_eq!(0i8.wrapping_sub(127), -127);
735 /// assert_eq!((-2i8).wrapping_sub(127), 127);
736 /// ```
737 #[stable(feature = "rust1", since = "1.0.0")]
738 #[inline]
739 pub fn wrapping_sub(self, rhs: Self) -> Self {
740 unsafe {
741 intrinsics::overflowing_sub(self, rhs)
742 }
743 }
744
745 /// Wrapping (modular) multiplication. Computes `self *
746 /// other`, wrapping around at the boundary of the type.
747 ///
748 /// # Examples
749 ///
750 /// Basic usage:
751 ///
752 /// ```
753 /// assert_eq!(10i8.wrapping_mul(12), 120);
754 /// assert_eq!(11i8.wrapping_mul(12), -124);
755 /// ```
756 #[stable(feature = "rust1", since = "1.0.0")]
757 #[inline]
758 pub fn wrapping_mul(self, rhs: Self) -> Self {
759 unsafe {
760 intrinsics::overflowing_mul(self, rhs)
761 }
762 }
763
764 /// Wrapping (modular) division. Computes `self / other`,
765 /// wrapping around at the boundary of the type.
766 ///
767 /// The only case where such wrapping can occur is when one
768 /// divides `MIN / -1` on a signed type (where `MIN` is the
769 /// negative minimal value for the type); this is equivalent
770 /// to `-MIN`, a positive value that is too large to represent
771 /// in the type. In such a case, this function returns `MIN`
772 /// itself.
773 ///
774 /// # Panics
775 ///
776 /// This function will panic if `rhs` is 0.
777 ///
778 /// # Examples
779 ///
780 /// Basic usage:
781 ///
782 /// ```
783 /// assert_eq!(100u8.wrapping_div(10), 10);
784 /// assert_eq!((-128i8).wrapping_div(-1), -128);
785 /// ```
786 #[stable(feature = "num_wrapping", since = "1.2.0")]
787 #[inline(always)]
788 pub fn wrapping_div(self, rhs: Self) -> Self {
789 self.overflowing_div(rhs).0
790 }
791
792 /// Wrapping (modular) remainder. Computes `self % other`,
793 /// wrapping around at the boundary of the type.
794 ///
795 /// Such wrap-around never actually occurs mathematically;
796 /// implementation artifacts make `x % y` invalid for `MIN /
797 /// -1` on a signed type (where `MIN` is the negative
798 /// minimal value). In such a case, this function returns `0`.
799 ///
800 /// # Panics
801 ///
802 /// This function will panic if `rhs` is 0.
803 ///
804 /// # Examples
805 ///
806 /// Basic usage:
807 ///
808 /// ```
809 /// assert_eq!(100i8.wrapping_rem(10), 0);
810 /// assert_eq!((-128i8).wrapping_rem(-1), 0);
811 /// ```
812 #[stable(feature = "num_wrapping", since = "1.2.0")]
813 #[inline(always)]
814 pub fn wrapping_rem(self, rhs: Self) -> Self {
815 self.overflowing_rem(rhs).0
816 }
817
818 /// Wrapping (modular) negation. Computes `-self`,
819 /// wrapping around at the boundary of the type.
820 ///
821 /// The only case where such wrapping can occur is when one
822 /// negates `MIN` on a signed type (where `MIN` is the
823 /// negative minimal value for the type); this is a positive
824 /// value that is too large to represent in the type. In such
825 /// a case, this function returns `MIN` itself.
826 ///
827 /// # Examples
828 ///
829 /// Basic usage:
830 ///
831 /// ```
832 /// assert_eq!(100i8.wrapping_neg(), -100);
833 /// assert_eq!((-128i8).wrapping_neg(), -128);
834 /// ```
835 #[stable(feature = "num_wrapping", since = "1.2.0")]
836 #[inline(always)]
837 pub fn wrapping_neg(self) -> Self {
838 self.overflowing_neg().0
839 }
840
841 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
842 /// where `mask` removes any high-order bits of `rhs` that
843 /// would cause the shift to exceed the bitwidth of the type.
844 ///
845 /// Note that this is *not* the same as a rotate-left; the
846 /// RHS of a wrapping shift-left is restricted to the range
847 /// of the type, rather than the bits shifted out of the LHS
848 /// being returned to the other end. The primitive integer
849 /// types all implement a `rotate_left` function, which may
850 /// be what you want instead.
851 ///
852 /// # Examples
853 ///
854 /// Basic usage:
855 ///
856 /// ```
857 /// assert_eq!((-1i8).wrapping_shl(7), -128);
858 /// assert_eq!((-1i8).wrapping_shl(8), -1);
859 /// ```
860 #[stable(feature = "num_wrapping", since = "1.2.0")]
861 #[inline(always)]
862 pub fn wrapping_shl(self, rhs: u32) -> Self {
863 self.overflowing_shl(rhs).0
864 }
865
866 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
867 /// where `mask` removes any high-order bits of `rhs` that
868 /// would cause the shift to exceed the bitwidth of the type.
869 ///
870 /// Note that this is *not* the same as a rotate-right; the
871 /// RHS of a wrapping shift-right is restricted to the range
872 /// of the type, rather than the bits shifted out of the LHS
873 /// being returned to the other end. The primitive integer
874 /// types all implement a `rotate_right` function, which may
875 /// be what you want instead.
876 ///
877 /// # Examples
878 ///
879 /// Basic usage:
880 ///
881 /// ```
882 /// assert_eq!((-128i8).wrapping_shr(7), -1);
883 /// assert_eq!((-128i8).wrapping_shr(8), -128);
884 /// ```
885 #[stable(feature = "num_wrapping", since = "1.2.0")]
886 #[inline(always)]
887 pub fn wrapping_shr(self, rhs: u32) -> Self {
888 self.overflowing_shr(rhs).0
889 }
890
891 /// Wrapping (modular) absolute value. Computes `self.abs()`,
892 /// wrapping around at the boundary of the type.
893 ///
894 /// The only case where such wrapping can occur is when one takes
895 /// the absolute value of the negative minimal value for the type
896 /// this is a positive value that is too large to represent in the
897 /// type. In such a case, this function returns `MIN` itself.
898 ///
899 /// # Examples
900 ///
901 /// Basic usage:
902 ///
903 /// ```
904 /// # #![feature(no_panic_abs)]
905 ///
906 /// assert_eq!(100i8.wrapping_abs(), 100);
907 /// assert_eq!((-100i8).wrapping_abs(), 100);
908 /// assert_eq!((-128i8).wrapping_abs(), -128);
909 /// assert_eq!((-128i8).wrapping_abs() as u8, 128);
910 /// ```
911 #[unstable(feature = "no_panic_abs", issue = "35057")]
912 #[inline(always)]
913 pub fn wrapping_abs(self) -> Self {
914 if self.is_negative() {
915 self.wrapping_neg()
916 } else {
917 self
918 }
919 }
920
921 /// Calculates `self` + `rhs`
922 ///
923 /// Returns a tuple of the addition along with a boolean indicating
924 /// whether an arithmetic overflow would occur. If an overflow would
925 /// have occurred then the wrapped value is returned.
926 ///
927 /// # Examples
928 ///
929 /// Basic usage
930 ///
931 /// ```
932 /// use std::i32;
933 ///
934 /// assert_eq!(5i32.overflowing_add(2), (7, false));
935 /// assert_eq!(i32::MAX.overflowing_add(1), (i32::MIN, true));
936 /// ```
937 #[inline]
938 #[stable(feature = "wrapping", since = "1.7.0")]
939 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
940 unsafe {
941 let (a, b) = $add_with_overflow(self as $ActualT,
942 rhs as $ActualT);
943 (a as Self, b)
944 }
945 }
946
947 /// Calculates `self` - `rhs`
948 ///
949 /// Returns a tuple of the subtraction along with a boolean indicating
950 /// whether an arithmetic overflow would occur. If an overflow would
951 /// have occurred then the wrapped value is returned.
952 ///
953 /// # Examples
954 ///
955 /// Basic usage
956 ///
957 /// ```
958 /// use std::i32;
959 ///
960 /// assert_eq!(5i32.overflowing_sub(2), (3, false));
961 /// assert_eq!(i32::MIN.overflowing_sub(1), (i32::MAX, true));
962 /// ```
963 #[inline]
964 #[stable(feature = "wrapping", since = "1.7.0")]
965 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
966 unsafe {
967 let (a, b) = $sub_with_overflow(self as $ActualT,
968 rhs as $ActualT);
969 (a as Self, b)
970 }
971 }
972
973 /// Calculates the multiplication of `self` and `rhs`.
974 ///
975 /// Returns a tuple of the multiplication along with a boolean
976 /// indicating whether an arithmetic overflow would occur. If an
977 /// overflow would have occurred then the wrapped value is returned.
978 ///
979 /// # Examples
980 ///
981 /// Basic usage
982 ///
983 /// ```
984 /// assert_eq!(5i32.overflowing_mul(2), (10, false));
985 /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
986 /// ```
987 #[inline]
988 #[stable(feature = "wrapping", since = "1.7.0")]
989 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
990 unsafe {
991 let (a, b) = $mul_with_overflow(self as $ActualT,
992 rhs as $ActualT);
993 (a as Self, b)
994 }
995 }
996
997 /// Calculates the divisor when `self` is divided by `rhs`.
998 ///
999 /// Returns a tuple of the divisor along with a boolean indicating
1000 /// whether an arithmetic overflow would occur. If an overflow would
1001 /// occur then self is returned.
1002 ///
1003 /// # Panics
1004 ///
1005 /// This function will panic if `rhs` is 0.
1006 ///
1007 /// # Examples
1008 ///
1009 /// Basic usage
1010 ///
1011 /// ```
1012 /// use std::i32;
1013 ///
1014 /// assert_eq!(5i32.overflowing_div(2), (2, false));
1015 /// assert_eq!(i32::MIN.overflowing_div(-1), (i32::MIN, true));
1016 /// ```
1017 #[inline]
1018 #[stable(feature = "wrapping", since = "1.7.0")]
1019 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
1020 if self == Self::min_value() && rhs == -1 {
1021 (self, true)
1022 } else {
1023 (self / rhs, false)
1024 }
1025 }
1026
1027 /// Calculates the remainder when `self` is divided by `rhs`.
1028 ///
1029 /// Returns a tuple of the remainder after dividing along with a boolean
1030 /// indicating whether an arithmetic overflow would occur. If an
1031 /// overflow would occur then 0 is returned.
1032 ///
1033 /// # Panics
1034 ///
1035 /// This function will panic if `rhs` is 0.
1036 ///
1037 /// # Examples
1038 ///
1039 /// Basic usage
1040 ///
1041 /// ```
1042 /// use std::i32;
1043 ///
1044 /// assert_eq!(5i32.overflowing_rem(2), (1, false));
1045 /// assert_eq!(i32::MIN.overflowing_rem(-1), (0, true));
1046 /// ```
1047 #[inline]
1048 #[stable(feature = "wrapping", since = "1.7.0")]
1049 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
1050 if self == Self::min_value() && rhs == -1 {
1051 (0, true)
1052 } else {
1053 (self % rhs, false)
1054 }
1055 }
1056
1057 /// Negates self, overflowing if this is equal to the minimum value.
1058 ///
1059 /// Returns a tuple of the negated version of self along with a boolean
1060 /// indicating whether an overflow happened. If `self` is the minimum
1061 /// value (e.g. `i32::MIN` for values of type `i32`), then the minimum
1062 /// value will be returned again and `true` will be returned for an
1063 /// overflow happening.
1064 ///
1065 /// # Examples
1066 ///
1067 /// Basic usage
1068 ///
1069 /// ```
1070 /// use std::i32;
1071 ///
1072 /// assert_eq!(2i32.overflowing_neg(), (-2, false));
1073 /// assert_eq!(i32::MIN.overflowing_neg(), (i32::MIN, true));
1074 /// ```
1075 #[inline]
1076 #[stable(feature = "wrapping", since = "1.7.0")]
1077 pub fn overflowing_neg(self) -> (Self, bool) {
1078 if self == Self::min_value() {
1079 (Self::min_value(), true)
1080 } else {
1081 (-self, false)
1082 }
1083 }
1084
1085 /// Shifts self left by `rhs` bits.
1086 ///
1087 /// Returns a tuple of the shifted version of self along with a boolean
1088 /// indicating whether the shift value was larger than or equal to the
1089 /// number of bits. If the shift value is too large, then value is
1090 /// masked (N-1) where N is the number of bits, and this value is then
1091 /// used to perform the shift.
1092 ///
1093 /// # Examples
1094 ///
1095 /// Basic usage
1096 ///
1097 /// ```
1098 /// assert_eq!(0x10i32.overflowing_shl(4), (0x100, false));
1099 /// assert_eq!(0x10i32.overflowing_shl(36), (0x100, true));
1100 /// ```
1101 #[inline]
1102 #[stable(feature = "wrapping", since = "1.7.0")]
1103 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1104 (self << (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
1105 }
1106
1107 /// Shifts self right by `rhs` bits.
1108 ///
1109 /// Returns a tuple of the shifted version of self along with a boolean
1110 /// indicating whether the shift value was larger than or equal to the
1111 /// number of bits. If the shift value is too large, then value is
1112 /// masked (N-1) where N is the number of bits, and this value is then
1113 /// used to perform the shift.
1114 ///
1115 /// # Examples
1116 ///
1117 /// Basic usage
1118 ///
1119 /// ```
1120 /// assert_eq!(0x10i32.overflowing_shr(4), (0x1, false));
1121 /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
1122 /// ```
1123 #[inline]
1124 #[stable(feature = "wrapping", since = "1.7.0")]
1125 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1126 (self >> (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
1127 }
1128
1129 /// Computes the absolute value of `self`.
1130 ///
1131 /// Returns a tuple of the absolute version of self along with a
1132 /// boolean indicating whether an overflow happened. If self is the
1133 /// minimum value (e.g. i32::MIN for values of type i32), then the
1134 /// minimum value will be returned again and true will be returned for
1135 /// an overflow happening.
1136 ///
1137 /// # Examples
1138 ///
1139 /// Basic usage:
1140 ///
1141 /// ```
1142 /// # #![feature(no_panic_abs)]
1143 ///
1144 /// assert_eq!(10i8.overflowing_abs(), (10,false));
1145 /// assert_eq!((-10i8).overflowing_abs(), (10,false));
1146 /// assert_eq!((-128i8).overflowing_abs(), (-128,true));
1147 /// ```
1148 #[unstable(feature = "no_panic_abs", issue = "35057")]
1149 #[inline]
1150 pub fn overflowing_abs(self) -> (Self, bool) {
1151 if self.is_negative() {
1152 self.overflowing_neg()
1153 } else {
1154 (self, false)
1155 }
1156 }
1157
1158 /// Raises self to the power of `exp`, using exponentiation by squaring.
1159 ///
1160 /// # Examples
1161 ///
1162 /// Basic usage:
1163 ///
1164 /// ```
1165 /// let x: i32 = 2; // or any other integer type
1166 ///
1167 /// assert_eq!(x.pow(4), 16);
1168 /// ```
1169 #[stable(feature = "rust1", since = "1.0.0")]
1170 #[inline]
1171 #[rustc_inherit_overflow_checks]
1172 pub fn pow(self, mut exp: u32) -> Self {
1173 let mut base = self;
1174 let mut acc = 1;
1175
1176 while exp > 1 {
1177 if (exp & 1) == 1 {
1178 acc = acc * base;
1179 }
1180 exp /= 2;
1181 base = base * base;
1182 }
1183
1184 // Deal with the final bit of the exponent separately, since
1185 // squaring the base afterwards is not necessary and may cause a
1186 // needless overflow.
1187 if exp == 1 {
1188 acc = acc * base;
1189 }
1190
1191 acc
1192 }
1193
1194 /// Computes the absolute value of `self`.
1195 ///
1196 /// # Overflow behavior
1197 ///
1198 /// The absolute value of `i32::min_value()` cannot be represented as an
1199 /// `i32`, and attempting to calculate it will cause an overflow. This
1200 /// means that code in debug mode will trigger a panic on this case and
1201 /// optimized code will return `i32::min_value()` without a panic.
1202 ///
1203 /// # Examples
1204 ///
1205 /// Basic usage:
1206 ///
1207 /// ```
1208 /// assert_eq!(10i8.abs(), 10);
1209 /// assert_eq!((-10i8).abs(), 10);
1210 /// ```
1211 #[stable(feature = "rust1", since = "1.0.0")]
1212 #[inline]
1213 #[rustc_inherit_overflow_checks]
1214 pub fn abs(self) -> Self {
1215 if self.is_negative() {
1216 // Note that the #[inline] above means that the overflow
1217 // semantics of this negation depend on the crate we're being
1218 // inlined into.
1219 -self
1220 } else {
1221 self
1222 }
1223 }
1224
1225 /// Returns a number representing sign of `self`.
1226 ///
1227 /// - `0` if the number is zero
1228 /// - `1` if the number is positive
1229 /// - `-1` if the number is negative
1230 ///
1231 /// # Examples
1232 ///
1233 /// Basic usage:
1234 ///
1235 /// ```
1236 /// assert_eq!(10i8.signum(), 1);
1237 /// assert_eq!(0i8.signum(), 0);
1238 /// assert_eq!((-10i8).signum(), -1);
1239 /// ```
1240 #[stable(feature = "rust1", since = "1.0.0")]
1241 #[inline]
1242 pub fn signum(self) -> Self {
1243 match self {
1244 n if n > 0 => 1,
1245 0 => 0,
1246 _ => -1,
1247 }
1248 }
1249
1250 /// Returns `true` if `self` is positive and `false` if the number
1251 /// is zero or negative.
1252 ///
1253 /// # Examples
1254 ///
1255 /// Basic usage:
1256 ///
1257 /// ```
1258 /// assert!(10i8.is_positive());
1259 /// assert!(!(-10i8).is_positive());
1260 /// ```
1261 #[stable(feature = "rust1", since = "1.0.0")]
1262 #[inline]
1263 pub fn is_positive(self) -> bool { self > 0 }
1264
1265 /// Returns `true` if `self` is negative and `false` if the number
1266 /// is zero or positive.
1267 ///
1268 /// # Examples
1269 ///
1270 /// Basic usage:
1271 ///
1272 /// ```
1273 /// assert!((-10i8).is_negative());
1274 /// assert!(!10i8.is_negative());
1275 /// ```
1276 #[stable(feature = "rust1", since = "1.0.0")]
1277 #[inline]
1278 pub fn is_negative(self) -> bool { self < 0 }
1279 }
1280 }
1281
1282 #[lang = "i8"]
1283 impl i8 {
1284 int_impl! { i8, u8, 8,
1285 intrinsics::add_with_overflow,
1286 intrinsics::sub_with_overflow,
1287 intrinsics::mul_with_overflow }
1288 }
1289
1290 #[lang = "i16"]
1291 impl i16 {
1292 int_impl! { i16, u16, 16,
1293 intrinsics::add_with_overflow,
1294 intrinsics::sub_with_overflow,
1295 intrinsics::mul_with_overflow }
1296 }
1297
1298 #[lang = "i32"]
1299 impl i32 {
1300 int_impl! { i32, u32, 32,
1301 intrinsics::add_with_overflow,
1302 intrinsics::sub_with_overflow,
1303 intrinsics::mul_with_overflow }
1304 }
1305
1306 #[lang = "i64"]
1307 impl i64 {
1308 int_impl! { i64, u64, 64,
1309 intrinsics::add_with_overflow,
1310 intrinsics::sub_with_overflow,
1311 intrinsics::mul_with_overflow }
1312 }
1313
1314 #[cfg(target_pointer_width = "16")]
1315 #[lang = "isize"]
1316 impl isize {
1317 int_impl! { i16, u16, 16,
1318 intrinsics::add_with_overflow,
1319 intrinsics::sub_with_overflow,
1320 intrinsics::mul_with_overflow }
1321 }
1322
1323 #[cfg(target_pointer_width = "32")]
1324 #[lang = "isize"]
1325 impl isize {
1326 int_impl! { i32, u32, 32,
1327 intrinsics::add_with_overflow,
1328 intrinsics::sub_with_overflow,
1329 intrinsics::mul_with_overflow }
1330 }
1331
1332 #[cfg(target_pointer_width = "64")]
1333 #[lang = "isize"]
1334 impl isize {
1335 int_impl! { i64, u64, 64,
1336 intrinsics::add_with_overflow,
1337 intrinsics::sub_with_overflow,
1338 intrinsics::mul_with_overflow }
1339 }
1340
1341 // `Int` + `UnsignedInt` implemented for unsigned integers
1342 macro_rules! uint_impl {
1343 ($ActualT:ty, $BITS:expr,
1344 $ctpop:path,
1345 $ctlz:path,
1346 $cttz:path,
1347 $bswap:path,
1348 $add_with_overflow:path,
1349 $sub_with_overflow:path,
1350 $mul_with_overflow:path) => {
1351 /// Returns the smallest value that can be represented by this integer type.
1352 ///
1353 /// # Examples
1354 ///
1355 /// ```
1356 /// assert_eq!(u8::min_value(), 0);
1357 /// ```
1358 #[stable(feature = "rust1", since = "1.0.0")]
1359 #[inline]
1360 pub const fn min_value() -> Self { 0 }
1361
1362 /// Returns the largest value that can be represented by this integer type.
1363 ///
1364 /// # Examples
1365 ///
1366 /// ```
1367 /// assert_eq!(u8::max_value(), 255);
1368 /// ```
1369 #[stable(feature = "rust1", since = "1.0.0")]
1370 #[inline]
1371 pub const fn max_value() -> Self { !0 }
1372
1373 /// Converts a string slice in a given base to an integer.
1374 ///
1375 /// Leading and trailing whitespace represent an error.
1376 ///
1377 /// # Examples
1378 ///
1379 /// Basic usage:
1380 ///
1381 /// ```
1382 /// assert_eq!(u32::from_str_radix("A", 16), Ok(10));
1383 /// ```
1384 #[stable(feature = "rust1", since = "1.0.0")]
1385 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
1386 from_str_radix(src, radix)
1387 }
1388
1389 /// Returns the number of ones in the binary representation of `self`.
1390 ///
1391 /// # Examples
1392 ///
1393 /// Basic usage:
1394 ///
1395 /// ```
1396 /// let n = 0b01001100u8;
1397 ///
1398 /// assert_eq!(n.count_ones(), 3);
1399 /// ```
1400 #[stable(feature = "rust1", since = "1.0.0")]
1401 #[inline]
1402 pub fn count_ones(self) -> u32 {
1403 unsafe { $ctpop(self as $ActualT) as u32 }
1404 }
1405
1406 /// Returns the number of zeros in the binary representation of `self`.
1407 ///
1408 /// # Examples
1409 ///
1410 /// Basic usage:
1411 ///
1412 /// ```
1413 /// let n = 0b01001100u8;
1414 ///
1415 /// assert_eq!(n.count_zeros(), 5);
1416 /// ```
1417 #[stable(feature = "rust1", since = "1.0.0")]
1418 #[inline]
1419 pub fn count_zeros(self) -> u32 {
1420 (!self).count_ones()
1421 }
1422
1423 /// Returns the number of leading zeros in the binary representation
1424 /// of `self`.
1425 ///
1426 /// # Examples
1427 ///
1428 /// Basic usage:
1429 ///
1430 /// ```
1431 /// let n = 0b0101000u16;
1432 ///
1433 /// assert_eq!(n.leading_zeros(), 10);
1434 /// ```
1435 #[stable(feature = "rust1", since = "1.0.0")]
1436 #[inline]
1437 pub fn leading_zeros(self) -> u32 {
1438 unsafe { $ctlz(self as $ActualT) as u32 }
1439 }
1440
1441 /// Returns the number of trailing zeros in the binary representation
1442 /// of `self`.
1443 ///
1444 /// # Examples
1445 ///
1446 /// Basic usage:
1447 ///
1448 /// ```
1449 /// let n = 0b0101000u16;
1450 ///
1451 /// assert_eq!(n.trailing_zeros(), 3);
1452 /// ```
1453 #[stable(feature = "rust1", since = "1.0.0")]
1454 #[inline]
1455 pub fn trailing_zeros(self) -> u32 {
1456 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1457 // emits two conditional moves on x86_64. By promoting the value to
1458 // u16 and setting bit 8, we get better code without any conditional
1459 // operations.
1460 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1461 // pending, remove this workaround once LLVM generates better code
1462 // for cttz8.
1463 unsafe {
1464 if $BITS == 8 {
1465 intrinsics::cttz(self as u16 | 0x100) as u32
1466 } else {
1467 intrinsics::cttz(self) as u32
1468 }
1469 }
1470 }
1471
1472 /// Shifts the bits to the left by a specified amount, `n`,
1473 /// wrapping the truncated bits to the end of the resulting integer.
1474 ///
1475 /// Please note this isn't the same operation as `<<`!
1476 ///
1477 /// # Examples
1478 ///
1479 /// Basic usage:
1480 ///
1481 /// ```
1482 /// let n = 0x0123456789ABCDEFu64;
1483 /// let m = 0x3456789ABCDEF012u64;
1484 ///
1485 /// assert_eq!(n.rotate_left(12), m);
1486 /// ```
1487 #[stable(feature = "rust1", since = "1.0.0")]
1488 #[inline]
1489 pub fn rotate_left(self, n: u32) -> Self {
1490 // Protect against undefined behaviour for over-long bit shifts
1491 let n = n % $BITS;
1492 (self << n) | (self >> (($BITS - n) % $BITS))
1493 }
1494
1495 /// Shifts the bits to the right by a specified amount, `n`,
1496 /// wrapping the truncated bits to the beginning of the resulting
1497 /// integer.
1498 ///
1499 /// Please note this isn't the same operation as `>>`!
1500 ///
1501 /// # Examples
1502 ///
1503 /// Basic usage:
1504 ///
1505 /// ```
1506 /// let n = 0x0123456789ABCDEFu64;
1507 /// let m = 0xDEF0123456789ABCu64;
1508 ///
1509 /// assert_eq!(n.rotate_right(12), m);
1510 /// ```
1511 #[stable(feature = "rust1", since = "1.0.0")]
1512 #[inline]
1513 pub fn rotate_right(self, n: u32) -> Self {
1514 // Protect against undefined behaviour for over-long bit shifts
1515 let n = n % $BITS;
1516 (self >> n) | (self << (($BITS - n) % $BITS))
1517 }
1518
1519 /// Reverses the byte order of the integer.
1520 ///
1521 /// # Examples
1522 ///
1523 /// Basic usage:
1524 ///
1525 /// ```
1526 /// let n = 0x0123456789ABCDEFu64;
1527 /// let m = 0xEFCDAB8967452301u64;
1528 ///
1529 /// assert_eq!(n.swap_bytes(), m);
1530 /// ```
1531 #[stable(feature = "rust1", since = "1.0.0")]
1532 #[inline]
1533 pub fn swap_bytes(self) -> Self {
1534 unsafe { $bswap(self as $ActualT) as Self }
1535 }
1536
1537 /// Converts an integer from big endian to the target's endianness.
1538 ///
1539 /// On big endian this is a no-op. On little endian the bytes are
1540 /// swapped.
1541 ///
1542 /// # Examples
1543 ///
1544 /// Basic usage:
1545 ///
1546 /// ```
1547 /// let n = 0x0123456789ABCDEFu64;
1548 ///
1549 /// if cfg!(target_endian = "big") {
1550 /// assert_eq!(u64::from_be(n), n)
1551 /// } else {
1552 /// assert_eq!(u64::from_be(n), n.swap_bytes())
1553 /// }
1554 /// ```
1555 #[stable(feature = "rust1", since = "1.0.0")]
1556 #[inline]
1557 pub fn from_be(x: Self) -> Self {
1558 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
1559 }
1560
1561 /// Converts an integer from little endian to the target's endianness.
1562 ///
1563 /// On little endian this is a no-op. On big endian the bytes are
1564 /// swapped.
1565 ///
1566 /// # Examples
1567 ///
1568 /// Basic usage:
1569 ///
1570 /// ```
1571 /// let n = 0x0123456789ABCDEFu64;
1572 ///
1573 /// if cfg!(target_endian = "little") {
1574 /// assert_eq!(u64::from_le(n), n)
1575 /// } else {
1576 /// assert_eq!(u64::from_le(n), n.swap_bytes())
1577 /// }
1578 /// ```
1579 #[stable(feature = "rust1", since = "1.0.0")]
1580 #[inline]
1581 pub fn from_le(x: Self) -> Self {
1582 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
1583 }
1584
1585 /// Converts `self` to big endian from the target's endianness.
1586 ///
1587 /// On big endian this is a no-op. On little endian the bytes are
1588 /// swapped.
1589 ///
1590 /// # Examples
1591 ///
1592 /// Basic usage:
1593 ///
1594 /// ```
1595 /// let n = 0x0123456789ABCDEFu64;
1596 ///
1597 /// if cfg!(target_endian = "big") {
1598 /// assert_eq!(n.to_be(), n)
1599 /// } else {
1600 /// assert_eq!(n.to_be(), n.swap_bytes())
1601 /// }
1602 /// ```
1603 #[stable(feature = "rust1", since = "1.0.0")]
1604 #[inline]
1605 pub fn to_be(self) -> Self { // or not to be?
1606 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
1607 }
1608
1609 /// Converts `self` to little endian from the target's endianness.
1610 ///
1611 /// On little endian this is a no-op. On big endian the bytes are
1612 /// swapped.
1613 ///
1614 /// # Examples
1615 ///
1616 /// Basic usage:
1617 ///
1618 /// ```
1619 /// let n = 0x0123456789ABCDEFu64;
1620 ///
1621 /// if cfg!(target_endian = "little") {
1622 /// assert_eq!(n.to_le(), n)
1623 /// } else {
1624 /// assert_eq!(n.to_le(), n.swap_bytes())
1625 /// }
1626 /// ```
1627 #[stable(feature = "rust1", since = "1.0.0")]
1628 #[inline]
1629 pub fn to_le(self) -> Self {
1630 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
1631 }
1632
1633 /// Checked integer addition. Computes `self + other`, returning `None`
1634 /// if overflow occurred.
1635 ///
1636 /// # Examples
1637 ///
1638 /// Basic usage:
1639 ///
1640 /// ```
1641 /// assert_eq!(5u16.checked_add(65530), Some(65535));
1642 /// assert_eq!(6u16.checked_add(65530), None);
1643 /// ```
1644 #[stable(feature = "rust1", since = "1.0.0")]
1645 #[inline]
1646 pub fn checked_add(self, other: Self) -> Option<Self> {
1647 let (a, b) = self.overflowing_add(other);
1648 if b {None} else {Some(a)}
1649 }
1650
1651 /// Checked integer subtraction. Computes `self - other`, returning
1652 /// `None` if underflow occurred.
1653 ///
1654 /// # Examples
1655 ///
1656 /// Basic usage:
1657 ///
1658 /// ```
1659 /// assert_eq!(1u8.checked_sub(1), Some(0));
1660 /// assert_eq!(0u8.checked_sub(1), None);
1661 /// ```
1662 #[stable(feature = "rust1", since = "1.0.0")]
1663 #[inline]
1664 pub fn checked_sub(self, other: Self) -> Option<Self> {
1665 let (a, b) = self.overflowing_sub(other);
1666 if b {None} else {Some(a)}
1667 }
1668
1669 /// Checked integer multiplication. Computes `self * other`, returning
1670 /// `None` if underflow or overflow occurred.
1671 ///
1672 /// # Examples
1673 ///
1674 /// Basic usage:
1675 ///
1676 /// ```
1677 /// assert_eq!(5u8.checked_mul(51), Some(255));
1678 /// assert_eq!(5u8.checked_mul(52), None);
1679 /// ```
1680 #[stable(feature = "rust1", since = "1.0.0")]
1681 #[inline]
1682 pub fn checked_mul(self, other: Self) -> Option<Self> {
1683 let (a, b) = self.overflowing_mul(other);
1684 if b {None} else {Some(a)}
1685 }
1686
1687 /// Checked integer division. Computes `self / other`, returning `None`
1688 /// if `other == 0` or the operation results in underflow or overflow.
1689 ///
1690 /// # Examples
1691 ///
1692 /// Basic usage:
1693 ///
1694 /// ```
1695 /// assert_eq!(128u8.checked_div(2), Some(64));
1696 /// assert_eq!(1u8.checked_div(0), None);
1697 /// ```
1698 #[stable(feature = "rust1", since = "1.0.0")]
1699 #[inline]
1700 pub fn checked_div(self, other: Self) -> Option<Self> {
1701 match other {
1702 0 => None,
1703 other => Some(self / other),
1704 }
1705 }
1706
1707 /// Checked integer remainder. Computes `self % other`, returning `None`
1708 /// if `other == 0` or the operation results in underflow or overflow.
1709 ///
1710 /// # Examples
1711 ///
1712 /// Basic usage:
1713 ///
1714 /// ```
1715 /// assert_eq!(5u32.checked_rem(2), Some(1));
1716 /// assert_eq!(5u32.checked_rem(0), None);
1717 /// ```
1718 #[stable(feature = "wrapping", since = "1.7.0")]
1719 #[inline]
1720 pub fn checked_rem(self, other: Self) -> Option<Self> {
1721 if other == 0 {
1722 None
1723 } else {
1724 Some(self % other)
1725 }
1726 }
1727
1728 /// Checked negation. Computes `-self`, returning `None` unless `self ==
1729 /// 0`.
1730 ///
1731 /// Note that negating any positive integer will overflow.
1732 ///
1733 /// # Examples
1734 ///
1735 /// Basic usage:
1736 ///
1737 /// ```
1738 /// assert_eq!(0u32.checked_neg(), Some(0));
1739 /// assert_eq!(1u32.checked_neg(), None);
1740 /// ```
1741 #[stable(feature = "wrapping", since = "1.7.0")]
1742 #[inline]
1743 pub fn checked_neg(self) -> Option<Self> {
1744 let (a, b) = self.overflowing_neg();
1745 if b {None} else {Some(a)}
1746 }
1747
1748 /// Checked shift left. Computes `self << rhs`, returning `None`
1749 /// if `rhs` is larger than or equal to the number of bits in `self`.
1750 ///
1751 /// # Examples
1752 ///
1753 /// Basic usage:
1754 ///
1755 /// ```
1756 /// assert_eq!(0x10u32.checked_shl(4), Some(0x100));
1757 /// assert_eq!(0x10u32.checked_shl(33), None);
1758 /// ```
1759 #[stable(feature = "wrapping", since = "1.7.0")]
1760 #[inline]
1761 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
1762 let (a, b) = self.overflowing_shl(rhs);
1763 if b {None} else {Some(a)}
1764 }
1765
1766 /// Checked shift right. Computes `self >> rhs`, returning `None`
1767 /// if `rhs` is larger than or equal to the number of bits in `self`.
1768 ///
1769 /// # Examples
1770 ///
1771 /// Basic usage:
1772 ///
1773 /// ```
1774 /// assert_eq!(0x10u32.checked_shr(4), Some(0x1));
1775 /// assert_eq!(0x10u32.checked_shr(33), None);
1776 /// ```
1777 #[stable(feature = "wrapping", since = "1.7.0")]
1778 #[inline]
1779 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
1780 let (a, b) = self.overflowing_shr(rhs);
1781 if b {None} else {Some(a)}
1782 }
1783
1784 /// Saturating integer addition. Computes `self + other`, saturating at
1785 /// the numeric bounds instead of overflowing.
1786 ///
1787 /// # Examples
1788 ///
1789 /// Basic usage:
1790 ///
1791 /// ```
1792 /// assert_eq!(100u8.saturating_add(1), 101);
1793 /// assert_eq!(200u8.saturating_add(127), 255);
1794 /// ```
1795 #[stable(feature = "rust1", since = "1.0.0")]
1796 #[inline]
1797 pub fn saturating_add(self, other: Self) -> Self {
1798 match self.checked_add(other) {
1799 Some(x) => x,
1800 None => Self::max_value(),
1801 }
1802 }
1803
1804 /// Saturating integer subtraction. Computes `self - other`, saturating
1805 /// at the numeric bounds instead of overflowing.
1806 ///
1807 /// # Examples
1808 ///
1809 /// Basic usage:
1810 ///
1811 /// ```
1812 /// assert_eq!(100u8.saturating_sub(27), 73);
1813 /// assert_eq!(13u8.saturating_sub(127), 0);
1814 /// ```
1815 #[stable(feature = "rust1", since = "1.0.0")]
1816 #[inline]
1817 pub fn saturating_sub(self, other: Self) -> Self {
1818 match self.checked_sub(other) {
1819 Some(x) => x,
1820 None => Self::min_value(),
1821 }
1822 }
1823
1824 /// Saturating integer multiplication. Computes `self * other`,
1825 /// saturating at the numeric bounds instead of overflowing.
1826 ///
1827 /// # Examples
1828 ///
1829 /// Basic usage:
1830 ///
1831 /// ```
1832 /// use std::u32;
1833 ///
1834 /// assert_eq!(100u32.saturating_mul(127), 12700);
1835 /// assert_eq!((1u32 << 23).saturating_mul(1 << 23), u32::MAX);
1836 /// ```
1837 #[stable(feature = "wrapping", since = "1.7.0")]
1838 #[inline]
1839 pub fn saturating_mul(self, other: Self) -> Self {
1840 self.checked_mul(other).unwrap_or(Self::max_value())
1841 }
1842
1843 /// Wrapping (modular) addition. Computes `self + other`,
1844 /// wrapping around at the boundary of the type.
1845 ///
1846 /// # Examples
1847 ///
1848 /// Basic usage:
1849 ///
1850 /// ```
1851 /// assert_eq!(200u8.wrapping_add(55), 255);
1852 /// assert_eq!(200u8.wrapping_add(155), 99);
1853 /// ```
1854 #[stable(feature = "rust1", since = "1.0.0")]
1855 #[inline]
1856 pub fn wrapping_add(self, rhs: Self) -> Self {
1857 unsafe {
1858 intrinsics::overflowing_add(self, rhs)
1859 }
1860 }
1861
1862 /// Wrapping (modular) subtraction. Computes `self - other`,
1863 /// wrapping around at the boundary of the type.
1864 ///
1865 /// # Examples
1866 ///
1867 /// Basic usage:
1868 ///
1869 /// ```
1870 /// assert_eq!(100u8.wrapping_sub(100), 0);
1871 /// assert_eq!(100u8.wrapping_sub(155), 201);
1872 /// ```
1873 #[stable(feature = "rust1", since = "1.0.0")]
1874 #[inline]
1875 pub fn wrapping_sub(self, rhs: Self) -> Self {
1876 unsafe {
1877 intrinsics::overflowing_sub(self, rhs)
1878 }
1879 }
1880
1881 /// Wrapping (modular) multiplication. Computes `self *
1882 /// other`, wrapping around at the boundary of the type.
1883 ///
1884 /// # Examples
1885 ///
1886 /// Basic usage:
1887 ///
1888 /// ```
1889 /// assert_eq!(10u8.wrapping_mul(12), 120);
1890 /// assert_eq!(25u8.wrapping_mul(12), 44);
1891 /// ```
1892 #[stable(feature = "rust1", since = "1.0.0")]
1893 #[inline]
1894 pub fn wrapping_mul(self, rhs: Self) -> Self {
1895 unsafe {
1896 intrinsics::overflowing_mul(self, rhs)
1897 }
1898 }
1899
1900 /// Wrapping (modular) division. Computes `self / other`.
1901 /// Wrapped division on unsigned types is just normal division.
1902 /// There's no way wrapping could ever happen.
1903 /// This function exists, so that all operations
1904 /// are accounted for in the wrapping operations.
1905 ///
1906 /// # Examples
1907 ///
1908 /// Basic usage:
1909 ///
1910 /// ```
1911 /// assert_eq!(100u8.wrapping_div(10), 10);
1912 /// ```
1913 #[stable(feature = "num_wrapping", since = "1.2.0")]
1914 #[inline(always)]
1915 pub fn wrapping_div(self, rhs: Self) -> Self {
1916 self / rhs
1917 }
1918
1919 /// Wrapping (modular) remainder. Computes `self % other`.
1920 /// Wrapped remainder calculation on unsigned types is
1921 /// just the regular remainder calculation.
1922 /// There's no way wrapping could ever happen.
1923 /// This function exists, so that all operations
1924 /// are accounted for in the wrapping operations.
1925 ///
1926 /// # Examples
1927 ///
1928 /// Basic usage:
1929 ///
1930 /// ```
1931 /// assert_eq!(100u8.wrapping_rem(10), 0);
1932 /// ```
1933 #[stable(feature = "num_wrapping", since = "1.2.0")]
1934 #[inline(always)]
1935 pub fn wrapping_rem(self, rhs: Self) -> Self {
1936 self % rhs
1937 }
1938
1939 /// Wrapping (modular) negation. Computes `-self`,
1940 /// wrapping around at the boundary of the type.
1941 ///
1942 /// Since unsigned types do not have negative equivalents
1943 /// all applications of this function will wrap (except for `-0`).
1944 /// For values smaller than the corresponding signed type's maximum
1945 /// the result is the same as casting the corresponding signed value.
1946 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1947 /// `MAX` is the corresponding signed type's maximum.
1948 ///
1949 /// # Examples
1950 ///
1951 /// Basic usage:
1952 ///
1953 /// ```
1954 /// assert_eq!(100u8.wrapping_neg(), 156);
1955 /// assert_eq!(0u8.wrapping_neg(), 0);
1956 /// assert_eq!(180u8.wrapping_neg(), 76);
1957 /// assert_eq!(180u8.wrapping_neg(), (127 + 1) - (180u8 - (127 + 1)));
1958 /// ```
1959 #[stable(feature = "num_wrapping", since = "1.2.0")]
1960 #[inline(always)]
1961 pub fn wrapping_neg(self) -> Self {
1962 self.overflowing_neg().0
1963 }
1964
1965 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1966 /// where `mask` removes any high-order bits of `rhs` that
1967 /// would cause the shift to exceed the bitwidth of the type.
1968 ///
1969 /// Note that this is *not* the same as a rotate-left; the
1970 /// RHS of a wrapping shift-left is restricted to the range
1971 /// of the type, rather than the bits shifted out of the LHS
1972 /// being returned to the other end. The primitive integer
1973 /// types all implement a `rotate_left` function, which may
1974 /// be what you want instead.
1975 ///
1976 /// # Examples
1977 ///
1978 /// Basic usage:
1979 ///
1980 /// ```
1981 /// assert_eq!(1u8.wrapping_shl(7), 128);
1982 /// assert_eq!(1u8.wrapping_shl(8), 1);
1983 /// ```
1984 #[stable(feature = "num_wrapping", since = "1.2.0")]
1985 #[inline(always)]
1986 pub fn wrapping_shl(self, rhs: u32) -> Self {
1987 self.overflowing_shl(rhs).0
1988 }
1989
1990 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1991 /// where `mask` removes any high-order bits of `rhs` that
1992 /// would cause the shift to exceed the bitwidth of the type.
1993 ///
1994 /// Note that this is *not* the same as a rotate-right; the
1995 /// RHS of a wrapping shift-right is restricted to the range
1996 /// of the type, rather than the bits shifted out of the LHS
1997 /// being returned to the other end. The primitive integer
1998 /// types all implement a `rotate_right` function, which may
1999 /// be what you want instead.
2000 ///
2001 /// # Examples
2002 ///
2003 /// Basic usage:
2004 ///
2005 /// ```
2006 /// assert_eq!(128u8.wrapping_shr(7), 1);
2007 /// assert_eq!(128u8.wrapping_shr(8), 128);
2008 /// ```
2009 #[stable(feature = "num_wrapping", since = "1.2.0")]
2010 #[inline(always)]
2011 pub fn wrapping_shr(self, rhs: u32) -> Self {
2012 self.overflowing_shr(rhs).0
2013 }
2014
2015 /// Calculates `self` + `rhs`
2016 ///
2017 /// Returns a tuple of the addition along with a boolean indicating
2018 /// whether an arithmetic overflow would occur. If an overflow would
2019 /// have occurred then the wrapped value is returned.
2020 ///
2021 /// # Examples
2022 ///
2023 /// Basic usage
2024 ///
2025 /// ```
2026 /// use std::u32;
2027 ///
2028 /// assert_eq!(5u32.overflowing_add(2), (7, false));
2029 /// assert_eq!(u32::MAX.overflowing_add(1), (0, true));
2030 /// ```
2031 #[inline]
2032 #[stable(feature = "wrapping", since = "1.7.0")]
2033 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
2034 unsafe {
2035 let (a, b) = $add_with_overflow(self as $ActualT,
2036 rhs as $ActualT);
2037 (a as Self, b)
2038 }
2039 }
2040
2041 /// Calculates `self` - `rhs`
2042 ///
2043 /// Returns a tuple of the subtraction along with a boolean indicating
2044 /// whether an arithmetic overflow would occur. If an overflow would
2045 /// have occurred then the wrapped value is returned.
2046 ///
2047 /// # Examples
2048 ///
2049 /// Basic usage
2050 ///
2051 /// ```
2052 /// use std::u32;
2053 ///
2054 /// assert_eq!(5u32.overflowing_sub(2), (3, false));
2055 /// assert_eq!(0u32.overflowing_sub(1), (u32::MAX, true));
2056 /// ```
2057 #[inline]
2058 #[stable(feature = "wrapping", since = "1.7.0")]
2059 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
2060 unsafe {
2061 let (a, b) = $sub_with_overflow(self as $ActualT,
2062 rhs as $ActualT);
2063 (a as Self, b)
2064 }
2065 }
2066
2067 /// Calculates the multiplication of `self` and `rhs`.
2068 ///
2069 /// Returns a tuple of the multiplication along with a boolean
2070 /// indicating whether an arithmetic overflow would occur. If an
2071 /// overflow would have occurred then the wrapped value is returned.
2072 ///
2073 /// # Examples
2074 ///
2075 /// Basic usage
2076 ///
2077 /// ```
2078 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
2079 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
2080 /// ```
2081 #[inline]
2082 #[stable(feature = "wrapping", since = "1.7.0")]
2083 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
2084 unsafe {
2085 let (a, b) = $mul_with_overflow(self as $ActualT,
2086 rhs as $ActualT);
2087 (a as Self, b)
2088 }
2089 }
2090
2091 /// Calculates the divisor when `self` is divided by `rhs`.
2092 ///
2093 /// Returns a tuple of the divisor along with a boolean indicating
2094 /// whether an arithmetic overflow would occur. Note that for unsigned
2095 /// integers overflow never occurs, so the second value is always
2096 /// `false`.
2097 ///
2098 /// # Panics
2099 ///
2100 /// This function will panic if `rhs` is 0.
2101 ///
2102 /// # Examples
2103 ///
2104 /// Basic usage
2105 ///
2106 /// ```
2107 /// assert_eq!(5u32.overflowing_div(2), (2, false));
2108 /// ```
2109 #[inline]
2110 #[stable(feature = "wrapping", since = "1.7.0")]
2111 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
2112 (self / rhs, false)
2113 }
2114
2115 /// Calculates the remainder when `self` is divided by `rhs`.
2116 ///
2117 /// Returns a tuple of the remainder after dividing along with a boolean
2118 /// indicating whether an arithmetic overflow would occur. Note that for
2119 /// unsigned integers overflow never occurs, so the second value is
2120 /// always `false`.
2121 ///
2122 /// # Panics
2123 ///
2124 /// This function will panic if `rhs` is 0.
2125 ///
2126 /// # Examples
2127 ///
2128 /// Basic usage
2129 ///
2130 /// ```
2131 /// assert_eq!(5u32.overflowing_rem(2), (1, false));
2132 /// ```
2133 #[inline]
2134 #[stable(feature = "wrapping", since = "1.7.0")]
2135 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
2136 (self % rhs, false)
2137 }
2138
2139 /// Negates self in an overflowing fashion.
2140 ///
2141 /// Returns `!self + 1` using wrapping operations to return the value
2142 /// that represents the negation of this unsigned value. Note that for
2143 /// positive unsigned values overflow always occurs, but negating 0 does
2144 /// not overflow.
2145 ///
2146 /// # Examples
2147 ///
2148 /// Basic usage
2149 ///
2150 /// ```
2151 /// assert_eq!(0u32.overflowing_neg(), (0, false));
2152 /// assert_eq!(2u32.overflowing_neg(), (-2i32 as u32, true));
2153 /// ```
2154 #[inline]
2155 #[stable(feature = "wrapping", since = "1.7.0")]
2156 pub fn overflowing_neg(self) -> (Self, bool) {
2157 ((!self).wrapping_add(1), self != 0)
2158 }
2159
2160 /// Shifts self left by `rhs` bits.
2161 ///
2162 /// Returns a tuple of the shifted version of self along with a boolean
2163 /// indicating whether the shift value was larger than or equal to the
2164 /// number of bits. If the shift value is too large, then value is
2165 /// masked (N-1) where N is the number of bits, and this value is then
2166 /// used to perform the shift.
2167 ///
2168 /// # Examples
2169 ///
2170 /// Basic usage
2171 ///
2172 /// ```
2173 /// assert_eq!(0x10u32.overflowing_shl(4), (0x100, false));
2174 /// assert_eq!(0x10u32.overflowing_shl(36), (0x100, true));
2175 /// ```
2176 #[inline]
2177 #[stable(feature = "wrapping", since = "1.7.0")]
2178 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
2179 (self << (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
2180 }
2181
2182 /// Shifts self right by `rhs` bits.
2183 ///
2184 /// Returns a tuple of the shifted version of self along with a boolean
2185 /// indicating whether the shift value was larger than or equal to the
2186 /// number of bits. If the shift value is too large, then value is
2187 /// masked (N-1) where N is the number of bits, and this value is then
2188 /// used to perform the shift.
2189 ///
2190 /// # Examples
2191 ///
2192 /// Basic usage
2193 ///
2194 /// ```
2195 /// assert_eq!(0x10u32.overflowing_shr(4), (0x1, false));
2196 /// assert_eq!(0x10u32.overflowing_shr(36), (0x1, true));
2197 /// ```
2198 #[inline]
2199 #[stable(feature = "wrapping", since = "1.7.0")]
2200 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
2201 (self >> (rhs & ($BITS - 1)), (rhs > ($BITS - 1)))
2202 }
2203
2204 /// Raises self to the power of `exp`, using exponentiation by squaring.
2205 ///
2206 /// # Examples
2207 ///
2208 /// Basic usage:
2209 ///
2210 /// ```
2211 /// assert_eq!(2u32.pow(4), 16);
2212 /// ```
2213 #[stable(feature = "rust1", since = "1.0.0")]
2214 #[inline]
2215 #[rustc_inherit_overflow_checks]
2216 pub fn pow(self, mut exp: u32) -> Self {
2217 let mut base = self;
2218 let mut acc = 1;
2219
2220 let mut prev_base = self;
2221 let mut base_oflo = false;
2222 while exp > 0 {
2223 if (exp & 1) == 1 {
2224 if base_oflo {
2225 // ensure overflow occurs in the same manner it
2226 // would have otherwise (i.e. signal any exception
2227 // it would have otherwise).
2228 acc = acc * (prev_base * prev_base);
2229 } else {
2230 acc = acc * base;
2231 }
2232 }
2233 prev_base = base;
2234 let (new_base, new_base_oflo) = base.overflowing_mul(base);
2235 base = new_base;
2236 base_oflo = new_base_oflo;
2237 exp /= 2;
2238 }
2239 acc
2240 }
2241
2242 /// Returns `true` if and only if `self == 2^k` for some `k`.
2243 ///
2244 /// # Examples
2245 ///
2246 /// Basic usage:
2247 ///
2248 /// ```
2249 /// assert!(16u8.is_power_of_two());
2250 /// assert!(!10u8.is_power_of_two());
2251 /// ```
2252 #[stable(feature = "rust1", since = "1.0.0")]
2253 #[inline]
2254 pub fn is_power_of_two(self) -> bool {
2255 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
2256 }
2257
2258 /// Returns the smallest power of two greater than or equal to `self`.
2259 /// Unspecified behavior on overflow.
2260 ///
2261 /// # Examples
2262 ///
2263 /// Basic usage:
2264 ///
2265 /// ```
2266 /// assert_eq!(2u8.next_power_of_two(), 2);
2267 /// assert_eq!(3u8.next_power_of_two(), 4);
2268 /// ```
2269 #[stable(feature = "rust1", since = "1.0.0")]
2270 #[inline]
2271 pub fn next_power_of_two(self) -> Self {
2272 let bits = size_of::<Self>() * 8;
2273 let one: Self = 1;
2274 one << ((bits - self.wrapping_sub(one).leading_zeros() as usize) % bits)
2275 }
2276
2277 /// Returns the smallest power of two greater than or equal to `n`. If
2278 /// the next power of two is greater than the type's maximum value,
2279 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2280 ///
2281 /// # Examples
2282 ///
2283 /// Basic usage:
2284 ///
2285 /// ```
2286 /// assert_eq!(2u8.checked_next_power_of_two(), Some(2));
2287 /// assert_eq!(3u8.checked_next_power_of_two(), Some(4));
2288 /// assert_eq!(200u8.checked_next_power_of_two(), None);
2289 /// ```
2290 #[stable(feature = "rust1", since = "1.0.0")]
2291 pub fn checked_next_power_of_two(self) -> Option<Self> {
2292 let npot = self.next_power_of_two();
2293 if npot >= self {
2294 Some(npot)
2295 } else {
2296 None
2297 }
2298 }
2299 }
2300 }
2301
2302 #[lang = "u8"]
2303 impl u8 {
2304 uint_impl! { u8, 8,
2305 intrinsics::ctpop,
2306 intrinsics::ctlz,
2307 intrinsics::cttz,
2308 intrinsics::bswap,
2309 intrinsics::add_with_overflow,
2310 intrinsics::sub_with_overflow,
2311 intrinsics::mul_with_overflow }
2312 }
2313
2314 #[lang = "u16"]
2315 impl u16 {
2316 uint_impl! { u16, 16,
2317 intrinsics::ctpop,
2318 intrinsics::ctlz,
2319 intrinsics::cttz,
2320 intrinsics::bswap,
2321 intrinsics::add_with_overflow,
2322 intrinsics::sub_with_overflow,
2323 intrinsics::mul_with_overflow }
2324 }
2325
2326 #[lang = "u32"]
2327 impl u32 {
2328 uint_impl! { u32, 32,
2329 intrinsics::ctpop,
2330 intrinsics::ctlz,
2331 intrinsics::cttz,
2332 intrinsics::bswap,
2333 intrinsics::add_with_overflow,
2334 intrinsics::sub_with_overflow,
2335 intrinsics::mul_with_overflow }
2336 }
2337
2338 #[lang = "u64"]
2339 impl u64 {
2340 uint_impl! { u64, 64,
2341 intrinsics::ctpop,
2342 intrinsics::ctlz,
2343 intrinsics::cttz,
2344 intrinsics::bswap,
2345 intrinsics::add_with_overflow,
2346 intrinsics::sub_with_overflow,
2347 intrinsics::mul_with_overflow }
2348 }
2349
2350 #[cfg(target_pointer_width = "16")]
2351 #[lang = "usize"]
2352 impl usize {
2353 uint_impl! { u16, 16,
2354 intrinsics::ctpop,
2355 intrinsics::ctlz,
2356 intrinsics::cttz,
2357 intrinsics::bswap,
2358 intrinsics::add_with_overflow,
2359 intrinsics::sub_with_overflow,
2360 intrinsics::mul_with_overflow }
2361 }
2362 #[cfg(target_pointer_width = "32")]
2363 #[lang = "usize"]
2364 impl usize {
2365 uint_impl! { u32, 32,
2366 intrinsics::ctpop,
2367 intrinsics::ctlz,
2368 intrinsics::cttz,
2369 intrinsics::bswap,
2370 intrinsics::add_with_overflow,
2371 intrinsics::sub_with_overflow,
2372 intrinsics::mul_with_overflow }
2373 }
2374
2375 #[cfg(target_pointer_width = "64")]
2376 #[lang = "usize"]
2377 impl usize {
2378 uint_impl! { u64, 64,
2379 intrinsics::ctpop,
2380 intrinsics::ctlz,
2381 intrinsics::cttz,
2382 intrinsics::bswap,
2383 intrinsics::add_with_overflow,
2384 intrinsics::sub_with_overflow,
2385 intrinsics::mul_with_overflow }
2386 }
2387
2388 /// A classification of floating point numbers.
2389 ///
2390 /// This `enum` is used as the return type for [`f32::classify()`] and [`f64::classify()`]. See
2391 /// their documentation for more.
2392 ///
2393 /// [`f32::classify()`]: ../../std/primitive.f32.html#method.classify
2394 /// [`f64::classify()`]: ../../std/primitive.f64.html#method.classify
2395 ///
2396 /// # Examples
2397 ///
2398 /// ```
2399 /// use std::num::FpCategory;
2400 /// use std::f32;
2401 ///
2402 /// let num = 12.4_f32;
2403 /// let inf = f32::INFINITY;
2404 /// let zero = 0f32;
2405 /// let sub: f32 = 1.1754942e-38;
2406 /// let nan = f32::NAN;
2407 ///
2408 /// assert_eq!(num.classify(), FpCategory::Normal);
2409 /// assert_eq!(inf.classify(), FpCategory::Infinite);
2410 /// assert_eq!(zero.classify(), FpCategory::Zero);
2411 /// assert_eq!(nan.classify(), FpCategory::Nan);
2412 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
2413 /// ```
2414 #[derive(Copy, Clone, PartialEq, Debug)]
2415 #[stable(feature = "rust1", since = "1.0.0")]
2416 pub enum FpCategory {
2417 /// "Not a Number", often obtained by dividing by zero.
2418 #[stable(feature = "rust1", since = "1.0.0")]
2419 Nan,
2420
2421 /// Positive or negative infinity.
2422 #[stable(feature = "rust1", since = "1.0.0")]
2423 Infinite ,
2424
2425 /// Positive or negative zero.
2426 #[stable(feature = "rust1", since = "1.0.0")]
2427 Zero,
2428
2429 /// De-normalized floating point representation (less precise than `Normal`).
2430 #[stable(feature = "rust1", since = "1.0.0")]
2431 Subnormal,
2432
2433 /// A regular floating point number.
2434 #[stable(feature = "rust1", since = "1.0.0")]
2435 Normal,
2436 }
2437
2438 /// A built-in floating point number.
2439 #[doc(hidden)]
2440 #[unstable(feature = "core_float",
2441 reason = "stable interface is via `impl f{32,64}` in later crates",
2442 issue = "32110")]
2443 pub trait Float: Sized {
2444 /// Returns the NaN value.
2445 #[unstable(feature = "float_extras", reason = "needs removal",
2446 issue = "27752")]
2447 #[rustc_deprecated(since = "1.11.0",
2448 reason = "never really came to fruition and easily \
2449 implementable outside the standard library")]
2450 fn nan() -> Self;
2451 /// Returns the infinite value.
2452 #[unstable(feature = "float_extras", reason = "needs removal",
2453 issue = "27752")]
2454 #[rustc_deprecated(since = "1.11.0",
2455 reason = "never really came to fruition and easily \
2456 implementable outside the standard library")]
2457 fn infinity() -> Self;
2458 /// Returns the negative infinite value.
2459 #[unstable(feature = "float_extras", reason = "needs removal",
2460 issue = "27752")]
2461 #[rustc_deprecated(since = "1.11.0",
2462 reason = "never really came to fruition and easily \
2463 implementable outside the standard library")]
2464 fn neg_infinity() -> Self;
2465 /// Returns -0.0.
2466 #[unstable(feature = "float_extras", reason = "needs removal",
2467 issue = "27752")]
2468 #[rustc_deprecated(since = "1.11.0",
2469 reason = "never really came to fruition and easily \
2470 implementable outside the standard library")]
2471 fn neg_zero() -> Self;
2472 /// Returns 0.0.
2473 #[unstable(feature = "float_extras", reason = "needs removal",
2474 issue = "27752")]
2475 #[rustc_deprecated(since = "1.11.0",
2476 reason = "never really came to fruition and easily \
2477 implementable outside the standard library")]
2478 fn zero() -> Self;
2479 /// Returns 1.0.
2480 #[unstable(feature = "float_extras", reason = "needs removal",
2481 issue = "27752")]
2482 #[rustc_deprecated(since = "1.11.0",
2483 reason = "never really came to fruition and easily \
2484 implementable outside the standard library")]
2485 fn one() -> Self;
2486
2487 /// Returns true if this value is NaN and false otherwise.
2488 #[stable(feature = "core", since = "1.6.0")]
2489 fn is_nan(self) -> bool;
2490 /// Returns true if this value is positive infinity or negative infinity and
2491 /// false otherwise.
2492 #[stable(feature = "core", since = "1.6.0")]
2493 fn is_infinite(self) -> bool;
2494 /// Returns true if this number is neither infinite nor NaN.
2495 #[stable(feature = "core", since = "1.6.0")]
2496 fn is_finite(self) -> bool;
2497 /// Returns true if this number is neither zero, infinite, denormal, or NaN.
2498 #[stable(feature = "core", since = "1.6.0")]
2499 fn is_normal(self) -> bool;
2500 /// Returns the category that this number falls into.
2501 #[stable(feature = "core", since = "1.6.0")]
2502 fn classify(self) -> FpCategory;
2503
2504 /// Returns the mantissa, exponent and sign as integers, respectively.
2505 #[unstable(feature = "float_extras", reason = "signature is undecided",
2506 issue = "27752")]
2507 #[rustc_deprecated(since = "1.11.0",
2508 reason = "never really came to fruition and easily \
2509 implementable outside the standard library")]
2510 fn integer_decode(self) -> (u64, i16, i8);
2511
2512 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
2513 /// number is `Float::nan()`.
2514 #[stable(feature = "core", since = "1.6.0")]
2515 fn abs(self) -> Self;
2516 /// Returns a number that represents the sign of `self`.
2517 ///
2518 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
2519 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
2520 /// - `Float::nan()` if the number is `Float::nan()`
2521 #[stable(feature = "core", since = "1.6.0")]
2522 fn signum(self) -> Self;
2523
2524 /// Returns `true` if `self` is positive, including `+0.0` and
2525 /// `Float::infinity()`.
2526 #[stable(feature = "core", since = "1.6.0")]
2527 fn is_sign_positive(self) -> bool;
2528 /// Returns `true` if `self` is negative, including `-0.0` and
2529 /// `Float::neg_infinity()`.
2530 #[stable(feature = "core", since = "1.6.0")]
2531 fn is_sign_negative(self) -> bool;
2532
2533 /// Take the reciprocal (inverse) of a number, `1/x`.
2534 #[stable(feature = "core", since = "1.6.0")]
2535 fn recip(self) -> Self;
2536
2537 /// Raise a number to an integer power.
2538 ///
2539 /// Using this function is generally faster than using `powf`
2540 #[stable(feature = "core", since = "1.6.0")]
2541 fn powi(self, n: i32) -> Self;
2542
2543 /// Convert radians to degrees.
2544 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
2545 fn to_degrees(self) -> Self;
2546 /// Convert degrees to radians.
2547 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
2548 fn to_radians(self) -> Self;
2549 }
2550
2551 macro_rules! from_str_radix_int_impl {
2552 ($($t:ty)*) => {$(
2553 #[stable(feature = "rust1", since = "1.0.0")]
2554 impl FromStr for $t {
2555 type Err = ParseIntError;
2556 fn from_str(src: &str) -> Result<Self, ParseIntError> {
2557 from_str_radix(src, 10)
2558 }
2559 }
2560 )*}
2561 }
2562 from_str_radix_int_impl! { isize i8 i16 i32 i64 usize u8 u16 u32 u64 }
2563
2564 /// The error type returned when a checked integral type conversion fails.
2565 #[unstable(feature = "try_from", issue = "33417")]
2566 #[derive(Debug, Copy, Clone)]
2567 pub struct TryFromIntError(());
2568
2569 impl TryFromIntError {
2570 #[unstable(feature = "int_error_internals",
2571 reason = "available through Error trait and this method should \
2572 not be exposed publicly",
2573 issue = "0")]
2574 #[doc(hidden)]
2575 pub fn __description(&self) -> &str {
2576 "out of range integral type conversion attempted"
2577 }
2578 }
2579
2580 #[unstable(feature = "try_from", issue = "33417")]
2581 impl fmt::Display for TryFromIntError {
2582 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2583 self.__description().fmt(fmt)
2584 }
2585 }
2586
2587 macro_rules! same_sign_from_int_impl {
2588 ($storage:ty, $target:ty, $($source:ty),*) => {$(
2589 #[stable(feature = "rust1", since = "1.0.0")]
2590 impl TryFrom<$source> for $target {
2591 type Err = TryFromIntError;
2592
2593 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
2594 let min = <$target as FromStrRadixHelper>::min_value() as $storage;
2595 let max = <$target as FromStrRadixHelper>::max_value() as $storage;
2596 if u as $storage < min || u as $storage > max {
2597 Err(TryFromIntError(()))
2598 } else {
2599 Ok(u as $target)
2600 }
2601 }
2602 }
2603 )*}
2604 }
2605
2606 same_sign_from_int_impl!(u64, u8, u8, u16, u32, u64, usize);
2607 same_sign_from_int_impl!(i64, i8, i8, i16, i32, i64, isize);
2608 same_sign_from_int_impl!(u64, u16, u8, u16, u32, u64, usize);
2609 same_sign_from_int_impl!(i64, i16, i8, i16, i32, i64, isize);
2610 same_sign_from_int_impl!(u64, u32, u8, u16, u32, u64, usize);
2611 same_sign_from_int_impl!(i64, i32, i8, i16, i32, i64, isize);
2612 same_sign_from_int_impl!(u64, u64, u8, u16, u32, u64, usize);
2613 same_sign_from_int_impl!(i64, i64, i8, i16, i32, i64, isize);
2614 same_sign_from_int_impl!(u64, usize, u8, u16, u32, u64, usize);
2615 same_sign_from_int_impl!(i64, isize, i8, i16, i32, i64, isize);
2616
2617 macro_rules! cross_sign_from_int_impl {
2618 ($unsigned:ty, $($signed:ty),*) => {$(
2619 #[stable(feature = "rust1", since = "1.0.0")]
2620 impl TryFrom<$unsigned> for $signed {
2621 type Err = TryFromIntError;
2622
2623 fn try_from(u: $unsigned) -> Result<$signed, TryFromIntError> {
2624 let max = <$signed as FromStrRadixHelper>::max_value() as u64;
2625 if u as u64 > max {
2626 Err(TryFromIntError(()))
2627 } else {
2628 Ok(u as $signed)
2629 }
2630 }
2631 }
2632
2633 #[stable(feature = "rust1", since = "1.0.0")]
2634 impl TryFrom<$signed> for $unsigned {
2635 type Err = TryFromIntError;
2636
2637 fn try_from(u: $signed) -> Result<$unsigned, TryFromIntError> {
2638 let max = <$unsigned as FromStrRadixHelper>::max_value() as u64;
2639 if u < 0 || u as u64 > max {
2640 Err(TryFromIntError(()))
2641 } else {
2642 Ok(u as $unsigned)
2643 }
2644 }
2645 }
2646 )*}
2647 }
2648
2649 cross_sign_from_int_impl!(u8, i8, i16, i32, i64, isize);
2650 cross_sign_from_int_impl!(u16, i8, i16, i32, i64, isize);
2651 cross_sign_from_int_impl!(u32, i8, i16, i32, i64, isize);
2652 cross_sign_from_int_impl!(u64, i8, i16, i32, i64, isize);
2653 cross_sign_from_int_impl!(usize, i8, i16, i32, i64, isize);
2654
2655 #[doc(hidden)]
2656 trait FromStrRadixHelper: PartialOrd + Copy {
2657 fn min_value() -> Self;
2658 fn max_value() -> Self;
2659 fn from_u32(u: u32) -> Self;
2660 fn checked_mul(&self, other: u32) -> Option<Self>;
2661 fn checked_sub(&self, other: u32) -> Option<Self>;
2662 fn checked_add(&self, other: u32) -> Option<Self>;
2663 }
2664
2665 macro_rules! doit {
2666 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
2667 fn min_value() -> Self { Self::min_value() }
2668 fn max_value() -> Self { Self::max_value() }
2669 fn from_u32(u: u32) -> Self { u as Self }
2670 fn checked_mul(&self, other: u32) -> Option<Self> {
2671 Self::checked_mul(*self, other as Self)
2672 }
2673 fn checked_sub(&self, other: u32) -> Option<Self> {
2674 Self::checked_sub(*self, other as Self)
2675 }
2676 fn checked_add(&self, other: u32) -> Option<Self> {
2677 Self::checked_add(*self, other as Self)
2678 }
2679 })*)
2680 }
2681 doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize }
2682
2683 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32)
2684 -> Result<T, ParseIntError> {
2685 use self::IntErrorKind::*;
2686 use self::ParseIntError as PIE;
2687
2688 assert!(radix >= 2 && radix <= 36,
2689 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
2690 radix);
2691
2692 if src.is_empty() {
2693 return Err(PIE { kind: Empty });
2694 }
2695
2696 let is_signed_ty = T::from_u32(0) > T::min_value();
2697
2698 // all valid digits are ascii, so we will just iterate over the utf8 bytes
2699 // and cast them to chars. .to_digit() will safely return None for anything
2700 // other than a valid ascii digit for the given radix, including the first-byte
2701 // of multi-byte sequences
2702 let src = src.as_bytes();
2703
2704 let (is_positive, digits) = match src[0] {
2705 b'+' => (true, &src[1..]),
2706 b'-' if is_signed_ty => (false, &src[1..]),
2707 _ => (true, src)
2708 };
2709
2710 if digits.is_empty() {
2711 return Err(PIE { kind: Empty });
2712 }
2713
2714 let mut result = T::from_u32(0);
2715 if is_positive {
2716 // The number is positive
2717 for &c in digits {
2718 let x = match (c as char).to_digit(radix) {
2719 Some(x) => x,
2720 None => return Err(PIE { kind: InvalidDigit }),
2721 };
2722 result = match result.checked_mul(radix) {
2723 Some(result) => result,
2724 None => return Err(PIE { kind: Overflow }),
2725 };
2726 result = match result.checked_add(x) {
2727 Some(result) => result,
2728 None => return Err(PIE { kind: Overflow }),
2729 };
2730 }
2731 } else {
2732 // The number is negative
2733 for &c in digits {
2734 let x = match (c as char).to_digit(radix) {
2735 Some(x) => x,
2736 None => return Err(PIE { kind: InvalidDigit }),
2737 };
2738 result = match result.checked_mul(radix) {
2739 Some(result) => result,
2740 None => return Err(PIE { kind: Underflow }),
2741 };
2742 result = match result.checked_sub(x) {
2743 Some(result) => result,
2744 None => return Err(PIE { kind: Underflow }),
2745 };
2746 }
2747 }
2748 Ok(result)
2749 }
2750
2751 /// An error which can be returned when parsing an integer.
2752 ///
2753 /// This error is used as the error type for the `from_str_radix()` functions
2754 /// on the primitive integer types, such as [`i8::from_str_radix()`].
2755 ///
2756 /// [`i8::from_str_radix()`]: ../../std/primitive.i8.html#method.from_str_radix
2757 #[derive(Debug, Clone, PartialEq)]
2758 #[stable(feature = "rust1", since = "1.0.0")]
2759 pub struct ParseIntError { kind: IntErrorKind }
2760
2761 #[derive(Debug, Clone, PartialEq)]
2762 enum IntErrorKind {
2763 Empty,
2764 InvalidDigit,
2765 Overflow,
2766 Underflow,
2767 }
2768
2769 impl ParseIntError {
2770 #[unstable(feature = "int_error_internals",
2771 reason = "available through Error trait and this method should \
2772 not be exposed publicly",
2773 issue = "0")]
2774 #[doc(hidden)]
2775 pub fn __description(&self) -> &str {
2776 match self.kind {
2777 IntErrorKind::Empty => "cannot parse integer from empty string",
2778 IntErrorKind::InvalidDigit => "invalid digit found in string",
2779 IntErrorKind::Overflow => "number too large to fit in target type",
2780 IntErrorKind::Underflow => "number too small to fit in target type",
2781 }
2782 }
2783 }
2784
2785 #[stable(feature = "rust1", since = "1.0.0")]
2786 impl fmt::Display for ParseIntError {
2787 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2788 self.__description().fmt(f)
2789 }
2790 }
2791
2792 #[stable(feature = "rust1", since = "1.0.0")]
2793 pub use num::dec2flt::ParseFloatError;
2794
2795 // Conversion traits for primitive integer and float types
2796 // Conversions T -> T are covered by a blanket impl and therefore excluded
2797 // Some conversions from and to usize/isize are not implemented due to portability concerns
2798 macro_rules! impl_from {
2799 ($Small: ty, $Large: ty) => {
2800 #[stable(feature = "lossless_prim_conv", since = "1.5.0")]
2801 impl From<$Small> for $Large {
2802 #[inline]
2803 fn from(small: $Small) -> $Large {
2804 small as $Large
2805 }
2806 }
2807 }
2808 }
2809
2810 // Unsigned -> Unsigned
2811 impl_from! { u8, u16 }
2812 impl_from! { u8, u32 }
2813 impl_from! { u8, u64 }
2814 impl_from! { u8, usize }
2815 impl_from! { u16, u32 }
2816 impl_from! { u16, u64 }
2817 impl_from! { u32, u64 }
2818
2819 // Signed -> Signed
2820 impl_from! { i8, i16 }
2821 impl_from! { i8, i32 }
2822 impl_from! { i8, i64 }
2823 impl_from! { i8, isize }
2824 impl_from! { i16, i32 }
2825 impl_from! { i16, i64 }
2826 impl_from! { i32, i64 }
2827
2828 // Unsigned -> Signed
2829 impl_from! { u8, i16 }
2830 impl_from! { u8, i32 }
2831 impl_from! { u8, i64 }
2832 impl_from! { u16, i32 }
2833 impl_from! { u16, i64 }
2834 impl_from! { u32, i64 }
2835
2836 // Note: integers can only be represented with full precision in a float if
2837 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
2838 // Lossy float conversions are not implemented at this time.
2839
2840 // Signed -> Float
2841 impl_from! { i8, f32 }
2842 impl_from! { i8, f64 }
2843 impl_from! { i16, f32 }
2844 impl_from! { i16, f64 }
2845 impl_from! { i32, f64 }
2846
2847 // Unsigned -> Float
2848 impl_from! { u8, f32 }
2849 impl_from! { u8, f64 }
2850 impl_from! { u16, f32 }
2851 impl_from! { u16, f64 }
2852 impl_from! { u32, f64 }
2853
2854 // Float -> Float
2855 impl_from! { f32, f64 }