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