]> git.proxmox.com Git - rustc.git/blob - src/libcore/num/mod.rs
1fae88b9c7775aa341304aaf6ca67ccfb3c35e39
[rustc.git] / src / libcore / num / mod.rs
1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Numeric traits and functions for the built-in numeric types.
12
13 #![stable(feature = "rust1", since = "1.0.0")]
14
15 use convert::{Infallible, TryFrom};
16 use fmt;
17 use intrinsics;
18 use ops;
19 use str::FromStr;
20
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.
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 /// ```
44 #[stable(feature = "rust1", since = "1.0.0")]
45 #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Default, Hash)]
46 pub struct Wrapping<T>(#[stable(feature = "rust1", since = "1.0.0")]
47 pub T);
48
49 #[stable(feature = "rust1", since = "1.0.0")]
50 impl<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")]
57 impl<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
63 #[stable(feature = "wrapping_fmt", since = "1.11.0")]
64 impl<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")]
71 impl<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")]
78 impl<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")]
85 impl<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
91 mod wrapping;
92
93 // All these modules are technically private and only exposed for coretests:
94 pub mod flt2dec;
95 pub mod dec2flt;
96 pub mod bignum;
97 pub mod diy_float;
98
99 // `Int` + `SignedInt` implemented for signed integers
100 macro_rules! int_impl {
101 ($SelfT:ty, $ActualT:ident, $UnsignedT:ty, $BITS:expr) => {
102 /// Returns the smallest value that can be represented by this integer type.
103 ///
104 /// # Examples
105 ///
106 /// Basic usage:
107 ///
108 /// ```
109 /// assert_eq!(i8::min_value(), -128);
110 /// ```
111 #[stable(feature = "rust1", since = "1.0.0")]
112 #[inline]
113 pub const fn min_value() -> Self {
114 !0 ^ ((!0 as $UnsignedT) >> 1) as Self
115 }
116
117 /// Returns the largest value that can be represented by this integer type.
118 ///
119 /// # Examples
120 ///
121 /// Basic usage:
122 ///
123 /// ```
124 /// assert_eq!(i8::max_value(), 127);
125 /// ```
126 #[stable(feature = "rust1", since = "1.0.0")]
127 #[inline]
128 pub const fn max_value() -> Self {
129 !Self::min_value()
130 }
131
132 /// Converts a string slice in a given base to an integer.
133 ///
134 /// The string is expected to be an optional `+` or `-` sign
135 /// followed by digits.
136 /// Leading and trailing whitespace represent an error.
137 /// Digits are a subset of these characters, depending on `radix`:
138 ///
139 /// * `0-9`
140 /// * `a-z`
141 /// * `A-Z`
142 ///
143 /// # Panics
144 ///
145 /// This function panics if `radix` is not in the range from 2 to 36.
146 ///
147 /// # Examples
148 ///
149 /// Basic usage:
150 ///
151 /// ```
152 /// assert_eq!(i32::from_str_radix("A", 16), Ok(10));
153 /// ```
154 #[stable(feature = "rust1", since = "1.0.0")]
155 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
156 from_str_radix(src, radix)
157 }
158
159 /// Returns the number of ones in the binary representation of `self`.
160 ///
161 /// # Examples
162 ///
163 /// Basic usage:
164 ///
165 /// ```
166 /// let n = -0b1000_0000i8;
167 ///
168 /// assert_eq!(n.count_ones(), 1);
169 /// ```
170 #[stable(feature = "rust1", since = "1.0.0")]
171 #[inline]
172 pub fn count_ones(self) -> u32 { (self as $UnsignedT).count_ones() }
173
174 /// Returns the number of zeros in the binary representation of `self`.
175 ///
176 /// # Examples
177 ///
178 /// Basic usage:
179 ///
180 /// ```
181 /// let n = -0b1000_0000i8;
182 ///
183 /// assert_eq!(n.count_zeros(), 7);
184 /// ```
185 #[stable(feature = "rust1", since = "1.0.0")]
186 #[inline]
187 pub fn count_zeros(self) -> u32 {
188 (!self).count_ones()
189 }
190
191 /// Returns the number of leading zeros in the binary representation
192 /// of `self`.
193 ///
194 /// # Examples
195 ///
196 /// Basic usage:
197 ///
198 /// ```
199 /// let n = -1i16;
200 ///
201 /// assert_eq!(n.leading_zeros(), 0);
202 /// ```
203 #[stable(feature = "rust1", since = "1.0.0")]
204 #[inline]
205 pub fn leading_zeros(self) -> u32 {
206 (self as $UnsignedT).leading_zeros()
207 }
208
209 /// Returns the number of trailing zeros in the binary representation
210 /// of `self`.
211 ///
212 /// # Examples
213 ///
214 /// Basic usage:
215 ///
216 /// ```
217 /// let n = -4i8;
218 ///
219 /// assert_eq!(n.trailing_zeros(), 2);
220 /// ```
221 #[stable(feature = "rust1", since = "1.0.0")]
222 #[inline]
223 pub fn trailing_zeros(self) -> u32 {
224 (self as $UnsignedT).trailing_zeros()
225 }
226
227 /// Shifts the bits to the left by a specified amount, `n`,
228 /// wrapping the truncated bits to the end of the resulting integer.
229 ///
230 /// Please note this isn't the same operation as `<<`!
231 ///
232 /// # Examples
233 ///
234 /// Basic usage:
235 ///
236 /// ```
237 /// let n = 0x0123456789ABCDEFi64;
238 /// let m = -0x76543210FEDCBA99i64;
239 ///
240 /// assert_eq!(n.rotate_left(32), m);
241 /// ```
242 #[stable(feature = "rust1", since = "1.0.0")]
243 #[inline]
244 pub fn rotate_left(self, n: u32) -> Self {
245 (self as $UnsignedT).rotate_left(n) as Self
246 }
247
248 /// Shifts the bits to the right by a specified amount, `n`,
249 /// wrapping the truncated bits to the beginning of the resulting
250 /// integer.
251 ///
252 /// Please note this isn't the same operation as `>>`!
253 ///
254 /// # Examples
255 ///
256 /// Basic usage:
257 ///
258 /// ```
259 /// let n = 0x0123456789ABCDEFi64;
260 /// let m = -0xFEDCBA987654322i64;
261 ///
262 /// assert_eq!(n.rotate_right(4), m);
263 /// ```
264 #[stable(feature = "rust1", since = "1.0.0")]
265 #[inline]
266 pub fn rotate_right(self, n: u32) -> Self {
267 (self as $UnsignedT).rotate_right(n) as Self
268 }
269
270 /// Reverses the byte order of the integer.
271 ///
272 /// # Examples
273 ///
274 /// Basic usage:
275 ///
276 /// ```
277 /// let n: i16 = 0b0000000_01010101;
278 /// assert_eq!(n, 85);
279 ///
280 /// let m = n.swap_bytes();
281 ///
282 /// assert_eq!(m, 0b01010101_00000000);
283 /// assert_eq!(m, 21760);
284 /// ```
285 #[stable(feature = "rust1", since = "1.0.0")]
286 #[inline]
287 pub fn swap_bytes(self) -> Self {
288 (self as $UnsignedT).swap_bytes() as Self
289 }
290
291 /// Converts an integer from big endian to the target's endianness.
292 ///
293 /// On big endian this is a no-op. On little endian the bytes are
294 /// swapped.
295 ///
296 /// # Examples
297 ///
298 /// Basic usage:
299 ///
300 /// ```
301 /// let n = 0x0123456789ABCDEFi64;
302 ///
303 /// if cfg!(target_endian = "big") {
304 /// assert_eq!(i64::from_be(n), n)
305 /// } else {
306 /// assert_eq!(i64::from_be(n), n.swap_bytes())
307 /// }
308 /// ```
309 #[stable(feature = "rust1", since = "1.0.0")]
310 #[inline]
311 pub fn from_be(x: Self) -> Self {
312 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
313 }
314
315 /// Converts an integer from little endian to the target's endianness.
316 ///
317 /// On little endian this is a no-op. On big endian the bytes are
318 /// swapped.
319 ///
320 /// # Examples
321 ///
322 /// Basic usage:
323 ///
324 /// ```
325 /// let n = 0x0123456789ABCDEFi64;
326 ///
327 /// if cfg!(target_endian = "little") {
328 /// assert_eq!(i64::from_le(n), n)
329 /// } else {
330 /// assert_eq!(i64::from_le(n), n.swap_bytes())
331 /// }
332 /// ```
333 #[stable(feature = "rust1", since = "1.0.0")]
334 #[inline]
335 pub fn from_le(x: Self) -> Self {
336 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
337 }
338
339 /// Converts `self` to big endian from the target's endianness.
340 ///
341 /// On big endian this is a no-op. On little endian the bytes are
342 /// swapped.
343 ///
344 /// # Examples
345 ///
346 /// Basic usage:
347 ///
348 /// ```
349 /// let n = 0x0123456789ABCDEFi64;
350 ///
351 /// if cfg!(target_endian = "big") {
352 /// assert_eq!(n.to_be(), n)
353 /// } else {
354 /// assert_eq!(n.to_be(), n.swap_bytes())
355 /// }
356 /// ```
357 #[stable(feature = "rust1", since = "1.0.0")]
358 #[inline]
359 pub fn to_be(self) -> Self { // or not to be?
360 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
361 }
362
363 /// Converts `self` to little endian from the target's endianness.
364 ///
365 /// On little endian this is a no-op. On big endian the bytes are
366 /// swapped.
367 ///
368 /// # Examples
369 ///
370 /// Basic usage:
371 ///
372 /// ```
373 /// let n = 0x0123456789ABCDEFi64;
374 ///
375 /// if cfg!(target_endian = "little") {
376 /// assert_eq!(n.to_le(), n)
377 /// } else {
378 /// assert_eq!(n.to_le(), n.swap_bytes())
379 /// }
380 /// ```
381 #[stable(feature = "rust1", since = "1.0.0")]
382 #[inline]
383 pub fn to_le(self) -> Self {
384 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
385 }
386
387 /// Checked integer addition. Computes `self + rhs`, returning `None`
388 /// if overflow occurred.
389 ///
390 /// # Examples
391 ///
392 /// Basic usage:
393 ///
394 /// ```
395 /// assert_eq!(7i16.checked_add(32760), Some(32767));
396 /// assert_eq!(8i16.checked_add(32760), None);
397 /// ```
398 #[stable(feature = "rust1", since = "1.0.0")]
399 #[inline]
400 pub fn checked_add(self, rhs: Self) -> Option<Self> {
401 let (a, b) = self.overflowing_add(rhs);
402 if b {None} else {Some(a)}
403 }
404
405 /// Checked integer subtraction. Computes `self - rhs`, returning
406 /// `None` if overflow occurred.
407 ///
408 /// # Examples
409 ///
410 /// Basic usage:
411 ///
412 /// ```
413 /// assert_eq!((-127i8).checked_sub(1), Some(-128));
414 /// assert_eq!((-128i8).checked_sub(1), None);
415 /// ```
416 #[stable(feature = "rust1", since = "1.0.0")]
417 #[inline]
418 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
419 let (a, b) = self.overflowing_sub(rhs);
420 if b {None} else {Some(a)}
421 }
422
423 /// Checked integer multiplication. Computes `self * rhs`, returning
424 /// `None` if overflow occurred.
425 ///
426 /// # Examples
427 ///
428 /// Basic usage:
429 ///
430 /// ```
431 /// assert_eq!(6i8.checked_mul(21), Some(126));
432 /// assert_eq!(6i8.checked_mul(22), None);
433 /// ```
434 #[stable(feature = "rust1", since = "1.0.0")]
435 #[inline]
436 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
437 let (a, b) = self.overflowing_mul(rhs);
438 if b {None} else {Some(a)}
439 }
440
441 /// Checked integer division. Computes `self / rhs`, returning `None`
442 /// if `rhs == 0` or the division results in overflow.
443 ///
444 /// # Examples
445 ///
446 /// Basic usage:
447 ///
448 /// ```
449 /// assert_eq!((-127i8).checked_div(-1), Some(127));
450 /// assert_eq!((-128i8).checked_div(-1), None);
451 /// assert_eq!((1i8).checked_div(0), None);
452 /// ```
453 #[stable(feature = "rust1", since = "1.0.0")]
454 #[inline]
455 pub fn checked_div(self, rhs: Self) -> Option<Self> {
456 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
457 None
458 } else {
459 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
460 }
461 }
462
463 /// Checked integer remainder. Computes `self % rhs`, returning `None`
464 /// if `rhs == 0` or the division results in overflow.
465 ///
466 /// # Examples
467 ///
468 /// Basic usage:
469 ///
470 /// ```
471 /// use std::i32;
472 ///
473 /// assert_eq!(5i32.checked_rem(2), Some(1));
474 /// assert_eq!(5i32.checked_rem(0), None);
475 /// assert_eq!(i32::MIN.checked_rem(-1), None);
476 /// ```
477 #[stable(feature = "wrapping", since = "1.7.0")]
478 #[inline]
479 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
480 if rhs == 0 || (self == Self::min_value() && rhs == -1) {
481 None
482 } else {
483 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
484 }
485 }
486
487 /// Checked negation. Computes `-self`, returning `None` if `self ==
488 /// MIN`.
489 ///
490 /// # Examples
491 ///
492 /// Basic usage:
493 ///
494 /// ```
495 /// use std::i32;
496 ///
497 /// assert_eq!(5i32.checked_neg(), Some(-5));
498 /// assert_eq!(i32::MIN.checked_neg(), None);
499 /// ```
500 #[stable(feature = "wrapping", since = "1.7.0")]
501 #[inline]
502 pub fn checked_neg(self) -> Option<Self> {
503 let (a, b) = self.overflowing_neg();
504 if b {None} else {Some(a)}
505 }
506
507 /// Checked shift left. Computes `self << rhs`, returning `None`
508 /// if `rhs` is larger than or equal to the number of bits in `self`.
509 ///
510 /// # Examples
511 ///
512 /// Basic usage:
513 ///
514 /// ```
515 /// assert_eq!(0x10i32.checked_shl(4), Some(0x100));
516 /// assert_eq!(0x10i32.checked_shl(33), None);
517 /// ```
518 #[stable(feature = "wrapping", since = "1.7.0")]
519 #[inline]
520 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
521 let (a, b) = self.overflowing_shl(rhs);
522 if b {None} else {Some(a)}
523 }
524
525 /// Checked shift right. Computes `self >> rhs`, returning `None`
526 /// if `rhs` is larger than or equal to the number of bits in `self`.
527 ///
528 /// # Examples
529 ///
530 /// Basic usage:
531 ///
532 /// ```
533 /// assert_eq!(0x10i32.checked_shr(4), Some(0x1));
534 /// assert_eq!(0x10i32.checked_shr(33), None);
535 /// ```
536 #[stable(feature = "wrapping", since = "1.7.0")]
537 #[inline]
538 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
539 let (a, b) = self.overflowing_shr(rhs);
540 if b {None} else {Some(a)}
541 }
542
543 /// Checked absolute value. Computes `self.abs()`, returning `None` if
544 /// `self == MIN`.
545 ///
546 /// # Examples
547 ///
548 /// Basic usage:
549 ///
550 /// ```
551 /// use std::i32;
552 ///
553 /// assert_eq!((-5i32).checked_abs(), Some(5));
554 /// assert_eq!(i32::MIN.checked_abs(), None);
555 /// ```
556 #[stable(feature = "no_panic_abs", since = "1.13.0")]
557 #[inline]
558 pub fn checked_abs(self) -> Option<Self> {
559 if self.is_negative() {
560 self.checked_neg()
561 } else {
562 Some(self)
563 }
564 }
565
566 /// Saturating integer addition. Computes `self + rhs`, saturating at
567 /// the numeric bounds instead of overflowing.
568 ///
569 /// # Examples
570 ///
571 /// Basic usage:
572 ///
573 /// ```
574 /// assert_eq!(100i8.saturating_add(1), 101);
575 /// assert_eq!(100i8.saturating_add(127), 127);
576 /// ```
577 #[stable(feature = "rust1", since = "1.0.0")]
578 #[inline]
579 pub fn saturating_add(self, rhs: Self) -> Self {
580 match self.checked_add(rhs) {
581 Some(x) => x,
582 None if rhs >= 0 => Self::max_value(),
583 None => Self::min_value(),
584 }
585 }
586
587 /// Saturating integer subtraction. Computes `self - rhs`, saturating
588 /// at the numeric bounds instead of overflowing.
589 ///
590 /// # Examples
591 ///
592 /// Basic usage:
593 ///
594 /// ```
595 /// assert_eq!(100i8.saturating_sub(127), -27);
596 /// assert_eq!((-100i8).saturating_sub(127), -128);
597 /// ```
598 #[stable(feature = "rust1", since = "1.0.0")]
599 #[inline]
600 pub fn saturating_sub(self, rhs: Self) -> Self {
601 match self.checked_sub(rhs) {
602 Some(x) => x,
603 None if rhs >= 0 => Self::min_value(),
604 None => Self::max_value(),
605 }
606 }
607
608 /// Saturating integer multiplication. Computes `self * rhs`,
609 /// saturating at the numeric bounds instead of overflowing.
610 ///
611 /// # Examples
612 ///
613 /// Basic usage:
614 ///
615 /// ```
616 /// use std::i32;
617 ///
618 /// assert_eq!(100i32.saturating_mul(127), 12700);
619 /// assert_eq!((1i32 << 23).saturating_mul(1 << 23), i32::MAX);
620 /// assert_eq!((-1i32 << 23).saturating_mul(1 << 23), i32::MIN);
621 /// ```
622 #[stable(feature = "wrapping", since = "1.7.0")]
623 #[inline]
624 pub fn saturating_mul(self, rhs: Self) -> Self {
625 self.checked_mul(rhs).unwrap_or_else(|| {
626 if (self < 0 && rhs < 0) || (self > 0 && rhs > 0) {
627 Self::max_value()
628 } else {
629 Self::min_value()
630 }
631 })
632 }
633
634 /// Wrapping (modular) addition. Computes `self + rhs`,
635 /// wrapping around at the boundary of the type.
636 ///
637 /// # Examples
638 ///
639 /// Basic usage:
640 ///
641 /// ```
642 /// assert_eq!(100i8.wrapping_add(27), 127);
643 /// assert_eq!(100i8.wrapping_add(127), -29);
644 /// ```
645 #[stable(feature = "rust1", since = "1.0.0")]
646 #[inline]
647 pub fn wrapping_add(self, rhs: Self) -> Self {
648 unsafe {
649 intrinsics::overflowing_add(self, rhs)
650 }
651 }
652
653 /// Wrapping (modular) subtraction. Computes `self - rhs`,
654 /// wrapping around at the boundary of the type.
655 ///
656 /// # Examples
657 ///
658 /// Basic usage:
659 ///
660 /// ```
661 /// assert_eq!(0i8.wrapping_sub(127), -127);
662 /// assert_eq!((-2i8).wrapping_sub(127), 127);
663 /// ```
664 #[stable(feature = "rust1", since = "1.0.0")]
665 #[inline]
666 pub fn wrapping_sub(self, rhs: Self) -> Self {
667 unsafe {
668 intrinsics::overflowing_sub(self, rhs)
669 }
670 }
671
672 /// Wrapping (modular) multiplication. Computes `self *
673 /// rhs`, wrapping around at the boundary of the type.
674 ///
675 /// # Examples
676 ///
677 /// Basic usage:
678 ///
679 /// ```
680 /// assert_eq!(10i8.wrapping_mul(12), 120);
681 /// assert_eq!(11i8.wrapping_mul(12), -124);
682 /// ```
683 #[stable(feature = "rust1", since = "1.0.0")]
684 #[inline]
685 pub fn wrapping_mul(self, rhs: Self) -> Self {
686 unsafe {
687 intrinsics::overflowing_mul(self, rhs)
688 }
689 }
690
691 /// Wrapping (modular) division. Computes `self / rhs`,
692 /// wrapping around at the boundary of the type.
693 ///
694 /// The only case where such wrapping can occur is when one
695 /// divides `MIN / -1` on a signed type (where `MIN` is the
696 /// negative minimal value for the type); this is equivalent
697 /// to `-MIN`, a positive value that is too large to represent
698 /// in the type. In such a case, this function returns `MIN`
699 /// itself.
700 ///
701 /// # Panics
702 ///
703 /// This function will panic if `rhs` is 0.
704 ///
705 /// # Examples
706 ///
707 /// Basic usage:
708 ///
709 /// ```
710 /// assert_eq!(100u8.wrapping_div(10), 10);
711 /// assert_eq!((-128i8).wrapping_div(-1), -128);
712 /// ```
713 #[stable(feature = "num_wrapping", since = "1.2.0")]
714 #[inline]
715 pub fn wrapping_div(self, rhs: Self) -> Self {
716 self.overflowing_div(rhs).0
717 }
718
719 /// Wrapping (modular) remainder. Computes `self % rhs`,
720 /// wrapping around at the boundary of the type.
721 ///
722 /// Such wrap-around never actually occurs mathematically;
723 /// implementation artifacts make `x % y` invalid for `MIN /
724 /// -1` on a signed type (where `MIN` is the negative
725 /// minimal value). In such a case, this function returns `0`.
726 ///
727 /// # Panics
728 ///
729 /// This function will panic if `rhs` is 0.
730 ///
731 /// # Examples
732 ///
733 /// Basic usage:
734 ///
735 /// ```
736 /// assert_eq!(100i8.wrapping_rem(10), 0);
737 /// assert_eq!((-128i8).wrapping_rem(-1), 0);
738 /// ```
739 #[stable(feature = "num_wrapping", since = "1.2.0")]
740 #[inline]
741 pub fn wrapping_rem(self, rhs: Self) -> Self {
742 self.overflowing_rem(rhs).0
743 }
744
745 /// Wrapping (modular) negation. Computes `-self`,
746 /// wrapping around at the boundary of the type.
747 ///
748 /// The only case where such wrapping can occur is when one
749 /// negates `MIN` on a signed type (where `MIN` is the
750 /// negative minimal value for the type); this is a positive
751 /// value that is too large to represent in the type. In such
752 /// a case, this function returns `MIN` itself.
753 ///
754 /// # Examples
755 ///
756 /// Basic usage:
757 ///
758 /// ```
759 /// assert_eq!(100i8.wrapping_neg(), -100);
760 /// assert_eq!((-128i8).wrapping_neg(), -128);
761 /// ```
762 #[stable(feature = "num_wrapping", since = "1.2.0")]
763 #[inline]
764 pub fn wrapping_neg(self) -> Self {
765 self.overflowing_neg().0
766 }
767
768 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
769 /// where `mask` removes any high-order bits of `rhs` that
770 /// would cause the shift to exceed the bitwidth of the type.
771 ///
772 /// Note that this is *not* the same as a rotate-left; the
773 /// RHS of a wrapping shift-left is restricted to the range
774 /// of the type, rather than the bits shifted out of the LHS
775 /// being returned to the other end. The primitive integer
776 /// types all implement a `rotate_left` function, which may
777 /// be what you want instead.
778 ///
779 /// # Examples
780 ///
781 /// Basic usage:
782 ///
783 /// ```
784 /// assert_eq!((-1i8).wrapping_shl(7), -128);
785 /// assert_eq!((-1i8).wrapping_shl(8), -1);
786 /// ```
787 #[stable(feature = "num_wrapping", since = "1.2.0")]
788 #[inline]
789 pub fn wrapping_shl(self, rhs: u32) -> Self {
790 unsafe {
791 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
792 }
793 }
794
795 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
796 /// where `mask` removes any high-order bits of `rhs` that
797 /// would cause the shift to exceed the bitwidth of the type.
798 ///
799 /// Note that this is *not* the same as a rotate-right; the
800 /// RHS of a wrapping shift-right is restricted to the range
801 /// of the type, rather than the bits shifted out of the LHS
802 /// being returned to the other end. The primitive integer
803 /// types all implement a `rotate_right` function, which may
804 /// be what you want instead.
805 ///
806 /// # Examples
807 ///
808 /// Basic usage:
809 ///
810 /// ```
811 /// assert_eq!((-128i8).wrapping_shr(7), -1);
812 /// assert_eq!((-128i8).wrapping_shr(8), -128);
813 /// ```
814 #[stable(feature = "num_wrapping", since = "1.2.0")]
815 #[inline]
816 pub fn wrapping_shr(self, rhs: u32) -> Self {
817 unsafe {
818 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
819 }
820 }
821
822 /// Wrapping (modular) absolute value. Computes `self.abs()`,
823 /// wrapping around at the boundary of the type.
824 ///
825 /// The only case where such wrapping can occur is when one takes
826 /// the absolute value of the negative minimal value for the type
827 /// this is a positive value that is too large to represent in the
828 /// type. In such a case, this function returns `MIN` itself.
829 ///
830 /// # Examples
831 ///
832 /// Basic usage:
833 ///
834 /// ```
835 /// assert_eq!(100i8.wrapping_abs(), 100);
836 /// assert_eq!((-100i8).wrapping_abs(), 100);
837 /// assert_eq!((-128i8).wrapping_abs(), -128);
838 /// assert_eq!((-128i8).wrapping_abs() as u8, 128);
839 /// ```
840 #[stable(feature = "no_panic_abs", since = "1.13.0")]
841 #[inline]
842 pub fn wrapping_abs(self) -> Self {
843 if self.is_negative() {
844 self.wrapping_neg()
845 } else {
846 self
847 }
848 }
849
850 /// Calculates `self` + `rhs`
851 ///
852 /// Returns a tuple of the addition along with a boolean indicating
853 /// whether an arithmetic overflow would occur. If an overflow would
854 /// have occurred then the wrapped value is returned.
855 ///
856 /// # Examples
857 ///
858 /// Basic usage
859 ///
860 /// ```
861 /// use std::i32;
862 ///
863 /// assert_eq!(5i32.overflowing_add(2), (7, false));
864 /// assert_eq!(i32::MAX.overflowing_add(1), (i32::MIN, true));
865 /// ```
866 #[inline]
867 #[stable(feature = "wrapping", since = "1.7.0")]
868 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
869 let (a, b) = unsafe {
870 intrinsics::add_with_overflow(self as $ActualT,
871 rhs as $ActualT)
872 };
873 (a as Self, b)
874 }
875
876 /// Calculates `self` - `rhs`
877 ///
878 /// Returns a tuple of the subtraction along with a boolean indicating
879 /// whether an arithmetic overflow would occur. If an overflow would
880 /// have occurred then the wrapped value is returned.
881 ///
882 /// # Examples
883 ///
884 /// Basic usage
885 ///
886 /// ```
887 /// use std::i32;
888 ///
889 /// assert_eq!(5i32.overflowing_sub(2), (3, false));
890 /// assert_eq!(i32::MIN.overflowing_sub(1), (i32::MAX, true));
891 /// ```
892 #[inline]
893 #[stable(feature = "wrapping", since = "1.7.0")]
894 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
895 let (a, b) = unsafe {
896 intrinsics::sub_with_overflow(self as $ActualT,
897 rhs as $ActualT)
898 };
899 (a as Self, b)
900 }
901
902 /// Calculates the multiplication of `self` and `rhs`.
903 ///
904 /// Returns a tuple of the multiplication along with a boolean
905 /// indicating whether an arithmetic overflow would occur. If an
906 /// overflow would have occurred then the wrapped value is returned.
907 ///
908 /// # Examples
909 ///
910 /// Basic usage
911 ///
912 /// ```
913 /// assert_eq!(5i32.overflowing_mul(2), (10, false));
914 /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
915 /// ```
916 #[inline]
917 #[stable(feature = "wrapping", since = "1.7.0")]
918 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
919 let (a, b) = unsafe {
920 intrinsics::mul_with_overflow(self as $ActualT,
921 rhs as $ActualT)
922 };
923 (a as Self, b)
924 }
925
926 /// Calculates the divisor when `self` is divided by `rhs`.
927 ///
928 /// Returns a tuple of the divisor along with a boolean indicating
929 /// whether an arithmetic overflow would occur. If an overflow would
930 /// occur then self is returned.
931 ///
932 /// # Panics
933 ///
934 /// This function will panic if `rhs` is 0.
935 ///
936 /// # Examples
937 ///
938 /// Basic usage
939 ///
940 /// ```
941 /// use std::i32;
942 ///
943 /// assert_eq!(5i32.overflowing_div(2), (2, false));
944 /// assert_eq!(i32::MIN.overflowing_div(-1), (i32::MIN, true));
945 /// ```
946 #[inline]
947 #[stable(feature = "wrapping", since = "1.7.0")]
948 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
949 if self == Self::min_value() && rhs == -1 {
950 (self, true)
951 } else {
952 (self / rhs, false)
953 }
954 }
955
956 /// Calculates the remainder when `self` is divided by `rhs`.
957 ///
958 /// Returns a tuple of the remainder after dividing along with a boolean
959 /// indicating whether an arithmetic overflow would occur. If an
960 /// overflow would occur then 0 is returned.
961 ///
962 /// # Panics
963 ///
964 /// This function will panic if `rhs` is 0.
965 ///
966 /// # Examples
967 ///
968 /// Basic usage
969 ///
970 /// ```
971 /// use std::i32;
972 ///
973 /// assert_eq!(5i32.overflowing_rem(2), (1, false));
974 /// assert_eq!(i32::MIN.overflowing_rem(-1), (0, true));
975 /// ```
976 #[inline]
977 #[stable(feature = "wrapping", since = "1.7.0")]
978 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
979 if self == Self::min_value() && rhs == -1 {
980 (0, true)
981 } else {
982 (self % rhs, false)
983 }
984 }
985
986 /// Negates self, overflowing if this is equal to the minimum value.
987 ///
988 /// Returns a tuple of the negated version of self along with a boolean
989 /// indicating whether an overflow happened. If `self` is the minimum
990 /// value (e.g. `i32::MIN` for values of type `i32`), then the minimum
991 /// value will be returned again and `true` will be returned for an
992 /// overflow happening.
993 ///
994 /// # Examples
995 ///
996 /// Basic usage
997 ///
998 /// ```
999 /// use std::i32;
1000 ///
1001 /// assert_eq!(2i32.overflowing_neg(), (-2, false));
1002 /// assert_eq!(i32::MIN.overflowing_neg(), (i32::MIN, true));
1003 /// ```
1004 #[inline]
1005 #[stable(feature = "wrapping", since = "1.7.0")]
1006 pub fn overflowing_neg(self) -> (Self, bool) {
1007 if self == Self::min_value() {
1008 (Self::min_value(), true)
1009 } else {
1010 (-self, false)
1011 }
1012 }
1013
1014 /// Shifts self left by `rhs` bits.
1015 ///
1016 /// Returns a tuple of the shifted version of self along with a boolean
1017 /// indicating whether the shift value was larger than or equal to the
1018 /// number of bits. If the shift value is too large, then value is
1019 /// masked (N-1) where N is the number of bits, and this value is then
1020 /// used to perform the shift.
1021 ///
1022 /// # Examples
1023 ///
1024 /// Basic usage
1025 ///
1026 /// ```
1027 /// assert_eq!(0x10i32.overflowing_shl(4), (0x100, false));
1028 /// assert_eq!(0x10i32.overflowing_shl(36), (0x100, true));
1029 /// ```
1030 #[inline]
1031 #[stable(feature = "wrapping", since = "1.7.0")]
1032 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
1033 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
1034 }
1035
1036 /// Shifts self right by `rhs` bits.
1037 ///
1038 /// Returns a tuple of the shifted version of self along with a boolean
1039 /// indicating whether the shift value was larger than or equal to the
1040 /// number of bits. If the shift value is too large, then value is
1041 /// masked (N-1) where N is the number of bits, and this value is then
1042 /// used to perform the shift.
1043 ///
1044 /// # Examples
1045 ///
1046 /// Basic usage
1047 ///
1048 /// ```
1049 /// assert_eq!(0x10i32.overflowing_shr(4), (0x1, false));
1050 /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
1051 /// ```
1052 #[inline]
1053 #[stable(feature = "wrapping", since = "1.7.0")]
1054 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
1055 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
1056 }
1057
1058 /// Computes the absolute value of `self`.
1059 ///
1060 /// Returns a tuple of the absolute version of self along with a
1061 /// boolean indicating whether an overflow happened. If self is the
1062 /// minimum value (e.g. i32::MIN for values of type i32), then the
1063 /// minimum value will be returned again and true will be returned for
1064 /// an overflow happening.
1065 ///
1066 /// # Examples
1067 ///
1068 /// Basic usage:
1069 ///
1070 /// ```
1071 /// assert_eq!(10i8.overflowing_abs(), (10,false));
1072 /// assert_eq!((-10i8).overflowing_abs(), (10,false));
1073 /// assert_eq!((-128i8).overflowing_abs(), (-128,true));
1074 /// ```
1075 #[stable(feature = "no_panic_abs", since = "1.13.0")]
1076 #[inline]
1077 pub fn overflowing_abs(self) -> (Self, bool) {
1078 if self.is_negative() {
1079 self.overflowing_neg()
1080 } else {
1081 (self, false)
1082 }
1083 }
1084
1085 /// Raises self to the power of `exp`, using exponentiation by squaring.
1086 ///
1087 /// # Examples
1088 ///
1089 /// Basic usage:
1090 ///
1091 /// ```
1092 /// let x: i32 = 2; // or any other integer type
1093 ///
1094 /// assert_eq!(x.pow(4), 16);
1095 /// ```
1096 #[stable(feature = "rust1", since = "1.0.0")]
1097 #[inline]
1098 #[rustc_inherit_overflow_checks]
1099 pub fn pow(self, mut exp: u32) -> Self {
1100 let mut base = self;
1101 let mut acc = 1;
1102
1103 while exp > 1 {
1104 if (exp & 1) == 1 {
1105 acc = acc * base;
1106 }
1107 exp /= 2;
1108 base = base * base;
1109 }
1110
1111 // Deal with the final bit of the exponent separately, since
1112 // squaring the base afterwards is not necessary and may cause a
1113 // needless overflow.
1114 if exp == 1 {
1115 acc = acc * base;
1116 }
1117
1118 acc
1119 }
1120
1121 /// Computes the absolute value of `self`.
1122 ///
1123 /// # Overflow behavior
1124 ///
1125 /// The absolute value of `i32::min_value()` cannot be represented as an
1126 /// `i32`, and attempting to calculate it will cause an overflow. This
1127 /// means that code in debug mode will trigger a panic on this case and
1128 /// optimized code will return `i32::min_value()` without a panic.
1129 ///
1130 /// # Examples
1131 ///
1132 /// Basic usage:
1133 ///
1134 /// ```
1135 /// assert_eq!(10i8.abs(), 10);
1136 /// assert_eq!((-10i8).abs(), 10);
1137 /// ```
1138 #[stable(feature = "rust1", since = "1.0.0")]
1139 #[inline]
1140 #[rustc_inherit_overflow_checks]
1141 pub fn abs(self) -> Self {
1142 if self.is_negative() {
1143 // Note that the #[inline] above means that the overflow
1144 // semantics of this negation depend on the crate we're being
1145 // inlined into.
1146 -self
1147 } else {
1148 self
1149 }
1150 }
1151
1152 /// Returns a number representing sign of `self`.
1153 ///
1154 /// - `0` if the number is zero
1155 /// - `1` if the number is positive
1156 /// - `-1` if the number is negative
1157 ///
1158 /// # Examples
1159 ///
1160 /// Basic usage:
1161 ///
1162 /// ```
1163 /// assert_eq!(10i8.signum(), 1);
1164 /// assert_eq!(0i8.signum(), 0);
1165 /// assert_eq!((-10i8).signum(), -1);
1166 /// ```
1167 #[stable(feature = "rust1", since = "1.0.0")]
1168 #[inline]
1169 pub fn signum(self) -> Self {
1170 match self {
1171 n if n > 0 => 1,
1172 0 => 0,
1173 _ => -1,
1174 }
1175 }
1176
1177 /// Returns `true` if `self` is positive and `false` if the number
1178 /// is zero or negative.
1179 ///
1180 /// # Examples
1181 ///
1182 /// Basic usage:
1183 ///
1184 /// ```
1185 /// assert!(10i8.is_positive());
1186 /// assert!(!(-10i8).is_positive());
1187 /// ```
1188 #[stable(feature = "rust1", since = "1.0.0")]
1189 #[inline]
1190 pub fn is_positive(self) -> bool { self > 0 }
1191
1192 /// Returns `true` if `self` is negative and `false` if the number
1193 /// is zero or positive.
1194 ///
1195 /// # Examples
1196 ///
1197 /// Basic usage:
1198 ///
1199 /// ```
1200 /// assert!((-10i8).is_negative());
1201 /// assert!(!10i8.is_negative());
1202 /// ```
1203 #[stable(feature = "rust1", since = "1.0.0")]
1204 #[inline]
1205 pub fn is_negative(self) -> bool { self < 0 }
1206 }
1207 }
1208
1209 #[lang = "i8"]
1210 impl i8 {
1211 int_impl! { i8, i8, u8, 8 }
1212 }
1213
1214 #[lang = "i16"]
1215 impl i16 {
1216 int_impl! { i16, i16, u16, 16 }
1217 }
1218
1219 #[lang = "i32"]
1220 impl i32 {
1221 int_impl! { i32, i32, u32, 32 }
1222 }
1223
1224 #[lang = "i64"]
1225 impl i64 {
1226 int_impl! { i64, i64, u64, 64 }
1227 }
1228
1229 #[lang = "i128"]
1230 impl i128 {
1231 int_impl! { i128, i128, u128, 128 }
1232 }
1233
1234 #[cfg(target_pointer_width = "16")]
1235 #[lang = "isize"]
1236 impl isize {
1237 int_impl! { isize, i16, u16, 16 }
1238 }
1239
1240 #[cfg(target_pointer_width = "32")]
1241 #[lang = "isize"]
1242 impl isize {
1243 int_impl! { isize, i32, u32, 32 }
1244 }
1245
1246 #[cfg(target_pointer_width = "64")]
1247 #[lang = "isize"]
1248 impl isize {
1249 int_impl! { isize, i64, u64, 64 }
1250 }
1251
1252 // `Int` + `UnsignedInt` implemented for unsigned integers
1253 macro_rules! uint_impl {
1254 ($SelfT:ty, $ActualT:ty, $BITS:expr) => {
1255 /// Returns the smallest value that can be represented by this integer type.
1256 ///
1257 /// # Examples
1258 ///
1259 /// Basic usage:
1260 ///
1261 /// ```
1262 /// assert_eq!(u8::min_value(), 0);
1263 /// ```
1264 #[stable(feature = "rust1", since = "1.0.0")]
1265 #[inline]
1266 pub const fn min_value() -> Self { 0 }
1267
1268 /// Returns the largest value that can be represented by this integer type.
1269 ///
1270 /// # Examples
1271 ///
1272 /// Basic usage:
1273 ///
1274 /// ```
1275 /// assert_eq!(u8::max_value(), 255);
1276 /// ```
1277 #[stable(feature = "rust1", since = "1.0.0")]
1278 #[inline]
1279 pub const fn max_value() -> Self { !0 }
1280
1281 /// Converts a string slice in a given base to an integer.
1282 ///
1283 /// The string is expected to be an optional `+` sign
1284 /// followed by digits.
1285 /// Leading and trailing whitespace represent an error.
1286 /// Digits are a subset of these characters, depending on `radix`:
1287 ///
1288 /// * `0-9`
1289 /// * `a-z`
1290 /// * `A-Z`
1291 ///
1292 /// # Panics
1293 ///
1294 /// This function panics if `radix` is not in the range from 2 to 36.
1295 ///
1296 /// # Examples
1297 ///
1298 /// Basic usage:
1299 ///
1300 /// ```
1301 /// assert_eq!(u32::from_str_radix("A", 16), Ok(10));
1302 /// ```
1303 #[stable(feature = "rust1", since = "1.0.0")]
1304 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> {
1305 from_str_radix(src, radix)
1306 }
1307
1308 /// Returns the number of ones in the binary representation of `self`.
1309 ///
1310 /// # Examples
1311 ///
1312 /// Basic usage:
1313 ///
1314 /// ```
1315 /// let n = 0b01001100u8;
1316 ///
1317 /// assert_eq!(n.count_ones(), 3);
1318 /// ```
1319 #[stable(feature = "rust1", since = "1.0.0")]
1320 #[inline]
1321 pub fn count_ones(self) -> u32 {
1322 unsafe { intrinsics::ctpop(self as $ActualT) as u32 }
1323 }
1324
1325 /// Returns the number of zeros in the binary representation of `self`.
1326 ///
1327 /// # Examples
1328 ///
1329 /// Basic usage:
1330 ///
1331 /// ```
1332 /// let n = 0b01001100u8;
1333 ///
1334 /// assert_eq!(n.count_zeros(), 5);
1335 /// ```
1336 #[stable(feature = "rust1", since = "1.0.0")]
1337 #[inline]
1338 pub fn count_zeros(self) -> u32 {
1339 (!self).count_ones()
1340 }
1341
1342 /// Returns the number of leading zeros in the binary representation
1343 /// of `self`.
1344 ///
1345 /// # Examples
1346 ///
1347 /// Basic usage:
1348 ///
1349 /// ```
1350 /// let n = 0b0101000u16;
1351 ///
1352 /// assert_eq!(n.leading_zeros(), 10);
1353 /// ```
1354 #[stable(feature = "rust1", since = "1.0.0")]
1355 #[inline]
1356 pub fn leading_zeros(self) -> u32 {
1357 unsafe { intrinsics::ctlz(self as $ActualT) as u32 }
1358 }
1359
1360 /// Returns the number of trailing zeros in the binary representation
1361 /// of `self`.
1362 ///
1363 /// # Examples
1364 ///
1365 /// Basic usage:
1366 ///
1367 /// ```
1368 /// let n = 0b0101000u16;
1369 ///
1370 /// assert_eq!(n.trailing_zeros(), 3);
1371 /// ```
1372 #[stable(feature = "rust1", since = "1.0.0")]
1373 #[inline]
1374 pub fn trailing_zeros(self) -> u32 {
1375 // As of LLVM 3.6 the codegen for the zero-safe cttz8 intrinsic
1376 // emits two conditional moves on x86_64. By promoting the value to
1377 // u16 and setting bit 8, we get better code without any conditional
1378 // operations.
1379 // FIXME: There's a LLVM patch (http://reviews.llvm.org/D9284)
1380 // pending, remove this workaround once LLVM generates better code
1381 // for cttz8.
1382 unsafe {
1383 if $BITS == 8 {
1384 intrinsics::cttz(self as u16 | 0x100) as u32
1385 } else {
1386 intrinsics::cttz(self) as u32
1387 }
1388 }
1389 }
1390
1391 /// Shifts the bits to the left by a specified amount, `n`,
1392 /// wrapping the truncated bits to the end of the resulting integer.
1393 ///
1394 /// Please note this isn't the same operation as `<<`!
1395 ///
1396 /// # Examples
1397 ///
1398 /// Basic usage:
1399 ///
1400 /// ```
1401 /// let n = 0x0123456789ABCDEFu64;
1402 /// let m = 0x3456789ABCDEF012u64;
1403 ///
1404 /// assert_eq!(n.rotate_left(12), m);
1405 /// ```
1406 #[stable(feature = "rust1", since = "1.0.0")]
1407 #[inline]
1408 pub fn rotate_left(self, n: u32) -> Self {
1409 // Protect against undefined behaviour for over-long bit shifts
1410 let n = n % $BITS;
1411 (self << n) | (self >> (($BITS - n) % $BITS))
1412 }
1413
1414 /// Shifts the bits to the right by a specified amount, `n`,
1415 /// wrapping the truncated bits to the beginning of the resulting
1416 /// integer.
1417 ///
1418 /// Please note this isn't the same operation as `>>`!
1419 ///
1420 /// # Examples
1421 ///
1422 /// Basic usage:
1423 ///
1424 /// ```
1425 /// let n = 0x0123456789ABCDEFu64;
1426 /// let m = 0xDEF0123456789ABCu64;
1427 ///
1428 /// assert_eq!(n.rotate_right(12), m);
1429 /// ```
1430 #[stable(feature = "rust1", since = "1.0.0")]
1431 #[inline]
1432 pub fn rotate_right(self, n: u32) -> Self {
1433 // Protect against undefined behaviour for over-long bit shifts
1434 let n = n % $BITS;
1435 (self >> n) | (self << (($BITS - n) % $BITS))
1436 }
1437
1438 /// Reverses the byte order of the integer.
1439 ///
1440 /// # Examples
1441 ///
1442 /// Basic usage:
1443 ///
1444 /// ```
1445 /// let n: u16 = 0b0000000_01010101;
1446 /// assert_eq!(n, 85);
1447 ///
1448 /// let m = n.swap_bytes();
1449 ///
1450 /// assert_eq!(m, 0b01010101_00000000);
1451 /// assert_eq!(m, 21760);
1452 /// ```
1453 #[stable(feature = "rust1", since = "1.0.0")]
1454 #[inline]
1455 pub fn swap_bytes(self) -> Self {
1456 unsafe { intrinsics::bswap(self as $ActualT) as Self }
1457 }
1458
1459 /// Converts an integer from big endian to the target's endianness.
1460 ///
1461 /// On big endian this is a no-op. On little endian the bytes are
1462 /// swapped.
1463 ///
1464 /// # Examples
1465 ///
1466 /// Basic usage:
1467 ///
1468 /// ```
1469 /// let n = 0x0123456789ABCDEFu64;
1470 ///
1471 /// if cfg!(target_endian = "big") {
1472 /// assert_eq!(u64::from_be(n), n)
1473 /// } else {
1474 /// assert_eq!(u64::from_be(n), n.swap_bytes())
1475 /// }
1476 /// ```
1477 #[stable(feature = "rust1", since = "1.0.0")]
1478 #[inline]
1479 pub fn from_be(x: Self) -> Self {
1480 if cfg!(target_endian = "big") { x } else { x.swap_bytes() }
1481 }
1482
1483 /// Converts an integer from little endian to the target's endianness.
1484 ///
1485 /// On little endian this is a no-op. On big endian the bytes are
1486 /// swapped.
1487 ///
1488 /// # Examples
1489 ///
1490 /// Basic usage:
1491 ///
1492 /// ```
1493 /// let n = 0x0123456789ABCDEFu64;
1494 ///
1495 /// if cfg!(target_endian = "little") {
1496 /// assert_eq!(u64::from_le(n), n)
1497 /// } else {
1498 /// assert_eq!(u64::from_le(n), n.swap_bytes())
1499 /// }
1500 /// ```
1501 #[stable(feature = "rust1", since = "1.0.0")]
1502 #[inline]
1503 pub fn from_le(x: Self) -> Self {
1504 if cfg!(target_endian = "little") { x } else { x.swap_bytes() }
1505 }
1506
1507 /// Converts `self` to big endian from the target's endianness.
1508 ///
1509 /// On big endian this is a no-op. On little endian the bytes are
1510 /// swapped.
1511 ///
1512 /// # Examples
1513 ///
1514 /// Basic usage:
1515 ///
1516 /// ```
1517 /// let n = 0x0123456789ABCDEFu64;
1518 ///
1519 /// if cfg!(target_endian = "big") {
1520 /// assert_eq!(n.to_be(), n)
1521 /// } else {
1522 /// assert_eq!(n.to_be(), n.swap_bytes())
1523 /// }
1524 /// ```
1525 #[stable(feature = "rust1", since = "1.0.0")]
1526 #[inline]
1527 pub fn to_be(self) -> Self { // or not to be?
1528 if cfg!(target_endian = "big") { self } else { self.swap_bytes() }
1529 }
1530
1531 /// Converts `self` to little endian from the target's endianness.
1532 ///
1533 /// On little endian this is a no-op. On big endian the bytes are
1534 /// swapped.
1535 ///
1536 /// # Examples
1537 ///
1538 /// Basic usage:
1539 ///
1540 /// ```
1541 /// let n = 0x0123456789ABCDEFu64;
1542 ///
1543 /// if cfg!(target_endian = "little") {
1544 /// assert_eq!(n.to_le(), n)
1545 /// } else {
1546 /// assert_eq!(n.to_le(), n.swap_bytes())
1547 /// }
1548 /// ```
1549 #[stable(feature = "rust1", since = "1.0.0")]
1550 #[inline]
1551 pub fn to_le(self) -> Self {
1552 if cfg!(target_endian = "little") { self } else { self.swap_bytes() }
1553 }
1554
1555 /// Checked integer addition. Computes `self + rhs`, returning `None`
1556 /// if overflow occurred.
1557 ///
1558 /// # Examples
1559 ///
1560 /// Basic usage:
1561 ///
1562 /// ```
1563 /// assert_eq!(5u16.checked_add(65530), Some(65535));
1564 /// assert_eq!(6u16.checked_add(65530), None);
1565 /// ```
1566 #[stable(feature = "rust1", since = "1.0.0")]
1567 #[inline]
1568 pub fn checked_add(self, rhs: Self) -> Option<Self> {
1569 let (a, b) = self.overflowing_add(rhs);
1570 if b {None} else {Some(a)}
1571 }
1572
1573 /// Checked integer subtraction. Computes `self - rhs`, returning
1574 /// `None` if overflow occurred.
1575 ///
1576 /// # Examples
1577 ///
1578 /// Basic usage:
1579 ///
1580 /// ```
1581 /// assert_eq!(1u8.checked_sub(1), Some(0));
1582 /// assert_eq!(0u8.checked_sub(1), None);
1583 /// ```
1584 #[stable(feature = "rust1", since = "1.0.0")]
1585 #[inline]
1586 pub fn checked_sub(self, rhs: Self) -> Option<Self> {
1587 let (a, b) = self.overflowing_sub(rhs);
1588 if b {None} else {Some(a)}
1589 }
1590
1591 /// Checked integer multiplication. Computes `self * rhs`, returning
1592 /// `None` if overflow occurred.
1593 ///
1594 /// # Examples
1595 ///
1596 /// Basic usage:
1597 ///
1598 /// ```
1599 /// assert_eq!(5u8.checked_mul(51), Some(255));
1600 /// assert_eq!(5u8.checked_mul(52), None);
1601 /// ```
1602 #[stable(feature = "rust1", since = "1.0.0")]
1603 #[inline]
1604 pub fn checked_mul(self, rhs: Self) -> Option<Self> {
1605 let (a, b) = self.overflowing_mul(rhs);
1606 if b {None} else {Some(a)}
1607 }
1608
1609 /// Checked integer division. Computes `self / rhs`, returning `None`
1610 /// if `rhs == 0`.
1611 ///
1612 /// # Examples
1613 ///
1614 /// Basic usage:
1615 ///
1616 /// ```
1617 /// assert_eq!(128u8.checked_div(2), Some(64));
1618 /// assert_eq!(1u8.checked_div(0), None);
1619 /// ```
1620 #[stable(feature = "rust1", since = "1.0.0")]
1621 #[inline]
1622 pub fn checked_div(self, rhs: Self) -> Option<Self> {
1623 match rhs {
1624 0 => None,
1625 rhs => Some(unsafe { intrinsics::unchecked_div(self, rhs) }),
1626 }
1627 }
1628
1629 /// Checked integer remainder. Computes `self % rhs`, returning `None`
1630 /// if `rhs == 0`.
1631 ///
1632 /// # Examples
1633 ///
1634 /// Basic usage:
1635 ///
1636 /// ```
1637 /// assert_eq!(5u32.checked_rem(2), Some(1));
1638 /// assert_eq!(5u32.checked_rem(0), None);
1639 /// ```
1640 #[stable(feature = "wrapping", since = "1.7.0")]
1641 #[inline]
1642 pub fn checked_rem(self, rhs: Self) -> Option<Self> {
1643 if rhs == 0 {
1644 None
1645 } else {
1646 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
1647 }
1648 }
1649
1650 /// Checked negation. Computes `-self`, returning `None` unless `self ==
1651 /// 0`.
1652 ///
1653 /// Note that negating any positive integer will overflow.
1654 ///
1655 /// # Examples
1656 ///
1657 /// Basic usage:
1658 ///
1659 /// ```
1660 /// assert_eq!(0u32.checked_neg(), Some(0));
1661 /// assert_eq!(1u32.checked_neg(), None);
1662 /// ```
1663 #[stable(feature = "wrapping", since = "1.7.0")]
1664 #[inline]
1665 pub fn checked_neg(self) -> Option<Self> {
1666 let (a, b) = self.overflowing_neg();
1667 if b {None} else {Some(a)}
1668 }
1669
1670 /// Checked shift left. Computes `self << rhs`, returning `None`
1671 /// if `rhs` is larger than or equal to the number of bits in `self`.
1672 ///
1673 /// # Examples
1674 ///
1675 /// Basic usage:
1676 ///
1677 /// ```
1678 /// assert_eq!(0x10u32.checked_shl(4), Some(0x100));
1679 /// assert_eq!(0x10u32.checked_shl(33), None);
1680 /// ```
1681 #[stable(feature = "wrapping", since = "1.7.0")]
1682 #[inline]
1683 pub fn checked_shl(self, rhs: u32) -> Option<Self> {
1684 let (a, b) = self.overflowing_shl(rhs);
1685 if b {None} else {Some(a)}
1686 }
1687
1688 /// Checked shift right. Computes `self >> rhs`, returning `None`
1689 /// if `rhs` is larger than or equal to the number of bits in `self`.
1690 ///
1691 /// # Examples
1692 ///
1693 /// Basic usage:
1694 ///
1695 /// ```
1696 /// assert_eq!(0x10u32.checked_shr(4), Some(0x1));
1697 /// assert_eq!(0x10u32.checked_shr(33), None);
1698 /// ```
1699 #[stable(feature = "wrapping", since = "1.7.0")]
1700 #[inline]
1701 pub fn checked_shr(self, rhs: u32) -> Option<Self> {
1702 let (a, b) = self.overflowing_shr(rhs);
1703 if b {None} else {Some(a)}
1704 }
1705
1706 /// Saturating integer addition. Computes `self + rhs`, saturating at
1707 /// the numeric bounds instead of overflowing.
1708 ///
1709 /// # Examples
1710 ///
1711 /// Basic usage:
1712 ///
1713 /// ```
1714 /// assert_eq!(100u8.saturating_add(1), 101);
1715 /// assert_eq!(200u8.saturating_add(127), 255);
1716 /// ```
1717 #[stable(feature = "rust1", since = "1.0.0")]
1718 #[inline]
1719 pub fn saturating_add(self, rhs: Self) -> Self {
1720 match self.checked_add(rhs) {
1721 Some(x) => x,
1722 None => Self::max_value(),
1723 }
1724 }
1725
1726 /// Saturating integer subtraction. Computes `self - rhs`, saturating
1727 /// at the numeric bounds instead of overflowing.
1728 ///
1729 /// # Examples
1730 ///
1731 /// Basic usage:
1732 ///
1733 /// ```
1734 /// assert_eq!(100u8.saturating_sub(27), 73);
1735 /// assert_eq!(13u8.saturating_sub(127), 0);
1736 /// ```
1737 #[stable(feature = "rust1", since = "1.0.0")]
1738 #[inline]
1739 pub fn saturating_sub(self, rhs: Self) -> Self {
1740 match self.checked_sub(rhs) {
1741 Some(x) => x,
1742 None => Self::min_value(),
1743 }
1744 }
1745
1746 /// Saturating integer multiplication. Computes `self * rhs`,
1747 /// saturating at the numeric bounds instead of overflowing.
1748 ///
1749 /// # Examples
1750 ///
1751 /// Basic usage:
1752 ///
1753 /// ```
1754 /// use std::u32;
1755 ///
1756 /// assert_eq!(100u32.saturating_mul(127), 12700);
1757 /// assert_eq!((1u32 << 23).saturating_mul(1 << 23), u32::MAX);
1758 /// ```
1759 #[stable(feature = "wrapping", since = "1.7.0")]
1760 #[inline]
1761 pub fn saturating_mul(self, rhs: Self) -> Self {
1762 self.checked_mul(rhs).unwrap_or(Self::max_value())
1763 }
1764
1765 /// Wrapping (modular) addition. Computes `self + rhs`,
1766 /// wrapping around at the boundary of the type.
1767 ///
1768 /// # Examples
1769 ///
1770 /// Basic usage:
1771 ///
1772 /// ```
1773 /// assert_eq!(200u8.wrapping_add(55), 255);
1774 /// assert_eq!(200u8.wrapping_add(155), 99);
1775 /// ```
1776 #[stable(feature = "rust1", since = "1.0.0")]
1777 #[inline]
1778 pub fn wrapping_add(self, rhs: Self) -> Self {
1779 unsafe {
1780 intrinsics::overflowing_add(self, rhs)
1781 }
1782 }
1783
1784 /// Wrapping (modular) subtraction. Computes `self - rhs`,
1785 /// wrapping around at the boundary of the type.
1786 ///
1787 /// # Examples
1788 ///
1789 /// Basic usage:
1790 ///
1791 /// ```
1792 /// assert_eq!(100u8.wrapping_sub(100), 0);
1793 /// assert_eq!(100u8.wrapping_sub(155), 201);
1794 /// ```
1795 #[stable(feature = "rust1", since = "1.0.0")]
1796 #[inline]
1797 pub fn wrapping_sub(self, rhs: Self) -> Self {
1798 unsafe {
1799 intrinsics::overflowing_sub(self, rhs)
1800 }
1801 }
1802
1803 /// Wrapping (modular) multiplication. Computes `self *
1804 /// rhs`, wrapping around at the boundary of the type.
1805 ///
1806 /// # Examples
1807 ///
1808 /// Basic usage:
1809 ///
1810 /// ```
1811 /// assert_eq!(10u8.wrapping_mul(12), 120);
1812 /// assert_eq!(25u8.wrapping_mul(12), 44);
1813 /// ```
1814 #[stable(feature = "rust1", since = "1.0.0")]
1815 #[inline]
1816 pub fn wrapping_mul(self, rhs: Self) -> Self {
1817 unsafe {
1818 intrinsics::overflowing_mul(self, rhs)
1819 }
1820 }
1821
1822 /// Wrapping (modular) division. Computes `self / rhs`.
1823 /// Wrapped division on unsigned types is just normal division.
1824 /// There's no way wrapping could ever happen.
1825 /// This function exists, so that all operations
1826 /// are accounted for in the wrapping operations.
1827 ///
1828 /// # Examples
1829 ///
1830 /// Basic usage:
1831 ///
1832 /// ```
1833 /// assert_eq!(100u8.wrapping_div(10), 10);
1834 /// ```
1835 #[stable(feature = "num_wrapping", since = "1.2.0")]
1836 #[inline]
1837 pub fn wrapping_div(self, rhs: Self) -> Self {
1838 self / rhs
1839 }
1840
1841 /// Wrapping (modular) remainder. Computes `self % rhs`.
1842 /// Wrapped remainder calculation on unsigned types is
1843 /// just the regular remainder calculation.
1844 /// There's no way wrapping could ever happen.
1845 /// This function exists, so that all operations
1846 /// are accounted for in the wrapping operations.
1847 ///
1848 /// # Examples
1849 ///
1850 /// Basic usage:
1851 ///
1852 /// ```
1853 /// assert_eq!(100u8.wrapping_rem(10), 0);
1854 /// ```
1855 #[stable(feature = "num_wrapping", since = "1.2.0")]
1856 #[inline]
1857 pub fn wrapping_rem(self, rhs: Self) -> Self {
1858 self % rhs
1859 }
1860
1861 /// Wrapping (modular) negation. Computes `-self`,
1862 /// wrapping around at the boundary of the type.
1863 ///
1864 /// Since unsigned types do not have negative equivalents
1865 /// all applications of this function will wrap (except for `-0`).
1866 /// For values smaller than the corresponding signed type's maximum
1867 /// the result is the same as casting the corresponding signed value.
1868 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
1869 /// `MAX` is the corresponding signed type's maximum.
1870 ///
1871 /// # Examples
1872 ///
1873 /// Basic usage:
1874 ///
1875 /// ```
1876 /// assert_eq!(100u8.wrapping_neg(), 156);
1877 /// assert_eq!(0u8.wrapping_neg(), 0);
1878 /// assert_eq!(180u8.wrapping_neg(), 76);
1879 /// assert_eq!(180u8.wrapping_neg(), (127 + 1) - (180u8 - (127 + 1)));
1880 /// ```
1881 #[stable(feature = "num_wrapping", since = "1.2.0")]
1882 #[inline]
1883 pub fn wrapping_neg(self) -> Self {
1884 self.overflowing_neg().0
1885 }
1886
1887 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
1888 /// where `mask` removes any high-order bits of `rhs` that
1889 /// would cause the shift to exceed the bitwidth of the type.
1890 ///
1891 /// Note that this is *not* the same as a rotate-left; the
1892 /// RHS of a wrapping shift-left is restricted to the range
1893 /// of the type, rather than the bits shifted out of the LHS
1894 /// being returned to the other end. The primitive integer
1895 /// types all implement a `rotate_left` function, which may
1896 /// be what you want instead.
1897 ///
1898 /// # Examples
1899 ///
1900 /// Basic usage:
1901 ///
1902 /// ```
1903 /// assert_eq!(1u8.wrapping_shl(7), 128);
1904 /// assert_eq!(1u8.wrapping_shl(8), 1);
1905 /// ```
1906 #[stable(feature = "num_wrapping", since = "1.2.0")]
1907 #[inline]
1908 pub fn wrapping_shl(self, rhs: u32) -> Self {
1909 unsafe {
1910 intrinsics::unchecked_shl(self, (rhs & ($BITS - 1)) as $SelfT)
1911 }
1912 }
1913
1914 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
1915 /// where `mask` removes any high-order bits of `rhs` that
1916 /// would cause the shift to exceed the bitwidth of the type.
1917 ///
1918 /// Note that this is *not* the same as a rotate-right; the
1919 /// RHS of a wrapping shift-right is restricted to the range
1920 /// of the type, rather than the bits shifted out of the LHS
1921 /// being returned to the other end. The primitive integer
1922 /// types all implement a `rotate_right` function, which may
1923 /// be what you want instead.
1924 ///
1925 /// # Examples
1926 ///
1927 /// Basic usage:
1928 ///
1929 /// ```
1930 /// assert_eq!(128u8.wrapping_shr(7), 1);
1931 /// assert_eq!(128u8.wrapping_shr(8), 128);
1932 /// ```
1933 #[stable(feature = "num_wrapping", since = "1.2.0")]
1934 #[inline]
1935 pub fn wrapping_shr(self, rhs: u32) -> Self {
1936 unsafe {
1937 intrinsics::unchecked_shr(self, (rhs & ($BITS - 1)) as $SelfT)
1938 }
1939 }
1940
1941 /// Calculates `self` + `rhs`
1942 ///
1943 /// Returns a tuple of the addition along with a boolean indicating
1944 /// whether an arithmetic overflow would occur. If an overflow would
1945 /// have occurred then the wrapped value is returned.
1946 ///
1947 /// # Examples
1948 ///
1949 /// Basic usage
1950 ///
1951 /// ```
1952 /// use std::u32;
1953 ///
1954 /// assert_eq!(5u32.overflowing_add(2), (7, false));
1955 /// assert_eq!(u32::MAX.overflowing_add(1), (0, true));
1956 /// ```
1957 #[inline]
1958 #[stable(feature = "wrapping", since = "1.7.0")]
1959 pub fn overflowing_add(self, rhs: Self) -> (Self, bool) {
1960 let (a, b) = unsafe {
1961 intrinsics::add_with_overflow(self as $ActualT,
1962 rhs as $ActualT)
1963 };
1964 (a as Self, b)
1965 }
1966
1967 /// Calculates `self` - `rhs`
1968 ///
1969 /// Returns a tuple of the subtraction along with a boolean indicating
1970 /// whether an arithmetic overflow would occur. If an overflow would
1971 /// have occurred then the wrapped value is returned.
1972 ///
1973 /// # Examples
1974 ///
1975 /// Basic usage
1976 ///
1977 /// ```
1978 /// use std::u32;
1979 ///
1980 /// assert_eq!(5u32.overflowing_sub(2), (3, false));
1981 /// assert_eq!(0u32.overflowing_sub(1), (u32::MAX, true));
1982 /// ```
1983 #[inline]
1984 #[stable(feature = "wrapping", since = "1.7.0")]
1985 pub fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
1986 let (a, b) = unsafe {
1987 intrinsics::sub_with_overflow(self as $ActualT,
1988 rhs as $ActualT)
1989 };
1990 (a as Self, b)
1991 }
1992
1993 /// Calculates the multiplication of `self` and `rhs`.
1994 ///
1995 /// Returns a tuple of the multiplication along with a boolean
1996 /// indicating whether an arithmetic overflow would occur. If an
1997 /// overflow would have occurred then the wrapped value is returned.
1998 ///
1999 /// # Examples
2000 ///
2001 /// Basic usage
2002 ///
2003 /// ```
2004 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
2005 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
2006 /// ```
2007 #[inline]
2008 #[stable(feature = "wrapping", since = "1.7.0")]
2009 pub fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
2010 let (a, b) = unsafe {
2011 intrinsics::mul_with_overflow(self as $ActualT,
2012 rhs as $ActualT)
2013 };
2014 (a as Self, b)
2015 }
2016
2017 /// Calculates the divisor when `self` is divided by `rhs`.
2018 ///
2019 /// Returns a tuple of the divisor along with a boolean indicating
2020 /// whether an arithmetic overflow would occur. Note that for unsigned
2021 /// integers overflow never occurs, so the second value is always
2022 /// `false`.
2023 ///
2024 /// # Panics
2025 ///
2026 /// This function will panic if `rhs` is 0.
2027 ///
2028 /// # Examples
2029 ///
2030 /// Basic usage
2031 ///
2032 /// ```
2033 /// assert_eq!(5u32.overflowing_div(2), (2, false));
2034 /// ```
2035 #[inline]
2036 #[stable(feature = "wrapping", since = "1.7.0")]
2037 pub fn overflowing_div(self, rhs: Self) -> (Self, bool) {
2038 (self / rhs, false)
2039 }
2040
2041 /// Calculates the remainder when `self` is divided by `rhs`.
2042 ///
2043 /// Returns a tuple of the remainder after dividing along with a boolean
2044 /// indicating whether an arithmetic overflow would occur. Note that for
2045 /// unsigned integers overflow never occurs, so the second value is
2046 /// always `false`.
2047 ///
2048 /// # Panics
2049 ///
2050 /// This function will panic if `rhs` is 0.
2051 ///
2052 /// # Examples
2053 ///
2054 /// Basic usage
2055 ///
2056 /// ```
2057 /// assert_eq!(5u32.overflowing_rem(2), (1, false));
2058 /// ```
2059 #[inline]
2060 #[stable(feature = "wrapping", since = "1.7.0")]
2061 pub fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
2062 (self % rhs, false)
2063 }
2064
2065 /// Negates self in an overflowing fashion.
2066 ///
2067 /// Returns `!self + 1` using wrapping operations to return the value
2068 /// that represents the negation of this unsigned value. Note that for
2069 /// positive unsigned values overflow always occurs, but negating 0 does
2070 /// not overflow.
2071 ///
2072 /// # Examples
2073 ///
2074 /// Basic usage
2075 ///
2076 /// ```
2077 /// assert_eq!(0u32.overflowing_neg(), (0, false));
2078 /// assert_eq!(2u32.overflowing_neg(), (-2i32 as u32, true));
2079 /// ```
2080 #[inline]
2081 #[stable(feature = "wrapping", since = "1.7.0")]
2082 pub fn overflowing_neg(self) -> (Self, bool) {
2083 ((!self).wrapping_add(1), self != 0)
2084 }
2085
2086 /// Shifts self left by `rhs` bits.
2087 ///
2088 /// Returns a tuple of the shifted version of self along with a boolean
2089 /// indicating whether the shift value was larger than or equal to the
2090 /// number of bits. If the shift value is too large, then value is
2091 /// masked (N-1) where N is the number of bits, and this value is then
2092 /// used to perform the shift.
2093 ///
2094 /// # Examples
2095 ///
2096 /// Basic usage
2097 ///
2098 /// ```
2099 /// assert_eq!(0x10u32.overflowing_shl(4), (0x100, false));
2100 /// assert_eq!(0x10u32.overflowing_shl(36), (0x100, true));
2101 /// ```
2102 #[inline]
2103 #[stable(feature = "wrapping", since = "1.7.0")]
2104 pub fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
2105 (self.wrapping_shl(rhs), (rhs > ($BITS - 1)))
2106 }
2107
2108 /// Shifts self right by `rhs` bits.
2109 ///
2110 /// Returns a tuple of the shifted version of self along with a boolean
2111 /// indicating whether the shift value was larger than or equal to the
2112 /// number of bits. If the shift value is too large, then value is
2113 /// masked (N-1) where N is the number of bits, and this value is then
2114 /// used to perform the shift.
2115 ///
2116 /// # Examples
2117 ///
2118 /// Basic usage
2119 ///
2120 /// ```
2121 /// assert_eq!(0x10u32.overflowing_shr(4), (0x1, false));
2122 /// assert_eq!(0x10u32.overflowing_shr(36), (0x1, true));
2123 /// ```
2124 #[inline]
2125 #[stable(feature = "wrapping", since = "1.7.0")]
2126 pub fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
2127 (self.wrapping_shr(rhs), (rhs > ($BITS - 1)))
2128
2129 }
2130
2131 /// Raises self to the power of `exp`, using exponentiation by squaring.
2132 ///
2133 /// # Examples
2134 ///
2135 /// Basic usage:
2136 ///
2137 /// ```
2138 /// assert_eq!(2u32.pow(4), 16);
2139 /// ```
2140 #[stable(feature = "rust1", since = "1.0.0")]
2141 #[inline]
2142 #[rustc_inherit_overflow_checks]
2143 pub fn pow(self, mut exp: u32) -> Self {
2144 let mut base = self;
2145 let mut acc = 1;
2146
2147 while exp > 1 {
2148 if (exp & 1) == 1 {
2149 acc = acc * base;
2150 }
2151 exp /= 2;
2152 base = base * base;
2153 }
2154
2155 // Deal with the final bit of the exponent separately, since
2156 // squaring the base afterwards is not necessary and may cause a
2157 // needless overflow.
2158 if exp == 1 {
2159 acc = acc * base;
2160 }
2161
2162 acc
2163 }
2164
2165 /// Returns `true` if and only if `self == 2^k` for some `k`.
2166 ///
2167 /// # Examples
2168 ///
2169 /// Basic usage:
2170 ///
2171 /// ```
2172 /// assert!(16u8.is_power_of_two());
2173 /// assert!(!10u8.is_power_of_two());
2174 /// ```
2175 #[stable(feature = "rust1", since = "1.0.0")]
2176 #[inline]
2177 pub fn is_power_of_two(self) -> bool {
2178 (self.wrapping_sub(1)) & self == 0 && !(self == 0)
2179 }
2180
2181 // Returns one less than next power of two.
2182 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
2183 //
2184 // 8u8.one_less_than_next_power_of_two() == 7
2185 // 6u8.one_less_than_next_power_of_two() == 7
2186 //
2187 // This method cannot overflow, as in the `next_power_of_two`
2188 // overflow cases it instead ends up returning the maximum value
2189 // of the type, and can return 0 for 0.
2190 #[inline]
2191 fn one_less_than_next_power_of_two(self) -> Self {
2192 if self <= 1 { return 0; }
2193
2194 // Because `p > 0`, it cannot consist entirely of leading zeros.
2195 // That means the shift is always in-bounds, and some processors
2196 // (such as intel pre-haswell) have more efficient ctlz
2197 // intrinsics when the argument is non-zero.
2198 let p = self - 1;
2199 let z = unsafe { intrinsics::ctlz_nonzero(p) };
2200 <$SelfT>::max_value() >> z
2201 }
2202
2203 /// Returns the smallest power of two greater than or equal to `self`.
2204 ///
2205 /// When return value overflows (i.e. `self > (1 << (N-1))` for type
2206 /// `uN`), it panics in debug mode and return value is wrapped to 0 in
2207 /// release mode (the only situation in which method can return 0).
2208 ///
2209 /// # Examples
2210 ///
2211 /// Basic usage:
2212 ///
2213 /// ```
2214 /// assert_eq!(2u8.next_power_of_two(), 2);
2215 /// assert_eq!(3u8.next_power_of_two(), 4);
2216 /// ```
2217 #[stable(feature = "rust1", since = "1.0.0")]
2218 #[inline]
2219 pub fn next_power_of_two(self) -> Self {
2220 // Call the trait to get overflow checks
2221 ops::Add::add(self.one_less_than_next_power_of_two(), 1)
2222 }
2223
2224 /// Returns the smallest power of two greater than or equal to `n`. If
2225 /// the next power of two is greater than the type's maximum value,
2226 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
2227 ///
2228 /// # Examples
2229 ///
2230 /// Basic usage:
2231 ///
2232 /// ```
2233 /// assert_eq!(2u8.checked_next_power_of_two(), Some(2));
2234 /// assert_eq!(3u8.checked_next_power_of_two(), Some(4));
2235 /// assert_eq!(200u8.checked_next_power_of_two(), None);
2236 /// ```
2237 #[stable(feature = "rust1", since = "1.0.0")]
2238 pub fn checked_next_power_of_two(self) -> Option<Self> {
2239 self.one_less_than_next_power_of_two().checked_add(1)
2240 }
2241 }
2242 }
2243
2244 #[lang = "u8"]
2245 impl u8 {
2246 uint_impl! { u8, u8, 8 }
2247
2248
2249 /// Checks if the value is within the ASCII range.
2250 ///
2251 /// # Examples
2252 ///
2253 /// ```
2254 /// let ascii = 97u8;
2255 /// let non_ascii = 150u8;
2256 ///
2257 /// assert!(ascii.is_ascii());
2258 /// assert!(!non_ascii.is_ascii());
2259 /// ```
2260 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2261 #[inline]
2262 pub fn is_ascii(&self) -> bool {
2263 *self & 128 == 0
2264 }
2265
2266 /// Makes a copy of the value in its ASCII upper case equivalent.
2267 ///
2268 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2269 /// but non-ASCII letters are unchanged.
2270 ///
2271 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
2272 ///
2273 /// # Examples
2274 ///
2275 /// ```
2276 /// let lowercase_a = 97u8;
2277 ///
2278 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
2279 /// ```
2280 ///
2281 /// [`make_ascii_uppercase`]: #method.make_ascii_uppercase
2282 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2283 #[inline]
2284 pub fn to_ascii_uppercase(&self) -> u8 {
2285 ASCII_UPPERCASE_MAP[*self as usize]
2286 }
2287
2288 /// Makes a copy of the value in its ASCII lower case equivalent.
2289 ///
2290 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2291 /// but non-ASCII letters are unchanged.
2292 ///
2293 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
2294 ///
2295 /// # Examples
2296 ///
2297 /// ```
2298 /// let uppercase_a = 65u8;
2299 ///
2300 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
2301 /// ```
2302 ///
2303 /// [`make_ascii_lowercase`]: #method.make_ascii_lowercase
2304 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2305 #[inline]
2306 pub fn to_ascii_lowercase(&self) -> u8 {
2307 ASCII_LOWERCASE_MAP[*self as usize]
2308 }
2309
2310 /// Checks that two values are an ASCII case-insensitive match.
2311 ///
2312 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
2313 ///
2314 /// # Examples
2315 ///
2316 /// ```
2317 /// let lowercase_a = 97u8;
2318 /// let uppercase_a = 65u8;
2319 ///
2320 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
2321 /// ```
2322 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2323 #[inline]
2324 pub fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
2325 self.to_ascii_lowercase() == other.to_ascii_lowercase()
2326 }
2327
2328 /// Converts this value to its ASCII upper case equivalent in-place.
2329 ///
2330 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
2331 /// but non-ASCII letters are unchanged.
2332 ///
2333 /// To return a new uppercased value without modifying the existing one, use
2334 /// [`to_ascii_uppercase`].
2335 ///
2336 /// # Examples
2337 ///
2338 /// ```
2339 /// let mut byte = b'a';
2340 ///
2341 /// byte.make_ascii_uppercase();
2342 ///
2343 /// assert_eq!(b'A', byte);
2344 /// ```
2345 ///
2346 /// [`to_ascii_uppercase`]: #method.to_ascii_uppercase
2347 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2348 #[inline]
2349 pub fn make_ascii_uppercase(&mut self) {
2350 *self = self.to_ascii_uppercase();
2351 }
2352
2353 /// Converts this value to its ASCII lower case equivalent in-place.
2354 ///
2355 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
2356 /// but non-ASCII letters are unchanged.
2357 ///
2358 /// To return a new lowercased value without modifying the existing one, use
2359 /// [`to_ascii_lowercase`].
2360 ///
2361 /// # Examples
2362 ///
2363 /// ```
2364 /// let mut byte = b'A';
2365 ///
2366 /// byte.make_ascii_lowercase();
2367 ///
2368 /// assert_eq!(b'a', byte);
2369 /// ```
2370 ///
2371 /// [`to_ascii_lowercase`]: #method.to_ascii_lowercase
2372 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
2373 #[inline]
2374 pub fn make_ascii_lowercase(&mut self) {
2375 *self = self.to_ascii_lowercase();
2376 }
2377
2378 /// Checks if the value is an ASCII alphabetic character:
2379 ///
2380 /// - U+0041 'A' ... U+005A 'Z', or
2381 /// - U+0061 'a' ... U+007A 'z'.
2382 ///
2383 /// # Examples
2384 ///
2385 /// ```
2386 /// #![feature(ascii_ctype)]
2387 ///
2388 /// let uppercase_a = b'A';
2389 /// let uppercase_g = b'G';
2390 /// let a = b'a';
2391 /// let g = b'g';
2392 /// let zero = b'0';
2393 /// let percent = b'%';
2394 /// let space = b' ';
2395 /// let lf = b'\n';
2396 /// let esc = 0x1b_u8;
2397 ///
2398 /// assert!(uppercase_a.is_ascii_alphabetic());
2399 /// assert!(uppercase_g.is_ascii_alphabetic());
2400 /// assert!(a.is_ascii_alphabetic());
2401 /// assert!(g.is_ascii_alphabetic());
2402 /// assert!(!zero.is_ascii_alphabetic());
2403 /// assert!(!percent.is_ascii_alphabetic());
2404 /// assert!(!space.is_ascii_alphabetic());
2405 /// assert!(!lf.is_ascii_alphabetic());
2406 /// assert!(!esc.is_ascii_alphabetic());
2407 /// ```
2408 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2409 #[inline]
2410 pub fn is_ascii_alphabetic(&self) -> bool {
2411 if *self >= 0x80 { return false; }
2412 match ASCII_CHARACTER_CLASS[*self as usize] {
2413 L | Lx | U | Ux => true,
2414 _ => false
2415 }
2416 }
2417
2418 /// Checks if the value is an ASCII uppercase character:
2419 /// U+0041 'A' ... U+005A 'Z'.
2420 ///
2421 /// # Examples
2422 ///
2423 /// ```
2424 /// #![feature(ascii_ctype)]
2425 ///
2426 /// let uppercase_a = b'A';
2427 /// let uppercase_g = b'G';
2428 /// let a = b'a';
2429 /// let g = b'g';
2430 /// let zero = b'0';
2431 /// let percent = b'%';
2432 /// let space = b' ';
2433 /// let lf = b'\n';
2434 /// let esc = 0x1b_u8;
2435 ///
2436 /// assert!(uppercase_a.is_ascii_uppercase());
2437 /// assert!(uppercase_g.is_ascii_uppercase());
2438 /// assert!(!a.is_ascii_uppercase());
2439 /// assert!(!g.is_ascii_uppercase());
2440 /// assert!(!zero.is_ascii_uppercase());
2441 /// assert!(!percent.is_ascii_uppercase());
2442 /// assert!(!space.is_ascii_uppercase());
2443 /// assert!(!lf.is_ascii_uppercase());
2444 /// assert!(!esc.is_ascii_uppercase());
2445 /// ```
2446 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2447 #[inline]
2448 pub fn is_ascii_uppercase(&self) -> bool {
2449 if *self >= 0x80 { return false }
2450 match ASCII_CHARACTER_CLASS[*self as usize] {
2451 U | Ux => true,
2452 _ => false
2453 }
2454 }
2455
2456 /// Checks if the value is an ASCII lowercase character:
2457 /// U+0061 'a' ... U+007A 'z'.
2458 ///
2459 /// # Examples
2460 ///
2461 /// ```
2462 /// #![feature(ascii_ctype)]
2463 ///
2464 /// let uppercase_a = b'A';
2465 /// let uppercase_g = b'G';
2466 /// let a = b'a';
2467 /// let g = b'g';
2468 /// let zero = b'0';
2469 /// let percent = b'%';
2470 /// let space = b' ';
2471 /// let lf = b'\n';
2472 /// let esc = 0x1b_u8;
2473 ///
2474 /// assert!(!uppercase_a.is_ascii_lowercase());
2475 /// assert!(!uppercase_g.is_ascii_lowercase());
2476 /// assert!(a.is_ascii_lowercase());
2477 /// assert!(g.is_ascii_lowercase());
2478 /// assert!(!zero.is_ascii_lowercase());
2479 /// assert!(!percent.is_ascii_lowercase());
2480 /// assert!(!space.is_ascii_lowercase());
2481 /// assert!(!lf.is_ascii_lowercase());
2482 /// assert!(!esc.is_ascii_lowercase());
2483 /// ```
2484 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2485 #[inline]
2486 pub fn is_ascii_lowercase(&self) -> bool {
2487 if *self >= 0x80 { return false }
2488 match ASCII_CHARACTER_CLASS[*self as usize] {
2489 L | Lx => true,
2490 _ => false
2491 }
2492 }
2493
2494 /// Checks if the value is an ASCII alphanumeric character:
2495 ///
2496 /// - U+0041 'A' ... U+005A 'Z', or
2497 /// - U+0061 'a' ... U+007A 'z', or
2498 /// - U+0030 '0' ... U+0039 '9'.
2499 ///
2500 /// # Examples
2501 ///
2502 /// ```
2503 /// #![feature(ascii_ctype)]
2504 ///
2505 /// let uppercase_a = b'A';
2506 /// let uppercase_g = b'G';
2507 /// let a = b'a';
2508 /// let g = b'g';
2509 /// let zero = b'0';
2510 /// let percent = b'%';
2511 /// let space = b' ';
2512 /// let lf = b'\n';
2513 /// let esc = 0x1b_u8;
2514 ///
2515 /// assert!(uppercase_a.is_ascii_alphanumeric());
2516 /// assert!(uppercase_g.is_ascii_alphanumeric());
2517 /// assert!(a.is_ascii_alphanumeric());
2518 /// assert!(g.is_ascii_alphanumeric());
2519 /// assert!(zero.is_ascii_alphanumeric());
2520 /// assert!(!percent.is_ascii_alphanumeric());
2521 /// assert!(!space.is_ascii_alphanumeric());
2522 /// assert!(!lf.is_ascii_alphanumeric());
2523 /// assert!(!esc.is_ascii_alphanumeric());
2524 /// ```
2525 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2526 #[inline]
2527 pub fn is_ascii_alphanumeric(&self) -> bool {
2528 if *self >= 0x80 { return false }
2529 match ASCII_CHARACTER_CLASS[*self as usize] {
2530 D | L | Lx | U | Ux => true,
2531 _ => false
2532 }
2533 }
2534
2535 /// Checks if the value is an ASCII decimal digit:
2536 /// U+0030 '0' ... U+0039 '9'.
2537 ///
2538 /// # Examples
2539 ///
2540 /// ```
2541 /// #![feature(ascii_ctype)]
2542 ///
2543 /// let uppercase_a = b'A';
2544 /// let uppercase_g = b'G';
2545 /// let a = b'a';
2546 /// let g = b'g';
2547 /// let zero = b'0';
2548 /// let percent = b'%';
2549 /// let space = b' ';
2550 /// let lf = b'\n';
2551 /// let esc = 0x1b_u8;
2552 ///
2553 /// assert!(!uppercase_a.is_ascii_digit());
2554 /// assert!(!uppercase_g.is_ascii_digit());
2555 /// assert!(!a.is_ascii_digit());
2556 /// assert!(!g.is_ascii_digit());
2557 /// assert!(zero.is_ascii_digit());
2558 /// assert!(!percent.is_ascii_digit());
2559 /// assert!(!space.is_ascii_digit());
2560 /// assert!(!lf.is_ascii_digit());
2561 /// assert!(!esc.is_ascii_digit());
2562 /// ```
2563 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2564 #[inline]
2565 pub fn is_ascii_digit(&self) -> bool {
2566 if *self >= 0x80 { return false }
2567 match ASCII_CHARACTER_CLASS[*self as usize] {
2568 D => true,
2569 _ => false
2570 }
2571 }
2572
2573 /// Checks if the value is an ASCII hexadecimal digit:
2574 ///
2575 /// - U+0030 '0' ... U+0039 '9', or
2576 /// - U+0041 'A' ... U+0046 'F', or
2577 /// - U+0061 'a' ... U+0066 'f'.
2578 ///
2579 /// # Examples
2580 ///
2581 /// ```
2582 /// #![feature(ascii_ctype)]
2583 ///
2584 /// let uppercase_a = b'A';
2585 /// let uppercase_g = b'G';
2586 /// let a = b'a';
2587 /// let g = b'g';
2588 /// let zero = b'0';
2589 /// let percent = b'%';
2590 /// let space = b' ';
2591 /// let lf = b'\n';
2592 /// let esc = 0x1b_u8;
2593 ///
2594 /// assert!(uppercase_a.is_ascii_hexdigit());
2595 /// assert!(!uppercase_g.is_ascii_hexdigit());
2596 /// assert!(a.is_ascii_hexdigit());
2597 /// assert!(!g.is_ascii_hexdigit());
2598 /// assert!(zero.is_ascii_hexdigit());
2599 /// assert!(!percent.is_ascii_hexdigit());
2600 /// assert!(!space.is_ascii_hexdigit());
2601 /// assert!(!lf.is_ascii_hexdigit());
2602 /// assert!(!esc.is_ascii_hexdigit());
2603 /// ```
2604 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2605 #[inline]
2606 pub fn is_ascii_hexdigit(&self) -> bool {
2607 if *self >= 0x80 { return false }
2608 match ASCII_CHARACTER_CLASS[*self as usize] {
2609 D | Lx | Ux => true,
2610 _ => false
2611 }
2612 }
2613
2614 /// Checks if the value is an ASCII punctuation character:
2615 ///
2616 /// - U+0021 ... U+002F `! " # $ % & ' ( ) * + , - . /`, or
2617 /// - U+003A ... U+0040 `: ; < = > ? @`, or
2618 /// - U+005B ... U+0060 ``[ \ ] ^ _ ` ``, or
2619 /// - U+007B ... U+007E `{ | } ~`
2620 ///
2621 /// # Examples
2622 ///
2623 /// ```
2624 /// #![feature(ascii_ctype)]
2625 ///
2626 /// let uppercase_a = b'A';
2627 /// let uppercase_g = b'G';
2628 /// let a = b'a';
2629 /// let g = b'g';
2630 /// let zero = b'0';
2631 /// let percent = b'%';
2632 /// let space = b' ';
2633 /// let lf = b'\n';
2634 /// let esc = 0x1b_u8;
2635 ///
2636 /// assert!(!uppercase_a.is_ascii_punctuation());
2637 /// assert!(!uppercase_g.is_ascii_punctuation());
2638 /// assert!(!a.is_ascii_punctuation());
2639 /// assert!(!g.is_ascii_punctuation());
2640 /// assert!(!zero.is_ascii_punctuation());
2641 /// assert!(percent.is_ascii_punctuation());
2642 /// assert!(!space.is_ascii_punctuation());
2643 /// assert!(!lf.is_ascii_punctuation());
2644 /// assert!(!esc.is_ascii_punctuation());
2645 /// ```
2646 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2647 #[inline]
2648 pub fn is_ascii_punctuation(&self) -> bool {
2649 if *self >= 0x80 { return false }
2650 match ASCII_CHARACTER_CLASS[*self as usize] {
2651 P => true,
2652 _ => false
2653 }
2654 }
2655
2656 /// Checks if the value is an ASCII graphic character:
2657 /// U+0021 '@' ... U+007E '~'.
2658 ///
2659 /// # Examples
2660 ///
2661 /// ```
2662 /// #![feature(ascii_ctype)]
2663 ///
2664 /// let uppercase_a = b'A';
2665 /// let uppercase_g = b'G';
2666 /// let a = b'a';
2667 /// let g = b'g';
2668 /// let zero = b'0';
2669 /// let percent = b'%';
2670 /// let space = b' ';
2671 /// let lf = b'\n';
2672 /// let esc = 0x1b_u8;
2673 ///
2674 /// assert!(uppercase_a.is_ascii_graphic());
2675 /// assert!(uppercase_g.is_ascii_graphic());
2676 /// assert!(a.is_ascii_graphic());
2677 /// assert!(g.is_ascii_graphic());
2678 /// assert!(zero.is_ascii_graphic());
2679 /// assert!(percent.is_ascii_graphic());
2680 /// assert!(!space.is_ascii_graphic());
2681 /// assert!(!lf.is_ascii_graphic());
2682 /// assert!(!esc.is_ascii_graphic());
2683 /// ```
2684 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2685 #[inline]
2686 pub fn is_ascii_graphic(&self) -> bool {
2687 if *self >= 0x80 { return false; }
2688 match ASCII_CHARACTER_CLASS[*self as usize] {
2689 Ux | U | Lx | L | D | P => true,
2690 _ => false
2691 }
2692 }
2693
2694 /// Checks if the value is an ASCII whitespace character:
2695 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
2696 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
2697 ///
2698 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
2699 /// whitespace][infra-aw]. There are several other definitions in
2700 /// wide use. For instance, [the POSIX locale][pct] includes
2701 /// U+000B VERTICAL TAB as well as all the above characters,
2702 /// but—from the very same specification—[the default rule for
2703 /// "field splitting" in the Bourne shell][bfs] considers *only*
2704 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
2705 ///
2706 /// If you are writing a program that will process an existing
2707 /// file format, check what that format's definition of whitespace is
2708 /// before using this function.
2709 ///
2710 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
2711 /// [pct]: http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
2712 /// [bfs]: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
2713 ///
2714 /// # Examples
2715 ///
2716 /// ```
2717 /// #![feature(ascii_ctype)]
2718 ///
2719 /// let uppercase_a = b'A';
2720 /// let uppercase_g = b'G';
2721 /// let a = b'a';
2722 /// let g = b'g';
2723 /// let zero = b'0';
2724 /// let percent = b'%';
2725 /// let space = b' ';
2726 /// let lf = b'\n';
2727 /// let esc = 0x1b_u8;
2728 ///
2729 /// assert!(!uppercase_a.is_ascii_whitespace());
2730 /// assert!(!uppercase_g.is_ascii_whitespace());
2731 /// assert!(!a.is_ascii_whitespace());
2732 /// assert!(!g.is_ascii_whitespace());
2733 /// assert!(!zero.is_ascii_whitespace());
2734 /// assert!(!percent.is_ascii_whitespace());
2735 /// assert!(space.is_ascii_whitespace());
2736 /// assert!(lf.is_ascii_whitespace());
2737 /// assert!(!esc.is_ascii_whitespace());
2738 /// ```
2739 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2740 #[inline]
2741 pub fn is_ascii_whitespace(&self) -> bool {
2742 if *self >= 0x80 { return false; }
2743 match ASCII_CHARACTER_CLASS[*self as usize] {
2744 Cw | W => true,
2745 _ => false
2746 }
2747 }
2748
2749 /// Checks if the value is an ASCII control character:
2750 /// U+0000 NUL ... U+001F UNIT SEPARATOR, or U+007F DELETE.
2751 /// Note that most ASCII whitespace characters are control
2752 /// characters, but SPACE is not.
2753 ///
2754 /// # Examples
2755 ///
2756 /// ```
2757 /// #![feature(ascii_ctype)]
2758 ///
2759 /// let uppercase_a = b'A';
2760 /// let uppercase_g = b'G';
2761 /// let a = b'a';
2762 /// let g = b'g';
2763 /// let zero = b'0';
2764 /// let percent = b'%';
2765 /// let space = b' ';
2766 /// let lf = b'\n';
2767 /// let esc = 0x1b_u8;
2768 ///
2769 /// assert!(!uppercase_a.is_ascii_control());
2770 /// assert!(!uppercase_g.is_ascii_control());
2771 /// assert!(!a.is_ascii_control());
2772 /// assert!(!g.is_ascii_control());
2773 /// assert!(!zero.is_ascii_control());
2774 /// assert!(!percent.is_ascii_control());
2775 /// assert!(!space.is_ascii_control());
2776 /// assert!(lf.is_ascii_control());
2777 /// assert!(esc.is_ascii_control());
2778 /// ```
2779 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
2780 #[inline]
2781 pub fn is_ascii_control(&self) -> bool {
2782 if *self >= 0x80 { return false; }
2783 match ASCII_CHARACTER_CLASS[*self as usize] {
2784 C | Cw => true,
2785 _ => false
2786 }
2787 }
2788 }
2789
2790 #[lang = "u16"]
2791 impl u16 {
2792 uint_impl! { u16, u16, 16 }
2793 }
2794
2795 #[lang = "u32"]
2796 impl u32 {
2797 uint_impl! { u32, u32, 32 }
2798 }
2799
2800 #[lang = "u64"]
2801 impl u64 {
2802 uint_impl! { u64, u64, 64 }
2803 }
2804
2805 #[lang = "u128"]
2806 impl u128 {
2807 uint_impl! { u128, u128, 128 }
2808 }
2809
2810 #[cfg(target_pointer_width = "16")]
2811 #[lang = "usize"]
2812 impl usize {
2813 uint_impl! { usize, u16, 16 }
2814 }
2815 #[cfg(target_pointer_width = "32")]
2816 #[lang = "usize"]
2817 impl usize {
2818 uint_impl! { usize, u32, 32 }
2819 }
2820
2821 #[cfg(target_pointer_width = "64")]
2822 #[lang = "usize"]
2823 impl usize {
2824 uint_impl! { usize, u64, 64 }
2825 }
2826
2827 /// A classification of floating point numbers.
2828 ///
2829 /// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
2830 /// their documentation for more.
2831 ///
2832 /// [`f32::classify`]: ../../std/primitive.f32.html#method.classify
2833 /// [`f64::classify`]: ../../std/primitive.f64.html#method.classify
2834 ///
2835 /// # Examples
2836 ///
2837 /// ```
2838 /// use std::num::FpCategory;
2839 /// use std::f32;
2840 ///
2841 /// let num = 12.4_f32;
2842 /// let inf = f32::INFINITY;
2843 /// let zero = 0f32;
2844 /// let sub: f32 = 1.1754942e-38;
2845 /// let nan = f32::NAN;
2846 ///
2847 /// assert_eq!(num.classify(), FpCategory::Normal);
2848 /// assert_eq!(inf.classify(), FpCategory::Infinite);
2849 /// assert_eq!(zero.classify(), FpCategory::Zero);
2850 /// assert_eq!(nan.classify(), FpCategory::Nan);
2851 /// assert_eq!(sub.classify(), FpCategory::Subnormal);
2852 /// ```
2853 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
2854 #[stable(feature = "rust1", since = "1.0.0")]
2855 pub enum FpCategory {
2856 /// "Not a Number", often obtained by dividing by zero.
2857 #[stable(feature = "rust1", since = "1.0.0")]
2858 Nan,
2859
2860 /// Positive or negative infinity.
2861 #[stable(feature = "rust1", since = "1.0.0")]
2862 Infinite,
2863
2864 /// Positive or negative zero.
2865 #[stable(feature = "rust1", since = "1.0.0")]
2866 Zero,
2867
2868 /// De-normalized floating point representation (less precise than `Normal`).
2869 #[stable(feature = "rust1", since = "1.0.0")]
2870 Subnormal,
2871
2872 /// A regular floating point number.
2873 #[stable(feature = "rust1", since = "1.0.0")]
2874 Normal,
2875 }
2876
2877 /// A built-in floating point number.
2878 #[doc(hidden)]
2879 #[unstable(feature = "core_float",
2880 reason = "stable interface is via `impl f{32,64}` in later crates",
2881 issue = "32110")]
2882 pub trait Float: Sized {
2883 /// Type used by `to_bits` and `from_bits`.
2884 #[stable(feature = "core_float_bits", since = "1.24.0")]
2885 type Bits;
2886
2887 /// Returns `true` if this value is NaN and false otherwise.
2888 #[stable(feature = "core", since = "1.6.0")]
2889 fn is_nan(self) -> bool;
2890 /// Returns `true` if this value is positive infinity or negative infinity and
2891 /// false otherwise.
2892 #[stable(feature = "core", since = "1.6.0")]
2893 fn is_infinite(self) -> bool;
2894 /// Returns `true` if this number is neither infinite nor NaN.
2895 #[stable(feature = "core", since = "1.6.0")]
2896 fn is_finite(self) -> bool;
2897 /// Returns `true` if this number is neither zero, infinite, denormal, or NaN.
2898 #[stable(feature = "core", since = "1.6.0")]
2899 fn is_normal(self) -> bool;
2900 /// Returns the category that this number falls into.
2901 #[stable(feature = "core", since = "1.6.0")]
2902 fn classify(self) -> FpCategory;
2903
2904 /// Computes the absolute value of `self`. Returns `Float::nan()` if the
2905 /// number is `Float::nan()`.
2906 #[stable(feature = "core", since = "1.6.0")]
2907 fn abs(self) -> Self;
2908 /// Returns a number that represents the sign of `self`.
2909 ///
2910 /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
2911 /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
2912 /// - `Float::nan()` if the number is `Float::nan()`
2913 #[stable(feature = "core", since = "1.6.0")]
2914 fn signum(self) -> Self;
2915
2916 /// Returns `true` if `self` is positive, including `+0.0` and
2917 /// `Float::infinity()`.
2918 #[stable(feature = "core", since = "1.6.0")]
2919 fn is_sign_positive(self) -> bool;
2920 /// Returns `true` if `self` is negative, including `-0.0` and
2921 /// `Float::neg_infinity()`.
2922 #[stable(feature = "core", since = "1.6.0")]
2923 fn is_sign_negative(self) -> bool;
2924
2925 /// Take the reciprocal (inverse) of a number, `1/x`.
2926 #[stable(feature = "core", since = "1.6.0")]
2927 fn recip(self) -> Self;
2928
2929 /// Raise a number to an integer power.
2930 ///
2931 /// Using this function is generally faster than using `powf`
2932 #[stable(feature = "core", since = "1.6.0")]
2933 fn powi(self, n: i32) -> Self;
2934
2935 /// Convert radians to degrees.
2936 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
2937 fn to_degrees(self) -> Self;
2938 /// Convert degrees to radians.
2939 #[stable(feature = "deg_rad_conversions", since="1.7.0")]
2940 fn to_radians(self) -> Self;
2941
2942 /// Returns the maximum of the two numbers.
2943 #[stable(feature = "core_float_min_max", since="1.20.0")]
2944 fn max(self, other: Self) -> Self;
2945 /// Returns the minimum of the two numbers.
2946 #[stable(feature = "core_float_min_max", since="1.20.0")]
2947 fn min(self, other: Self) -> Self;
2948
2949 /// Raw transmutation to integer.
2950 #[stable(feature = "core_float_bits", since="1.24.0")]
2951 fn to_bits(self) -> Self::Bits;
2952 /// Raw transmutation from integer.
2953 #[stable(feature = "core_float_bits", since="1.24.0")]
2954 fn from_bits(v: Self::Bits) -> Self;
2955 }
2956
2957 macro_rules! from_str_radix_int_impl {
2958 ($($t:ty)*) => {$(
2959 #[stable(feature = "rust1", since = "1.0.0")]
2960 impl FromStr for $t {
2961 type Err = ParseIntError;
2962 fn from_str(src: &str) -> Result<Self, ParseIntError> {
2963 from_str_radix(src, 10)
2964 }
2965 }
2966 )*}
2967 }
2968 from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 }
2969
2970 /// The error type returned when a checked integral type conversion fails.
2971 #[unstable(feature = "try_from", issue = "33417")]
2972 #[derive(Debug, Copy, Clone)]
2973 pub struct TryFromIntError(());
2974
2975 impl TryFromIntError {
2976 #[unstable(feature = "int_error_internals",
2977 reason = "available through Error trait and this method should \
2978 not be exposed publicly",
2979 issue = "0")]
2980 #[doc(hidden)]
2981 pub fn __description(&self) -> &str {
2982 "out of range integral type conversion attempted"
2983 }
2984 }
2985
2986 #[unstable(feature = "try_from", issue = "33417")]
2987 impl fmt::Display for TryFromIntError {
2988 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
2989 self.__description().fmt(fmt)
2990 }
2991 }
2992
2993 #[unstable(feature = "try_from", issue = "33417")]
2994 impl From<Infallible> for TryFromIntError {
2995 fn from(infallible: Infallible) -> TryFromIntError {
2996 match infallible {
2997 }
2998 }
2999 }
3000
3001 // no possible bounds violation
3002 macro_rules! try_from_unbounded {
3003 ($source:ty, $($target:ty),*) => {$(
3004 #[unstable(feature = "try_from", issue = "33417")]
3005 impl TryFrom<$source> for $target {
3006 type Error = Infallible;
3007
3008 #[inline]
3009 fn try_from(value: $source) -> Result<Self, Self::Error> {
3010 Ok(value as $target)
3011 }
3012 }
3013 )*}
3014 }
3015
3016 // only negative bounds
3017 macro_rules! try_from_lower_bounded {
3018 ($source:ty, $($target:ty),*) => {$(
3019 #[unstable(feature = "try_from", issue = "33417")]
3020 impl TryFrom<$source> for $target {
3021 type Error = TryFromIntError;
3022
3023 #[inline]
3024 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
3025 if u >= 0 {
3026 Ok(u as $target)
3027 } else {
3028 Err(TryFromIntError(()))
3029 }
3030 }
3031 }
3032 )*}
3033 }
3034
3035 // unsigned to signed (only positive bound)
3036 macro_rules! try_from_upper_bounded {
3037 ($source:ty, $($target:ty),*) => {$(
3038 #[unstable(feature = "try_from", issue = "33417")]
3039 impl TryFrom<$source> for $target {
3040 type Error = TryFromIntError;
3041
3042 #[inline]
3043 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
3044 if u > (<$target>::max_value() as $source) {
3045 Err(TryFromIntError(()))
3046 } else {
3047 Ok(u as $target)
3048 }
3049 }
3050 }
3051 )*}
3052 }
3053
3054 // all other cases
3055 macro_rules! try_from_both_bounded {
3056 ($source:ty, $($target:ty),*) => {$(
3057 #[unstable(feature = "try_from", issue = "33417")]
3058 impl TryFrom<$source> for $target {
3059 type Error = TryFromIntError;
3060
3061 #[inline]
3062 fn try_from(u: $source) -> Result<$target, TryFromIntError> {
3063 let min = <$target>::min_value() as $source;
3064 let max = <$target>::max_value() as $source;
3065 if u < min || u > max {
3066 Err(TryFromIntError(()))
3067 } else {
3068 Ok(u as $target)
3069 }
3070 }
3071 }
3072 )*}
3073 }
3074
3075 macro_rules! rev {
3076 ($mac:ident, $source:ty, $($target:ty),*) => {$(
3077 $mac!($target, $source);
3078 )*}
3079 }
3080
3081 /// intra-sign conversions
3082 try_from_upper_bounded!(u16, u8);
3083 try_from_upper_bounded!(u32, u16, u8);
3084 try_from_upper_bounded!(u64, u32, u16, u8);
3085 try_from_upper_bounded!(u128, u64, u32, u16, u8);
3086
3087 try_from_both_bounded!(i16, i8);
3088 try_from_both_bounded!(i32, i16, i8);
3089 try_from_both_bounded!(i64, i32, i16, i8);
3090 try_from_both_bounded!(i128, i64, i32, i16, i8);
3091
3092 // unsigned-to-signed
3093 try_from_upper_bounded!(u8, i8);
3094 try_from_upper_bounded!(u16, i8, i16);
3095 try_from_upper_bounded!(u32, i8, i16, i32);
3096 try_from_upper_bounded!(u64, i8, i16, i32, i64);
3097 try_from_upper_bounded!(u128, i8, i16, i32, i64, i128);
3098
3099 // signed-to-unsigned
3100 try_from_lower_bounded!(i8, u8, u16, u32, u64, u128);
3101 try_from_lower_bounded!(i16, u16, u32, u64, u128);
3102 try_from_lower_bounded!(i32, u32, u64, u128);
3103 try_from_lower_bounded!(i64, u64, u128);
3104 try_from_lower_bounded!(i128, u128);
3105 try_from_both_bounded!(i16, u8);
3106 try_from_both_bounded!(i32, u16, u8);
3107 try_from_both_bounded!(i64, u32, u16, u8);
3108 try_from_both_bounded!(i128, u64, u32, u16, u8);
3109
3110 // usize/isize
3111 try_from_upper_bounded!(usize, isize);
3112 try_from_lower_bounded!(isize, usize);
3113
3114 #[cfg(target_pointer_width = "16")]
3115 mod ptr_try_from_impls {
3116 use super::TryFromIntError;
3117 use convert::{Infallible, TryFrom};
3118
3119 try_from_upper_bounded!(usize, u8);
3120 try_from_unbounded!(usize, u16, u32, u64, u128);
3121 try_from_upper_bounded!(usize, i8, i16);
3122 try_from_unbounded!(usize, i32, i64, i128);
3123
3124 try_from_both_bounded!(isize, u8);
3125 try_from_lower_bounded!(isize, u16, u32, u64, u128);
3126 try_from_both_bounded!(isize, i8);
3127 try_from_unbounded!(isize, i16, i32, i64, i128);
3128
3129 rev!(try_from_unbounded, usize, u16);
3130 rev!(try_from_upper_bounded, usize, u32, u64, u128);
3131 rev!(try_from_lower_bounded, usize, i8, i16);
3132 rev!(try_from_both_bounded, usize, i32, i64, i128);
3133
3134 rev!(try_from_unbounded, isize, u8);
3135 rev!(try_from_upper_bounded, isize, u16, u32, u64, u128);
3136 rev!(try_from_unbounded, isize, i16);
3137 rev!(try_from_both_bounded, isize, i32, i64, i128);
3138 }
3139
3140 #[cfg(target_pointer_width = "32")]
3141 mod ptr_try_from_impls {
3142 use super::TryFromIntError;
3143 use convert::{Infallible, TryFrom};
3144
3145 try_from_upper_bounded!(usize, u8, u16);
3146 try_from_unbounded!(usize, u32, u64, u128);
3147 try_from_upper_bounded!(usize, i8, i16, i32);
3148 try_from_unbounded!(usize, i64, i128);
3149
3150 try_from_both_bounded!(isize, u8, u16);
3151 try_from_lower_bounded!(isize, u32, u64, u128);
3152 try_from_both_bounded!(isize, i8, i16);
3153 try_from_unbounded!(isize, i32, i64, i128);
3154
3155 rev!(try_from_unbounded, usize, u16, u32);
3156 rev!(try_from_upper_bounded, usize, u64, u128);
3157 rev!(try_from_lower_bounded, usize, i8, i16, i32);
3158 rev!(try_from_both_bounded, usize, i64, i128);
3159
3160 rev!(try_from_unbounded, isize, u8, u16);
3161 rev!(try_from_upper_bounded, isize, u32, u64, u128);
3162 rev!(try_from_unbounded, isize, i16, i32);
3163 rev!(try_from_both_bounded, isize, i64, i128);
3164 }
3165
3166 #[cfg(target_pointer_width = "64")]
3167 mod ptr_try_from_impls {
3168 use super::TryFromIntError;
3169 use convert::{Infallible, TryFrom};
3170
3171 try_from_upper_bounded!(usize, u8, u16, u32);
3172 try_from_unbounded!(usize, u64, u128);
3173 try_from_upper_bounded!(usize, i8, i16, i32, i64);
3174 try_from_unbounded!(usize, i128);
3175
3176 try_from_both_bounded!(isize, u8, u16, u32);
3177 try_from_lower_bounded!(isize, u64, u128);
3178 try_from_both_bounded!(isize, i8, i16, i32);
3179 try_from_unbounded!(isize, i64, i128);
3180
3181 rev!(try_from_unbounded, usize, u16, u32, u64);
3182 rev!(try_from_upper_bounded, usize, u128);
3183 rev!(try_from_lower_bounded, usize, i8, i16, i32, i64);
3184 rev!(try_from_both_bounded, usize, i128);
3185
3186 rev!(try_from_unbounded, isize, u8, u16, u32);
3187 rev!(try_from_upper_bounded, isize, u64, u128);
3188 rev!(try_from_unbounded, isize, i16, i32, i64);
3189 rev!(try_from_both_bounded, isize, i128);
3190 }
3191
3192 #[doc(hidden)]
3193 trait FromStrRadixHelper: PartialOrd + Copy {
3194 fn min_value() -> Self;
3195 fn max_value() -> Self;
3196 fn from_u32(u: u32) -> Self;
3197 fn checked_mul(&self, other: u32) -> Option<Self>;
3198 fn checked_sub(&self, other: u32) -> Option<Self>;
3199 fn checked_add(&self, other: u32) -> Option<Self>;
3200 }
3201
3202 macro_rules! doit {
3203 ($($t:ty)*) => ($(impl FromStrRadixHelper for $t {
3204 #[inline]
3205 fn min_value() -> Self { Self::min_value() }
3206 #[inline]
3207 fn max_value() -> Self { Self::max_value() }
3208 #[inline]
3209 fn from_u32(u: u32) -> Self { u as Self }
3210 #[inline]
3211 fn checked_mul(&self, other: u32) -> Option<Self> {
3212 Self::checked_mul(*self, other as Self)
3213 }
3214 #[inline]
3215 fn checked_sub(&self, other: u32) -> Option<Self> {
3216 Self::checked_sub(*self, other as Self)
3217 }
3218 #[inline]
3219 fn checked_add(&self, other: u32) -> Option<Self> {
3220 Self::checked_add(*self, other as Self)
3221 }
3222 })*)
3223 }
3224 doit! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }
3225
3226 fn from_str_radix<T: FromStrRadixHelper>(src: &str, radix: u32) -> Result<T, ParseIntError> {
3227 use self::IntErrorKind::*;
3228 use self::ParseIntError as PIE;
3229
3230 assert!(radix >= 2 && radix <= 36,
3231 "from_str_radix_int: must lie in the range `[2, 36]` - found {}",
3232 radix);
3233
3234 if src.is_empty() {
3235 return Err(PIE { kind: Empty });
3236 }
3237
3238 let is_signed_ty = T::from_u32(0) > T::min_value();
3239
3240 // all valid digits are ascii, so we will just iterate over the utf8 bytes
3241 // and cast them to chars. .to_digit() will safely return None for anything
3242 // other than a valid ascii digit for the given radix, including the first-byte
3243 // of multi-byte sequences
3244 let src = src.as_bytes();
3245
3246 let (is_positive, digits) = match src[0] {
3247 b'+' => (true, &src[1..]),
3248 b'-' if is_signed_ty => (false, &src[1..]),
3249 _ => (true, src),
3250 };
3251
3252 if digits.is_empty() {
3253 return Err(PIE { kind: Empty });
3254 }
3255
3256 let mut result = T::from_u32(0);
3257 if is_positive {
3258 // The number is positive
3259 for &c in digits {
3260 let x = match (c as char).to_digit(radix) {
3261 Some(x) => x,
3262 None => return Err(PIE { kind: InvalidDigit }),
3263 };
3264 result = match result.checked_mul(radix) {
3265 Some(result) => result,
3266 None => return Err(PIE { kind: Overflow }),
3267 };
3268 result = match result.checked_add(x) {
3269 Some(result) => result,
3270 None => return Err(PIE { kind: Overflow }),
3271 };
3272 }
3273 } else {
3274 // The number is negative
3275 for &c in digits {
3276 let x = match (c as char).to_digit(radix) {
3277 Some(x) => x,
3278 None => return Err(PIE { kind: InvalidDigit }),
3279 };
3280 result = match result.checked_mul(radix) {
3281 Some(result) => result,
3282 None => return Err(PIE { kind: Underflow }),
3283 };
3284 result = match result.checked_sub(x) {
3285 Some(result) => result,
3286 None => return Err(PIE { kind: Underflow }),
3287 };
3288 }
3289 }
3290 Ok(result)
3291 }
3292
3293 /// An error which can be returned when parsing an integer.
3294 ///
3295 /// This error is used as the error type for the `from_str_radix()` functions
3296 /// on the primitive integer types, such as [`i8::from_str_radix`].
3297 ///
3298 /// [`i8::from_str_radix`]: ../../std/primitive.i8.html#method.from_str_radix
3299 #[derive(Debug, Clone, PartialEq, Eq)]
3300 #[stable(feature = "rust1", since = "1.0.0")]
3301 pub struct ParseIntError {
3302 kind: IntErrorKind,
3303 }
3304
3305 #[derive(Debug, Clone, PartialEq, Eq)]
3306 enum IntErrorKind {
3307 Empty,
3308 InvalidDigit,
3309 Overflow,
3310 Underflow,
3311 }
3312
3313 impl ParseIntError {
3314 #[unstable(feature = "int_error_internals",
3315 reason = "available through Error trait and this method should \
3316 not be exposed publicly",
3317 issue = "0")]
3318 #[doc(hidden)]
3319 pub fn __description(&self) -> &str {
3320 match self.kind {
3321 IntErrorKind::Empty => "cannot parse integer from empty string",
3322 IntErrorKind::InvalidDigit => "invalid digit found in string",
3323 IntErrorKind::Overflow => "number too large to fit in target type",
3324 IntErrorKind::Underflow => "number too small to fit in target type",
3325 }
3326 }
3327 }
3328
3329 #[stable(feature = "rust1", since = "1.0.0")]
3330 impl fmt::Display for ParseIntError {
3331 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
3332 self.__description().fmt(f)
3333 }
3334 }
3335
3336 #[stable(feature = "rust1", since = "1.0.0")]
3337 pub use num::dec2flt::ParseFloatError;
3338
3339 // Conversion traits for primitive integer and float types
3340 // Conversions T -> T are covered by a blanket impl and therefore excluded
3341 // Some conversions from and to usize/isize are not implemented due to portability concerns
3342 macro_rules! impl_from {
3343 ($Small: ty, $Large: ty, #[$attr:meta]) => {
3344 #[$attr]
3345 impl From<$Small> for $Large {
3346 #[inline]
3347 fn from(small: $Small) -> $Large {
3348 small as $Large
3349 }
3350 }
3351 }
3352 }
3353
3354 // Unsigned -> Unsigned
3355 impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3356 impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3357 impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3358 impl_from! { u8, u128, #[unstable(feature = "i128", issue = "35118")] }
3359 impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3360 impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3361 impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3362 impl_from! { u16, u128, #[unstable(feature = "i128", issue = "35118")] }
3363 impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3364 impl_from! { u32, u128, #[unstable(feature = "i128", issue = "35118")] }
3365 impl_from! { u64, u128, #[unstable(feature = "i128", issue = "35118")] }
3366
3367 // Signed -> Signed
3368 impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3369 impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3370 impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3371 impl_from! { i8, i128, #[unstable(feature = "i128", issue = "35118")] }
3372 impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3373 impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3374 impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3375 impl_from! { i16, i128, #[unstable(feature = "i128", issue = "35118")] }
3376 impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3377 impl_from! { i32, i128, #[unstable(feature = "i128", issue = "35118")] }
3378 impl_from! { i64, i128, #[unstable(feature = "i128", issue = "35118")] }
3379
3380 // Unsigned -> Signed
3381 impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3382 impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3383 impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3384 impl_from! { u8, i128, #[unstable(feature = "i128", issue = "35118")] }
3385 impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3386 impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3387 impl_from! { u16, i128, #[unstable(feature = "i128", issue = "35118")] }
3388 impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] }
3389 impl_from! { u32, i128, #[unstable(feature = "i128", issue = "35118")] }
3390 impl_from! { u64, i128, #[unstable(feature = "i128", issue = "35118")] }
3391
3392 // Note: integers can only be represented with full precision in a float if
3393 // they fit in the significand, which is 24 bits in f32 and 53 bits in f64.
3394 // Lossy float conversions are not implemented at this time.
3395
3396 // Signed -> Float
3397 impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3398 impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3399 impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3400 impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3401 impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3402
3403 // Unsigned -> Float
3404 impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3405 impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3406 impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3407 impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3408 impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3409
3410 // Float -> Float
3411 impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] }
3412
3413 static ASCII_LOWERCASE_MAP: [u8; 256] = [
3414 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
3415 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
3416 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
3417 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
3418 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
3419 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
3420 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
3421 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
3422 b'@',
3423
3424 b'a', b'b', b'c', b'd', b'e', b'f', b'g',
3425 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
3426 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
3427 b'x', b'y', b'z',
3428
3429 b'[', b'\\', b']', b'^', b'_',
3430 b'`', b'a', b'b', b'c', b'd', b'e', b'f', b'g',
3431 b'h', b'i', b'j', b'k', b'l', b'm', b'n', b'o',
3432 b'p', b'q', b'r', b's', b't', b'u', b'v', b'w',
3433 b'x', b'y', b'z', b'{', b'|', b'}', b'~', 0x7f,
3434 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
3435 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
3436 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
3437 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
3438 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
3439 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
3440 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
3441 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
3442 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
3443 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
3444 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
3445 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
3446 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
3447 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
3448 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
3449 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
3450 ];
3451
3452 static ASCII_UPPERCASE_MAP: [u8; 256] = [
3453 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
3454 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
3455 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
3456 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
3457 b' ', b'!', b'"', b'#', b'$', b'%', b'&', b'\'',
3458 b'(', b')', b'*', b'+', b',', b'-', b'.', b'/',
3459 b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7',
3460 b'8', b'9', b':', b';', b'<', b'=', b'>', b'?',
3461 b'@', b'A', b'B', b'C', b'D', b'E', b'F', b'G',
3462 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
3463 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
3464 b'X', b'Y', b'Z', b'[', b'\\', b']', b'^', b'_',
3465 b'`',
3466
3467 b'A', b'B', b'C', b'D', b'E', b'F', b'G',
3468 b'H', b'I', b'J', b'K', b'L', b'M', b'N', b'O',
3469 b'P', b'Q', b'R', b'S', b'T', b'U', b'V', b'W',
3470 b'X', b'Y', b'Z',
3471
3472 b'{', b'|', b'}', b'~', 0x7f,
3473 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
3474 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
3475 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
3476 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
3477 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
3478 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
3479 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
3480 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
3481 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
3482 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
3483 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
3484 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
3485 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
3486 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
3487 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
3488 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff,
3489 ];
3490
3491 enum AsciiCharacterClass {
3492 C, // control
3493 Cw, // control whitespace
3494 W, // whitespace
3495 D, // digit
3496 L, // lowercase
3497 Lx, // lowercase hex digit
3498 U, // uppercase
3499 Ux, // uppercase hex digit
3500 P, // punctuation
3501 }
3502 use self::AsciiCharacterClass::*;
3503
3504 static ASCII_CHARACTER_CLASS: [AsciiCharacterClass; 128] = [
3505 // _0 _1 _2 _3 _4 _5 _6 _7 _8 _9 _a _b _c _d _e _f
3506 C, C, C, C, C, C, C, C, C, Cw,Cw,C, Cw,Cw,C, C, // 0_
3507 C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, C, // 1_
3508 W, P, P, P, P, P, P, P, P, P, P, P, P, P, P, P, // 2_
3509 D, D, D, D, D, D, D, D, D, D, P, P, P, P, P, P, // 3_
3510 P, Ux,Ux,Ux,Ux,Ux,Ux,U, U, U, U, U, U, U, U, U, // 4_
3511 U, U, U, U, U, U, U, U, U, U, U, P, P, P, P, P, // 5_
3512 P, Lx,Lx,Lx,Lx,Lx,Lx,L, L, L, L, L, L, L, L, L, // 6_
3513 L, L, L, L, L, L, L, L, L, L, L, P, P, P, P, C, // 7_
3514 ];