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