1 macro_rules! uint_impl { 2 ( 3 Self = $SelfT:ty, 4 ActualT = $ActualT:ident, 5 SignedT = $SignedT:ident, 6 NonZeroT = $NonZeroT:ident, 7 8 // There are all for use *only* in doc comments. 9 // As such, they're all passed as literals -- passing them as a string 10 // literal is fine if they need to be multiple code tokens. 11 // In non-comments, use the associated constants rather than these. 12 BITS = $BITS:literal, 13 MAX = $MaxV:literal, 14 rot = $rot:literal, 15 rot_op = $rot_op:literal, 16 rot_result = $rot_result:literal, 17 swap_op = $swap_op:literal, 18 swapped = $swapped:literal, 19 reversed = $reversed:literal, 20 le_bytes = $le_bytes:literal, 21 be_bytes = $be_bytes:literal, 22 to_xe_bytes_doc = $to_xe_bytes_doc:expr, 23 from_xe_bytes_doc = $from_xe_bytes_doc:expr, 24 bound_condition = $bound_condition:literal, 25 ) => { 26 /// The smallest value that can be represented by this integer type. 27 /// 28 /// # Examples 29 /// 30 /// Basic usage: 31 /// 32 /// ``` 33 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN, 0);")] 34 /// ``` 35 #[stable(feature = "assoc_int_consts", since = "1.43.0")] 36 pub const MIN: Self = 0; 37 38 /// The largest value that can be represented by this integer type 39 #[doc = concat!("(2<sup>", $BITS, "</sup> − 1", $bound_condition, ").")] 40 /// 41 /// # Examples 42 /// 43 /// Basic usage: 44 /// 45 /// ``` 46 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($MaxV), ");")] 47 /// ``` 48 #[stable(feature = "assoc_int_consts", since = "1.43.0")] 49 pub const MAX: Self = !0; 50 51 /// The size of this integer type in bits. 52 /// 53 /// # Examples 54 /// 55 /// ``` 56 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::BITS, ", stringify!($BITS), ");")] 57 /// ``` 58 #[stable(feature = "int_bits_const", since = "1.53.0")] 59 pub const BITS: u32 = Self::MAX.count_ones(); 60 61 /// Converts a string slice in a given base to an integer. 62 /// 63 /// The string is expected to be an optional `+` sign 64 /// followed by digits. 65 /// Leading and trailing whitespace represent an error. 66 /// Digits are a subset of these characters, depending on `radix`: 67 /// 68 /// * `0-9` 69 /// * `a-z` 70 /// * `A-Z` 71 /// 72 /// # Panics 73 /// 74 /// This function panics if `radix` is not in the range from 2 to 36. 75 /// 76 /// # Examples 77 /// 78 /// Basic usage: 79 /// 80 /// ``` 81 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::from_str_radix(\"A\", 16), Ok(10));")] 82 /// ``` 83 #[stable(feature = "rust1", since = "1.0.0")] 84 pub fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError> { 85 from_str_radix(src, radix) 86 } 87 88 /// Returns the number of ones in the binary representation of `self`. 89 /// 90 /// # Examples 91 /// 92 /// Basic usage: 93 /// 94 /// ``` 95 #[doc = concat!("let n = 0b01001100", stringify!($SelfT), ";")] 96 /// 97 /// assert_eq!(n.count_ones(), 3); 98 /// ``` 99 #[stable(feature = "rust1", since = "1.0.0")] 100 #[rustc_const_stable(feature = "const_math", since = "1.32.0")] 101 #[doc(alias = "popcount")] 102 #[doc(alias = "popcnt")] 103 #[must_use = "this returns the result of the operation, \ 104 without modifying the original"] 105 #[inline(always)] 106 pub const fn count_ones(self) -> u32 { 107 intrinsics::ctpop(self as $ActualT) as u32 108 } 109 110 /// Returns the number of zeros in the binary representation of `self`. 111 /// 112 /// # Examples 113 /// 114 /// Basic usage: 115 /// 116 /// ``` 117 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.count_zeros(), 0);")] 118 /// ``` 119 #[stable(feature = "rust1", since = "1.0.0")] 120 #[rustc_const_stable(feature = "const_math", since = "1.32.0")] 121 #[must_use = "this returns the result of the operation, \ 122 without modifying the original"] 123 #[inline(always)] 124 pub const fn count_zeros(self) -> u32 { 125 (!self).count_ones() 126 } 127 128 /// Returns the number of leading zeros in the binary representation of `self`. 129 /// 130 /// Depending on what you're doing with the value, you might also be interested in the 131 /// [`ilog2`] function which returns a consistent number, even if the type widens. 132 /// 133 /// # Examples 134 /// 135 /// Basic usage: 136 /// 137 /// ``` 138 #[doc = concat!("let n = ", stringify!($SelfT), "::MAX >> 2;")] 139 /// 140 /// assert_eq!(n.leading_zeros(), 2); 141 /// ``` 142 #[doc = concat!("[`ilog2`]: ", stringify!($SelfT), "::ilog2")] 143 #[stable(feature = "rust1", since = "1.0.0")] 144 #[rustc_const_stable(feature = "const_math", since = "1.32.0")] 145 #[must_use = "this returns the result of the operation, \ 146 without modifying the original"] 147 #[inline(always)] 148 pub const fn leading_zeros(self) -> u32 { 149 intrinsics::ctlz(self as $ActualT) as u32 150 } 151 152 /// Returns the number of trailing zeros in the binary representation 153 /// of `self`. 154 /// 155 /// # Examples 156 /// 157 /// Basic usage: 158 /// 159 /// ``` 160 #[doc = concat!("let n = 0b0101000", stringify!($SelfT), ";")] 161 /// 162 /// assert_eq!(n.trailing_zeros(), 3); 163 /// ``` 164 #[stable(feature = "rust1", since = "1.0.0")] 165 #[rustc_const_stable(feature = "const_math", since = "1.32.0")] 166 #[must_use = "this returns the result of the operation, \ 167 without modifying the original"] 168 #[inline(always)] 169 pub const fn trailing_zeros(self) -> u32 { 170 intrinsics::cttz(self) as u32 171 } 172 173 /// Returns the number of leading ones in the binary representation of `self`. 174 /// 175 /// # Examples 176 /// 177 /// Basic usage: 178 /// 179 /// ``` 180 #[doc = concat!("let n = !(", stringify!($SelfT), "::MAX >> 2);")] 181 /// 182 /// assert_eq!(n.leading_ones(), 2); 183 /// ``` 184 #[stable(feature = "leading_trailing_ones", since = "1.46.0")] 185 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")] 186 #[must_use = "this returns the result of the operation, \ 187 without modifying the original"] 188 #[inline(always)] 189 pub const fn leading_ones(self) -> u32 { 190 (!self).leading_zeros() 191 } 192 193 /// Returns the number of trailing ones in the binary representation 194 /// of `self`. 195 /// 196 /// # Examples 197 /// 198 /// Basic usage: 199 /// 200 /// ``` 201 #[doc = concat!("let n = 0b1010111", stringify!($SelfT), ";")] 202 /// 203 /// assert_eq!(n.trailing_ones(), 3); 204 /// ``` 205 #[stable(feature = "leading_trailing_ones", since = "1.46.0")] 206 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")] 207 #[must_use = "this returns the result of the operation, \ 208 without modifying the original"] 209 #[inline(always)] 210 pub const fn trailing_ones(self) -> u32 { 211 (!self).trailing_zeros() 212 } 213 214 /// Shifts the bits to the left by a specified amount, `n`, 215 /// wrapping the truncated bits to the end of the resulting integer. 216 /// 217 /// Please note this isn't the same operation as the `<<` shifting operator! 218 /// 219 /// # Examples 220 /// 221 /// Basic usage: 222 /// 223 /// ``` 224 #[doc = concat!("let n = ", $rot_op, stringify!($SelfT), ";")] 225 #[doc = concat!("let m = ", $rot_result, ";")] 226 /// 227 #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")] 228 /// ``` 229 #[stable(feature = "rust1", since = "1.0.0")] 230 #[rustc_const_stable(feature = "const_math", since = "1.32.0")] 231 #[must_use = "this returns the result of the operation, \ 232 without modifying the original"] 233 #[inline(always)] 234 pub const fn rotate_left(self, n: u32) -> Self { 235 intrinsics::rotate_left(self, n as $SelfT) 236 } 237 238 /// Shifts the bits to the right by a specified amount, `n`, 239 /// wrapping the truncated bits to the beginning of the resulting 240 /// integer. 241 /// 242 /// Please note this isn't the same operation as the `>>` shifting operator! 243 /// 244 /// # Examples 245 /// 246 /// Basic usage: 247 /// 248 /// ``` 249 #[doc = concat!("let n = ", $rot_result, stringify!($SelfT), ";")] 250 #[doc = concat!("let m = ", $rot_op, ";")] 251 /// 252 #[doc = concat!("assert_eq!(n.rotate_right(", $rot, "), m);")] 253 /// ``` 254 #[stable(feature = "rust1", since = "1.0.0")] 255 #[rustc_const_stable(feature = "const_math", since = "1.32.0")] 256 #[must_use = "this returns the result of the operation, \ 257 without modifying the original"] 258 #[inline(always)] 259 pub const fn rotate_right(self, n: u32) -> Self { 260 intrinsics::rotate_right(self, n as $SelfT) 261 } 262 263 /// Reverses the byte order of the integer. 264 /// 265 /// # Examples 266 /// 267 /// Basic usage: 268 /// 269 /// ``` 270 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")] 271 /// let m = n.swap_bytes(); 272 /// 273 #[doc = concat!("assert_eq!(m, ", $swapped, ");")] 274 /// ``` 275 #[stable(feature = "rust1", since = "1.0.0")] 276 #[rustc_const_stable(feature = "const_math", since = "1.32.0")] 277 #[must_use = "this returns the result of the operation, \ 278 without modifying the original"] 279 #[inline(always)] 280 pub const fn swap_bytes(self) -> Self { 281 intrinsics::bswap(self as $ActualT) as Self 282 } 283 284 /// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit, 285 /// second least-significant bit becomes second most-significant bit, etc. 286 /// 287 /// # Examples 288 /// 289 /// Basic usage: 290 /// 291 /// ``` 292 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")] 293 /// let m = n.reverse_bits(); 294 /// 295 #[doc = concat!("assert_eq!(m, ", $reversed, ");")] 296 #[doc = concat!("assert_eq!(0, 0", stringify!($SelfT), ".reverse_bits());")] 297 /// ``` 298 #[stable(feature = "reverse_bits", since = "1.37.0")] 299 #[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")] 300 #[must_use = "this returns the result of the operation, \ 301 without modifying the original"] 302 #[inline(always)] 303 pub const fn reverse_bits(self) -> Self { 304 intrinsics::bitreverse(self as $ActualT) as Self 305 } 306 307 /// Converts an integer from big endian to the target's endianness. 308 /// 309 /// On big endian this is a no-op. On little endian the bytes are 310 /// swapped. 311 /// 312 /// # Examples 313 /// 314 /// Basic usage: 315 /// 316 /// ``` 317 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")] 318 /// 319 /// if cfg!(target_endian = "big") { 320 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n)")] 321 /// } else { 322 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())")] 323 /// } 324 /// ``` 325 #[stable(feature = "rust1", since = "1.0.0")] 326 #[rustc_const_stable(feature = "const_math", since = "1.32.0")] 327 #[must_use] 328 #[inline(always)] 329 pub const fn from_be(x: Self) -> Self { 330 #[cfg(target_endian = "big")] 331 { 332 x 333 } 334 #[cfg(not(target_endian = "big"))] 335 { 336 x.swap_bytes() 337 } 338 } 339 340 /// Converts an integer from little endian to the target's endianness. 341 /// 342 /// On little endian this is a no-op. On big endian the bytes are 343 /// swapped. 344 /// 345 /// # Examples 346 /// 347 /// Basic usage: 348 /// 349 /// ``` 350 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")] 351 /// 352 /// if cfg!(target_endian = "little") { 353 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n)")] 354 /// } else { 355 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())")] 356 /// } 357 /// ``` 358 #[stable(feature = "rust1", since = "1.0.0")] 359 #[rustc_const_stable(feature = "const_math", since = "1.32.0")] 360 #[must_use] 361 #[inline(always)] 362 pub const fn from_le(x: Self) -> Self { 363 #[cfg(target_endian = "little")] 364 { 365 x 366 } 367 #[cfg(not(target_endian = "little"))] 368 { 369 x.swap_bytes() 370 } 371 } 372 373 /// Converts `self` to big endian from the target's endianness. 374 /// 375 /// On big endian this is a no-op. On little endian the bytes are 376 /// swapped. 377 /// 378 /// # Examples 379 /// 380 /// Basic usage: 381 /// 382 /// ``` 383 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")] 384 /// 385 /// if cfg!(target_endian = "big") { 386 /// assert_eq!(n.to_be(), n) 387 /// } else { 388 /// assert_eq!(n.to_be(), n.swap_bytes()) 389 /// } 390 /// ``` 391 #[stable(feature = "rust1", since = "1.0.0")] 392 #[rustc_const_stable(feature = "const_math", since = "1.32.0")] 393 #[must_use = "this returns the result of the operation, \ 394 without modifying the original"] 395 #[inline(always)] 396 pub const fn to_be(self) -> Self { // or not to be? 397 #[cfg(target_endian = "big")] 398 { 399 self 400 } 401 #[cfg(not(target_endian = "big"))] 402 { 403 self.swap_bytes() 404 } 405 } 406 407 /// Converts `self` to little endian from the target's endianness. 408 /// 409 /// On little endian this is a no-op. On big endian the bytes are 410 /// swapped. 411 /// 412 /// # Examples 413 /// 414 /// Basic usage: 415 /// 416 /// ``` 417 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")] 418 /// 419 /// if cfg!(target_endian = "little") { 420 /// assert_eq!(n.to_le(), n) 421 /// } else { 422 /// assert_eq!(n.to_le(), n.swap_bytes()) 423 /// } 424 /// ``` 425 #[stable(feature = "rust1", since = "1.0.0")] 426 #[rustc_const_stable(feature = "const_math", since = "1.32.0")] 427 #[must_use = "this returns the result of the operation, \ 428 without modifying the original"] 429 #[inline(always)] 430 pub const fn to_le(self) -> Self { 431 #[cfg(target_endian = "little")] 432 { 433 self 434 } 435 #[cfg(not(target_endian = "little"))] 436 { 437 self.swap_bytes() 438 } 439 } 440 441 /// Checked integer addition. Computes `self + rhs`, returning `None` 442 /// if overflow occurred. 443 /// 444 /// # Examples 445 /// 446 /// Basic usage: 447 /// 448 /// ``` 449 #[doc = concat!( 450 "assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), ", 451 "Some(", stringify!($SelfT), "::MAX - 1));" 452 )] 453 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")] 454 /// ``` 455 #[stable(feature = "rust1", since = "1.0.0")] 456 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")] 457 #[must_use = "this returns the result of the operation, \ 458 without modifying the original"] 459 #[inline] 460 pub const fn checked_add(self, rhs: Self) -> Option<Self> { 461 let (a, b) = self.overflowing_add(rhs); 462 if unlikely!(b) {None} else {Some(a)} 463 } 464 465 /// Unchecked integer addition. Computes `self + rhs`, assuming overflow 466 /// cannot occur. 467 /// 468 /// # Safety 469 /// 470 /// This results in undefined behavior when 471 #[doc = concat!("`self + rhs > ", stringify!($SelfT), "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`,")] 472 /// i.e. when [`checked_add`] would return `None`. 473 /// 474 #[doc = concat!("[`checked_add`]: ", stringify!($SelfT), "::checked_add")] 475 #[unstable( 476 feature = "unchecked_math", 477 reason = "niche optimization path", 478 issue = "85122", 479 )] 480 #[must_use = "this returns the result of the operation, \ 481 without modifying the original"] 482 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")] 483 #[inline(always)] 484 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces 485 pub const unsafe fn unchecked_add(self, rhs: Self) -> Self { 486 // SAFETY: the caller must uphold the safety contract for 487 // `unchecked_add`. 488 unsafe { intrinsics::unchecked_add(self, rhs) } 489 } 490 491 /// Checked addition with a signed integer. Computes `self + rhs`, 492 /// returning `None` if overflow occurred. 493 /// 494 /// # Examples 495 /// 496 /// Basic usage: 497 /// 498 /// ``` 499 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_signed(2), Some(3));")] 500 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_signed(-2), None);")] 501 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add_signed(3), None);")] 502 /// ``` 503 #[stable(feature = "mixed_integer_ops", since = "1.66.0")] 504 #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")] 505 #[must_use = "this returns the result of the operation, \ 506 without modifying the original"] 507 #[inline] 508 pub const fn checked_add_signed(self, rhs: $SignedT) -> Option<Self> { 509 let (a, b) = self.overflowing_add_signed(rhs); 510 if unlikely!(b) {None} else {Some(a)} 511 } 512 513 /// Checked integer subtraction. Computes `self - rhs`, returning 514 /// `None` if overflow occurred. 515 /// 516 /// # Examples 517 /// 518 /// Basic usage: 519 /// 520 /// ``` 521 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));")] 522 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);")] 523 /// ``` 524 #[stable(feature = "rust1", since = "1.0.0")] 525 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")] 526 #[must_use = "this returns the result of the operation, \ 527 without modifying the original"] 528 #[inline] 529 pub const fn checked_sub(self, rhs: Self) -> Option<Self> { 530 let (a, b) = self.overflowing_sub(rhs); 531 if unlikely!(b) {None} else {Some(a)} 532 } 533 534 /// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow 535 /// cannot occur. 536 /// 537 /// # Safety 538 /// 539 /// This results in undefined behavior when 540 #[doc = concat!("`self - rhs > ", stringify!($SelfT), "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`,")] 541 /// i.e. when [`checked_sub`] would return `None`. 542 /// 543 #[doc = concat!("[`checked_sub`]: ", stringify!($SelfT), "::checked_sub")] 544 #[unstable( 545 feature = "unchecked_math", 546 reason = "niche optimization path", 547 issue = "85122", 548 )] 549 #[must_use = "this returns the result of the operation, \ 550 without modifying the original"] 551 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")] 552 #[inline(always)] 553 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces 554 pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self { 555 // SAFETY: the caller must uphold the safety contract for 556 // `unchecked_sub`. 557 unsafe { intrinsics::unchecked_sub(self, rhs) } 558 } 559 560 /// Checked integer multiplication. Computes `self * rhs`, returning 561 /// `None` if overflow occurred. 562 /// 563 /// # Examples 564 /// 565 /// Basic usage: 566 /// 567 /// ``` 568 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));")] 569 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);")] 570 /// ``` 571 #[stable(feature = "rust1", since = "1.0.0")] 572 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")] 573 #[must_use = "this returns the result of the operation, \ 574 without modifying the original"] 575 #[inline] 576 pub const fn checked_mul(self, rhs: Self) -> Option<Self> { 577 let (a, b) = self.overflowing_mul(rhs); 578 if unlikely!(b) {None} else {Some(a)} 579 } 580 581 /// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow 582 /// cannot occur. 583 /// 584 /// # Safety 585 /// 586 /// This results in undefined behavior when 587 #[doc = concat!("`self * rhs > ", stringify!($SelfT), "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`,")] 588 /// i.e. when [`checked_mul`] would return `None`. 589 /// 590 #[doc = concat!("[`checked_mul`]: ", stringify!($SelfT), "::checked_mul")] 591 #[unstable( 592 feature = "unchecked_math", 593 reason = "niche optimization path", 594 issue = "85122", 595 )] 596 #[must_use = "this returns the result of the operation, \ 597 without modifying the original"] 598 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")] 599 #[inline(always)] 600 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces 601 pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self { 602 // SAFETY: the caller must uphold the safety contract for 603 // `unchecked_mul`. 604 unsafe { intrinsics::unchecked_mul(self, rhs) } 605 } 606 607 /// Checked integer division. Computes `self / rhs`, returning `None` 608 /// if `rhs == 0`. 609 /// 610 /// # Examples 611 /// 612 /// Basic usage: 613 /// 614 /// ``` 615 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));")] 616 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);")] 617 /// ``` 618 #[stable(feature = "rust1", since = "1.0.0")] 619 #[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")] 620 #[must_use = "this returns the result of the operation, \ 621 without modifying the original"] 622 #[inline] 623 pub const fn checked_div(self, rhs: Self) -> Option<Self> { 624 if unlikely!(rhs == 0) { 625 None 626 } else { 627 // SAFETY: div by zero has been checked above and unsigned types have no other 628 // failure modes for division 629 Some(unsafe { intrinsics::unchecked_div(self, rhs) }) 630 } 631 } 632 633 /// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None` 634 /// if `rhs == 0`. 635 /// 636 /// # Examples 637 /// 638 /// Basic usage: 639 /// 640 /// ``` 641 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));")] 642 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);")] 643 /// ``` 644 #[stable(feature = "euclidean_division", since = "1.38.0")] 645 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")] 646 #[must_use = "this returns the result of the operation, \ 647 without modifying the original"] 648 #[inline] 649 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> { 650 if unlikely!(rhs == 0) { 651 None 652 } else { 653 Some(self.div_euclid(rhs)) 654 } 655 } 656 657 658 /// Checked integer remainder. Computes `self % rhs`, returning `None` 659 /// if `rhs == 0`. 660 /// 661 /// # Examples 662 /// 663 /// Basic usage: 664 /// 665 /// ``` 666 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));")] 667 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);")] 668 /// ``` 669 #[stable(feature = "wrapping", since = "1.7.0")] 670 #[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")] 671 #[must_use = "this returns the result of the operation, \ 672 without modifying the original"] 673 #[inline] 674 pub const fn checked_rem(self, rhs: Self) -> Option<Self> { 675 if unlikely!(rhs == 0) { 676 None 677 } else { 678 // SAFETY: div by zero has been checked above and unsigned types have no other 679 // failure modes for division 680 Some(unsafe { intrinsics::unchecked_rem(self, rhs) }) 681 } 682 } 683 684 /// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None` 685 /// if `rhs == 0`. 686 /// 687 /// # Examples 688 /// 689 /// Basic usage: 690 /// 691 /// ``` 692 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));")] 693 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);")] 694 /// ``` 695 #[stable(feature = "euclidean_division", since = "1.38.0")] 696 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")] 697 #[must_use = "this returns the result of the operation, \ 698 without modifying the original"] 699 #[inline] 700 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> { 701 if unlikely!(rhs == 0) { 702 None 703 } else { 704 Some(self.rem_euclid(rhs)) 705 } 706 } 707 708 /// Returns the logarithm of the number with respect to an arbitrary base, 709 /// rounded down. 710 /// 711 /// This method might not be optimized owing to implementation details; 712 /// `ilog2` can produce results more efficiently for base 2, and `ilog10` 713 /// can produce results more efficiently for base 10. 714 /// 715 /// # Panics 716 /// 717 /// This function will panic if `self` is zero, or if `base` is less than 2. 718 /// 719 /// # Examples 720 /// 721 /// ``` 722 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".ilog(5), 1);")] 723 /// ``` 724 #[stable(feature = "int_log", since = "1.67.0")] 725 #[rustc_const_stable(feature = "int_log", since = "1.67.0")] 726 #[must_use = "this returns the result of the operation, \ 727 without modifying the original"] 728 #[inline] 729 #[track_caller] 730 pub const fn ilog(self, base: Self) -> u32 { 731 assert!(base >= 2, "base of integer logarithm must be at least 2"); 732 if let Some(log) = self.checked_ilog(base) { 733 log 734 } else { 735 int_log10::panic_for_nonpositive_argument() 736 } 737 } 738 739 /// Returns the base 2 logarithm of the number, rounded down. 740 /// 741 /// # Panics 742 /// 743 /// This function will panic if `self` is zero. 744 /// 745 /// # Examples 746 /// 747 /// ``` 748 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".ilog2(), 1);")] 749 /// ``` 750 #[stable(feature = "int_log", since = "1.67.0")] 751 #[rustc_const_stable(feature = "int_log", since = "1.67.0")] 752 #[must_use = "this returns the result of the operation, \ 753 without modifying the original"] 754 #[inline] 755 #[track_caller] 756 pub const fn ilog2(self) -> u32 { 757 if let Some(log) = self.checked_ilog2() { 758 log 759 } else { 760 int_log10::panic_for_nonpositive_argument() 761 } 762 } 763 764 /// Returns the base 10 logarithm of the number, rounded down. 765 /// 766 /// # Panics 767 /// 768 /// This function will panic if `self` is zero. 769 /// 770 /// # Example 771 /// 772 /// ``` 773 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".ilog10(), 1);")] 774 /// ``` 775 #[stable(feature = "int_log", since = "1.67.0")] 776 #[rustc_const_stable(feature = "int_log", since = "1.67.0")] 777 #[must_use = "this returns the result of the operation, \ 778 without modifying the original"] 779 #[inline] 780 #[track_caller] 781 pub const fn ilog10(self) -> u32 { 782 if let Some(log) = self.checked_ilog10() { 783 log 784 } else { 785 int_log10::panic_for_nonpositive_argument() 786 } 787 } 788 789 /// Returns the logarithm of the number with respect to an arbitrary base, 790 /// rounded down. 791 /// 792 /// Returns `None` if the number is zero, or if the base is not at least 2. 793 /// 794 /// This method might not be optimized owing to implementation details; 795 /// `checked_ilog2` can produce results more efficiently for base 2, and 796 /// `checked_ilog10` can produce results more efficiently for base 10. 797 /// 798 /// # Examples 799 /// 800 /// ``` 801 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_ilog(5), Some(1));")] 802 /// ``` 803 #[stable(feature = "int_log", since = "1.67.0")] 804 #[rustc_const_stable(feature = "int_log", since = "1.67.0")] 805 #[must_use = "this returns the result of the operation, \ 806 without modifying the original"] 807 #[inline] 808 pub const fn checked_ilog(self, base: Self) -> Option<u32> { 809 if self <= 0 || base <= 1 { 810 None 811 } else { 812 let mut n = 0; 813 let mut r = self; 814 815 // Optimization for 128 bit wide integers. 816 if Self::BITS == 128 { 817 let b = Self::ilog2(self) / (Self::ilog2(base) + 1); 818 n += b; 819 r /= base.pow(b as u32); 820 } 821 822 while r >= base { 823 r /= base; 824 n += 1; 825 } 826 Some(n) 827 } 828 } 829 830 /// Returns the base 2 logarithm of the number, rounded down. 831 /// 832 /// Returns `None` if the number is zero. 833 /// 834 /// # Examples 835 /// 836 /// ``` 837 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_ilog2(), Some(1));")] 838 /// ``` 839 #[stable(feature = "int_log", since = "1.67.0")] 840 #[rustc_const_stable(feature = "int_log", since = "1.67.0")] 841 #[must_use = "this returns the result of the operation, \ 842 without modifying the original"] 843 #[inline] 844 pub const fn checked_ilog2(self) -> Option<u32> { 845 if let Some(x) = <$NonZeroT>::new(self) { 846 Some(x.ilog2()) 847 } else { 848 None 849 } 850 } 851 852 /// Returns the base 10 logarithm of the number, rounded down. 853 /// 854 /// Returns `None` if the number is zero. 855 /// 856 /// # Examples 857 /// 858 /// ``` 859 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_ilog10(), Some(1));")] 860 /// ``` 861 #[stable(feature = "int_log", since = "1.67.0")] 862 #[rustc_const_stable(feature = "int_log", since = "1.67.0")] 863 #[must_use = "this returns the result of the operation, \ 864 without modifying the original"] 865 #[inline] 866 pub const fn checked_ilog10(self) -> Option<u32> { 867 if let Some(x) = <$NonZeroT>::new(self) { 868 Some(x.ilog10()) 869 } else { 870 None 871 } 872 } 873 874 /// Checked negation. Computes `-self`, returning `None` unless `self == 875 /// 0`. 876 /// 877 /// Note that negating any positive integer will overflow. 878 /// 879 /// # Examples 880 /// 881 /// Basic usage: 882 /// 883 /// ``` 884 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));")] 885 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);")] 886 /// ``` 887 #[stable(feature = "wrapping", since = "1.7.0")] 888 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")] 889 #[must_use = "this returns the result of the operation, \ 890 without modifying the original"] 891 #[inline] 892 pub const fn checked_neg(self) -> Option<Self> { 893 let (a, b) = self.overflowing_neg(); 894 if unlikely!(b) {None} else {Some(a)} 895 } 896 897 /// Checked shift left. Computes `self << rhs`, returning `None` 898 /// if `rhs` is larger than or equal to the number of bits in `self`. 899 /// 900 /// # Examples 901 /// 902 /// Basic usage: 903 /// 904 /// ``` 905 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));")] 906 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);")] 907 /// ``` 908 #[stable(feature = "wrapping", since = "1.7.0")] 909 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")] 910 #[must_use = "this returns the result of the operation, \ 911 without modifying the original"] 912 #[inline] 913 pub const fn checked_shl(self, rhs: u32) -> Option<Self> { 914 let (a, b) = self.overflowing_shl(rhs); 915 if unlikely!(b) {None} else {Some(a)} 916 } 917 918 /// Unchecked shift left. Computes `self << rhs`, assuming that 919 /// `rhs` is less than the number of bits in `self`. 920 /// 921 /// # Safety 922 /// 923 /// This results in undefined behavior if `rhs` is larger than 924 /// or equal to the number of bits in `self`, 925 /// i.e. when [`checked_shl`] would return `None`. 926 /// 927 #[doc = concat!("[`checked_shl`]: ", stringify!($SelfT), "::checked_shl")] 928 #[unstable( 929 feature = "unchecked_math", 930 reason = "niche optimization path", 931 issue = "85122", 932 )] 933 #[must_use = "this returns the result of the operation, \ 934 without modifying the original"] 935 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")] 936 #[inline(always)] 937 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces 938 pub const unsafe fn unchecked_shl(self, rhs: u32) -> Self { 939 // SAFETY: the caller must uphold the safety contract for 940 // `unchecked_shl`. 941 // Any legal shift amount is losslessly representable in the self type. 942 unsafe { intrinsics::unchecked_shl(self, conv_rhs_for_unchecked_shift!($SelfT, rhs)) } 943 } 944 945 /// Checked shift right. Computes `self >> rhs`, returning `None` 946 /// if `rhs` is larger than or equal to the number of bits in `self`. 947 /// 948 /// # Examples 949 /// 950 /// Basic usage: 951 /// 952 /// ``` 953 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));")] 954 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);")] 955 /// ``` 956 #[stable(feature = "wrapping", since = "1.7.0")] 957 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")] 958 #[must_use = "this returns the result of the operation, \ 959 without modifying the original"] 960 #[inline] 961 pub const fn checked_shr(self, rhs: u32) -> Option<Self> { 962 let (a, b) = self.overflowing_shr(rhs); 963 if unlikely!(b) {None} else {Some(a)} 964 } 965 966 /// Unchecked shift right. Computes `self >> rhs`, assuming that 967 /// `rhs` is less than the number of bits in `self`. 968 /// 969 /// # Safety 970 /// 971 /// This results in undefined behavior if `rhs` is larger than 972 /// or equal to the number of bits in `self`, 973 /// i.e. when [`checked_shr`] would return `None`. 974 /// 975 #[doc = concat!("[`checked_shr`]: ", stringify!($SelfT), "::checked_shr")] 976 #[unstable( 977 feature = "unchecked_math", 978 reason = "niche optimization path", 979 issue = "85122", 980 )] 981 #[must_use = "this returns the result of the operation, \ 982 without modifying the original"] 983 #[rustc_const_unstable(feature = "const_inherent_unchecked_arith", issue = "85122")] 984 #[inline(always)] 985 #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces 986 pub const unsafe fn unchecked_shr(self, rhs: u32) -> Self { 987 // SAFETY: the caller must uphold the safety contract for 988 // `unchecked_shr`. 989 // Any legal shift amount is losslessly representable in the self type. 990 unsafe { intrinsics::unchecked_shr(self, conv_rhs_for_unchecked_shift!($SelfT, rhs)) } 991 } 992 993 /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if 994 /// overflow occurred. 995 /// 996 /// # Examples 997 /// 998 /// Basic usage: 999 /// 1000 /// ``` 1001 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));")] 1002 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);")] 1003 /// ``` 1004 #[stable(feature = "no_panic_pow", since = "1.34.0")] 1005 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")] 1006 #[must_use = "this returns the result of the operation, \ 1007 without modifying the original"] 1008 #[inline] 1009 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> { 1010 if exp == 0 { 1011 return Some(1); 1012 } 1013 let mut base = self; 1014 let mut acc: Self = 1; 1015 1016 while exp > 1 { 1017 if (exp & 1) == 1 { 1018 acc = try_opt!(acc.checked_mul(base)); 1019 } 1020 exp /= 2; 1021 base = try_opt!(base.checked_mul(base)); 1022 } 1023 1024 // since exp!=0, finally the exp must be 1. 1025 // Deal with the final bit of the exponent separately, since 1026 // squaring the base afterwards is not necessary and may cause a 1027 // needless overflow. 1028 1029 acc.checked_mul(base) 1030 } 1031 1032 /// Saturating integer addition. Computes `self + rhs`, saturating at 1033 /// the numeric bounds instead of overflowing. 1034 /// 1035 /// # Examples 1036 /// 1037 /// Basic usage: 1038 /// 1039 /// ``` 1040 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);")] 1041 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(127), ", stringify!($SelfT), "::MAX);")] 1042 /// ``` 1043 #[stable(feature = "rust1", since = "1.0.0")] 1044 #[must_use = "this returns the result of the operation, \ 1045 without modifying the original"] 1046 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")] 1047 #[inline(always)] 1048 pub const fn saturating_add(self, rhs: Self) -> Self { 1049 intrinsics::saturating_add(self, rhs) 1050 } 1051 1052 /// Saturating addition with a signed integer. Computes `self + rhs`, 1053 /// saturating at the numeric bounds instead of overflowing. 1054 /// 1055 /// # Examples 1056 /// 1057 /// Basic usage: 1058 /// 1059 /// ``` 1060 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_signed(2), 3);")] 1061 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_signed(-2), 0);")] 1062 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).saturating_add_signed(4), ", stringify!($SelfT), "::MAX);")] 1063 /// ``` 1064 #[stable(feature = "mixed_integer_ops", since = "1.66.0")] 1065 #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")] 1066 #[must_use = "this returns the result of the operation, \ 1067 without modifying the original"] 1068 #[inline] 1069 pub const fn saturating_add_signed(self, rhs: $SignedT) -> Self { 1070 let (res, overflow) = self.overflowing_add(rhs as Self); 1071 if overflow == (rhs < 0) { 1072 res 1073 } else if overflow { 1074 Self::MAX 1075 } else { 1076 0 1077 } 1078 } 1079 1080 /// Saturating integer subtraction. Computes `self - rhs`, saturating 1081 /// at the numeric bounds instead of overflowing. 1082 /// 1083 /// # Examples 1084 /// 1085 /// Basic usage: 1086 /// 1087 /// ``` 1088 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);")] 1089 #[doc = concat!("assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);")] 1090 /// ``` 1091 #[stable(feature = "rust1", since = "1.0.0")] 1092 #[must_use = "this returns the result of the operation, \ 1093 without modifying the original"] 1094 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")] 1095 #[inline(always)] 1096 pub const fn saturating_sub(self, rhs: Self) -> Self { 1097 intrinsics::saturating_sub(self, rhs) 1098 } 1099 1100 /// Saturating integer multiplication. Computes `self * rhs`, 1101 /// saturating at the numeric bounds instead of overflowing. 1102 /// 1103 /// # Examples 1104 /// 1105 /// Basic usage: 1106 /// 1107 /// ``` 1108 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);")] 1109 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),"::MAX);")] 1110 /// ``` 1111 #[stable(feature = "wrapping", since = "1.7.0")] 1112 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")] 1113 #[must_use = "this returns the result of the operation, \ 1114 without modifying the original"] 1115 #[inline] 1116 pub const fn saturating_mul(self, rhs: Self) -> Self { 1117 match self.checked_mul(rhs) { 1118 Some(x) => x, 1119 None => Self::MAX, 1120 } 1121 } 1122 1123 /// Saturating integer division. Computes `self / rhs`, saturating at the 1124 /// numeric bounds instead of overflowing. 1125 /// 1126 /// # Examples 1127 /// 1128 /// Basic usage: 1129 /// 1130 /// ``` 1131 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".saturating_div(2), 2);")] 1132 /// 1133 /// ``` 1134 /// 1135 /// ```should_panic 1136 #[doc = concat!("let _ = 1", stringify!($SelfT), ".saturating_div(0);")] 1137 /// 1138 /// ``` 1139 #[stable(feature = "saturating_div", since = "1.58.0")] 1140 #[rustc_const_stable(feature = "saturating_div", since = "1.58.0")] 1141 #[must_use = "this returns the result of the operation, \ 1142 without modifying the original"] 1143 #[inline] 1144 pub const fn saturating_div(self, rhs: Self) -> Self { 1145 // on unsigned types, there is no overflow in integer division 1146 self.wrapping_div(rhs) 1147 } 1148 1149 /// Saturating integer exponentiation. Computes `self.pow(exp)`, 1150 /// saturating at the numeric bounds instead of overflowing. 1151 /// 1152 /// # Examples 1153 /// 1154 /// Basic usage: 1155 /// 1156 /// ``` 1157 #[doc = concat!("assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);")] 1158 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);")] 1159 /// ``` 1160 #[stable(feature = "no_panic_pow", since = "1.34.0")] 1161 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")] 1162 #[must_use = "this returns the result of the operation, \ 1163 without modifying the original"] 1164 #[inline] 1165 pub const fn saturating_pow(self, exp: u32) -> Self { 1166 match self.checked_pow(exp) { 1167 Some(x) => x, 1168 None => Self::MAX, 1169 } 1170 } 1171 1172 /// Wrapping (modular) addition. Computes `self + rhs`, 1173 /// wrapping around at the boundary of the type. 1174 /// 1175 /// # Examples 1176 /// 1177 /// Basic usage: 1178 /// 1179 /// ``` 1180 #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);")] 1181 #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);")] 1182 /// ``` 1183 #[stable(feature = "rust1", since = "1.0.0")] 1184 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] 1185 #[must_use = "this returns the result of the operation, \ 1186 without modifying the original"] 1187 #[inline(always)] 1188 pub const fn wrapping_add(self, rhs: Self) -> Self { 1189 intrinsics::wrapping_add(self, rhs) 1190 } 1191 1192 /// Wrapping (modular) addition with a signed integer. Computes 1193 /// `self + rhs`, wrapping around at the boundary of the type. 1194 /// 1195 /// # Examples 1196 /// 1197 /// Basic usage: 1198 /// 1199 /// ``` 1200 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(2), 3);")] 1201 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(-2), ", stringify!($SelfT), "::MAX);")] 1202 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).wrapping_add_signed(4), 1);")] 1203 /// ``` 1204 #[stable(feature = "mixed_integer_ops", since = "1.66.0")] 1205 #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")] 1206 #[must_use = "this returns the result of the operation, \ 1207 without modifying the original"] 1208 #[inline] 1209 pub const fn wrapping_add_signed(self, rhs: $SignedT) -> Self { 1210 self.wrapping_add(rhs as Self) 1211 } 1212 1213 /// Wrapping (modular) subtraction. Computes `self - rhs`, 1214 /// wrapping around at the boundary of the type. 1215 /// 1216 /// # Examples 1217 /// 1218 /// Basic usage: 1219 /// 1220 /// ``` 1221 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);")] 1222 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);")] 1223 /// ``` 1224 #[stable(feature = "rust1", since = "1.0.0")] 1225 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] 1226 #[must_use = "this returns the result of the operation, \ 1227 without modifying the original"] 1228 #[inline(always)] 1229 pub const fn wrapping_sub(self, rhs: Self) -> Self { 1230 intrinsics::wrapping_sub(self, rhs) 1231 } 1232 1233 /// Wrapping (modular) multiplication. Computes `self * 1234 /// rhs`, wrapping around at the boundary of the type. 1235 /// 1236 /// # Examples 1237 /// 1238 /// Basic usage: 1239 /// 1240 /// Please note that this example is shared between integer types. 1241 /// Which explains why `u8` is used here. 1242 /// 1243 /// ``` 1244 /// assert_eq!(10u8.wrapping_mul(12), 120); 1245 /// assert_eq!(25u8.wrapping_mul(12), 44); 1246 /// ``` 1247 #[stable(feature = "rust1", since = "1.0.0")] 1248 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] 1249 #[must_use = "this returns the result of the operation, \ 1250 without modifying the original"] 1251 #[inline(always)] 1252 pub const fn wrapping_mul(self, rhs: Self) -> Self { 1253 intrinsics::wrapping_mul(self, rhs) 1254 } 1255 1256 /// Wrapping (modular) division. Computes `self / rhs`. 1257 /// Wrapped division on unsigned types is just normal division. 1258 /// There's no way wrapping could ever happen. 1259 /// This function exists, so that all operations 1260 /// are accounted for in the wrapping operations. 1261 /// 1262 /// # Examples 1263 /// 1264 /// Basic usage: 1265 /// 1266 /// ``` 1267 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);")] 1268 /// ``` 1269 #[stable(feature = "num_wrapping", since = "1.2.0")] 1270 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")] 1271 #[must_use = "this returns the result of the operation, \ 1272 without modifying the original"] 1273 #[inline(always)] 1274 pub const fn wrapping_div(self, rhs: Self) -> Self { 1275 self / rhs 1276 } 1277 1278 /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`. 1279 /// Wrapped division on unsigned types is just normal division. 1280 /// There's no way wrapping could ever happen. 1281 /// This function exists, so that all operations 1282 /// are accounted for in the wrapping operations. 1283 /// Since, for the positive integers, all common 1284 /// definitions of division are equal, this 1285 /// is exactly equal to `self.wrapping_div(rhs)`. 1286 /// 1287 /// # Examples 1288 /// 1289 /// Basic usage: 1290 /// 1291 /// ``` 1292 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);")] 1293 /// ``` 1294 #[stable(feature = "euclidean_division", since = "1.38.0")] 1295 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")] 1296 #[must_use = "this returns the result of the operation, \ 1297 without modifying the original"] 1298 #[inline(always)] 1299 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self { 1300 self / rhs 1301 } 1302 1303 /// Wrapping (modular) remainder. Computes `self % rhs`. 1304 /// Wrapped remainder calculation on unsigned types is 1305 /// just the regular remainder calculation. 1306 /// There's no way wrapping could ever happen. 1307 /// This function exists, so that all operations 1308 /// are accounted for in the wrapping operations. 1309 /// 1310 /// # Examples 1311 /// 1312 /// Basic usage: 1313 /// 1314 /// ``` 1315 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);")] 1316 /// ``` 1317 #[stable(feature = "num_wrapping", since = "1.2.0")] 1318 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")] 1319 #[must_use = "this returns the result of the operation, \ 1320 without modifying the original"] 1321 #[inline(always)] 1322 pub const fn wrapping_rem(self, rhs: Self) -> Self { 1323 self % rhs 1324 } 1325 1326 /// Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`. 1327 /// Wrapped modulo calculation on unsigned types is 1328 /// just the regular remainder calculation. 1329 /// There's no way wrapping could ever happen. 1330 /// This function exists, so that all operations 1331 /// are accounted for in the wrapping operations. 1332 /// Since, for the positive integers, all common 1333 /// definitions of division are equal, this 1334 /// is exactly equal to `self.wrapping_rem(rhs)`. 1335 /// 1336 /// # Examples 1337 /// 1338 /// Basic usage: 1339 /// 1340 /// ``` 1341 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);")] 1342 /// ``` 1343 #[stable(feature = "euclidean_division", since = "1.38.0")] 1344 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")] 1345 #[must_use = "this returns the result of the operation, \ 1346 without modifying the original"] 1347 #[inline(always)] 1348 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self { 1349 self % rhs 1350 } 1351 1352 /// Wrapping (modular) negation. Computes `-self`, 1353 /// wrapping around at the boundary of the type. 1354 /// 1355 /// Since unsigned types do not have negative equivalents 1356 /// all applications of this function will wrap (except for `-0`). 1357 /// For values smaller than the corresponding signed type's maximum 1358 /// the result is the same as casting the corresponding signed value. 1359 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where 1360 /// `MAX` is the corresponding signed type's maximum. 1361 /// 1362 /// # Examples 1363 /// 1364 /// Basic usage: 1365 /// 1366 /// ``` 1367 #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".wrapping_neg(), 0);")] 1368 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_neg(), 1);")] 1369 #[doc = concat!("assert_eq!(13_", stringify!($SelfT), ".wrapping_neg(), (!13) + 1);")] 1370 #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".wrapping_neg(), !(42 - 1));")] 1371 /// ``` 1372 #[stable(feature = "num_wrapping", since = "1.2.0")] 1373 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] 1374 #[must_use = "this returns the result of the operation, \ 1375 without modifying the original"] 1376 #[inline(always)] 1377 pub const fn wrapping_neg(self) -> Self { 1378 (0 as $SelfT).wrapping_sub(self) 1379 } 1380 1381 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`, 1382 /// where `mask` removes any high-order bits of `rhs` that 1383 /// would cause the shift to exceed the bitwidth of the type. 1384 /// 1385 /// Note that this is *not* the same as a rotate-left; the 1386 /// RHS of a wrapping shift-left is restricted to the range 1387 /// of the type, rather than the bits shifted out of the LHS 1388 /// being returned to the other end. The primitive integer 1389 /// types all implement a [`rotate_left`](Self::rotate_left) function, 1390 /// which may be what you want instead. 1391 /// 1392 /// # Examples 1393 /// 1394 /// Basic usage: 1395 /// 1396 /// ``` 1397 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_shl(7), 128);")] 1398 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_shl(128), 1);")] 1399 /// ``` 1400 #[stable(feature = "num_wrapping", since = "1.2.0")] 1401 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] 1402 #[must_use = "this returns the result of the operation, \ 1403 without modifying the original"] 1404 #[inline(always)] 1405 #[rustc_allow_const_fn_unstable(const_inherent_unchecked_arith)] 1406 pub const fn wrapping_shl(self, rhs: u32) -> Self { 1407 // SAFETY: the masking by the bitsize of the type ensures that we do not shift 1408 // out of bounds 1409 unsafe { 1410 self.unchecked_shl(rhs & (Self::BITS - 1)) 1411 } 1412 } 1413 1414 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, 1415 /// where `mask` removes any high-order bits of `rhs` that 1416 /// would cause the shift to exceed the bitwidth of the type. 1417 /// 1418 /// Note that this is *not* the same as a rotate-right; the 1419 /// RHS of a wrapping shift-right is restricted to the range 1420 /// of the type, rather than the bits shifted out of the LHS 1421 /// being returned to the other end. The primitive integer 1422 /// types all implement a [`rotate_right`](Self::rotate_right) function, 1423 /// which may be what you want instead. 1424 /// 1425 /// # Examples 1426 /// 1427 /// Basic usage: 1428 /// 1429 /// ``` 1430 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".wrapping_shr(7), 1);")] 1431 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".wrapping_shr(128), 128);")] 1432 /// ``` 1433 #[stable(feature = "num_wrapping", since = "1.2.0")] 1434 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] 1435 #[must_use = "this returns the result of the operation, \ 1436 without modifying the original"] 1437 #[inline(always)] 1438 #[rustc_allow_const_fn_unstable(const_inherent_unchecked_arith)] 1439 pub const fn wrapping_shr(self, rhs: u32) -> Self { 1440 // SAFETY: the masking by the bitsize of the type ensures that we do not shift 1441 // out of bounds 1442 unsafe { 1443 self.unchecked_shr(rhs & (Self::BITS - 1)) 1444 } 1445 } 1446 1447 /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`, 1448 /// wrapping around at the boundary of the type. 1449 /// 1450 /// # Examples 1451 /// 1452 /// Basic usage: 1453 /// 1454 /// ``` 1455 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);")] 1456 /// assert_eq!(3u8.wrapping_pow(6), 217); 1457 /// ``` 1458 #[stable(feature = "no_panic_pow", since = "1.34.0")] 1459 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")] 1460 #[must_use = "this returns the result of the operation, \ 1461 without modifying the original"] 1462 #[inline] 1463 pub const fn wrapping_pow(self, mut exp: u32) -> Self { 1464 if exp == 0 { 1465 return 1; 1466 } 1467 let mut base = self; 1468 let mut acc: Self = 1; 1469 1470 while exp > 1 { 1471 if (exp & 1) == 1 { 1472 acc = acc.wrapping_mul(base); 1473 } 1474 exp /= 2; 1475 base = base.wrapping_mul(base); 1476 } 1477 1478 // since exp!=0, finally the exp must be 1. 1479 // Deal with the final bit of the exponent separately, since 1480 // squaring the base afterwards is not necessary and may cause a 1481 // needless overflow. 1482 acc.wrapping_mul(base) 1483 } 1484 1485 /// Calculates `self` + `rhs` 1486 /// 1487 /// Returns a tuple of the addition along with a boolean indicating 1488 /// whether an arithmetic overflow would occur. If an overflow would 1489 /// have occurred then the wrapped value is returned. 1490 /// 1491 /// # Examples 1492 /// 1493 /// Basic usage 1494 /// 1495 /// ``` 1496 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")] 1497 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));")] 1498 /// ``` 1499 #[stable(feature = "wrapping", since = "1.7.0")] 1500 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] 1501 #[must_use = "this returns the result of the operation, \ 1502 without modifying the original"] 1503 #[inline(always)] 1504 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) { 1505 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT); 1506 (a as Self, b) 1507 } 1508 1509 /// Calculates `self` + `rhs` + `carry` and returns a tuple containing 1510 /// the sum and the output carry. 1511 /// 1512 /// Performs "ternary addition" of two integer operands and a carry-in 1513 /// bit, and returns an output integer and a carry-out bit. This allows 1514 /// chaining together multiple additions to create a wider addition, and 1515 /// can be useful for bignum addition. 1516 /// 1517 #[doc = concat!("This can be thought of as a ", stringify!($BITS), "-bit \"full adder\", in the electronics sense.")] 1518 /// 1519 /// If the input carry is false, this method is equivalent to 1520 /// [`overflowing_add`](Self::overflowing_add), and the output carry is 1521 /// equal to the overflow flag. Note that although carry and overflow 1522 /// flags are similar for unsigned integers, they are different for 1523 /// signed integers. 1524 /// 1525 /// # Examples 1526 /// 1527 /// ``` 1528 /// #![feature(bigint_helper_methods)] 1529 /// 1530 #[doc = concat!("// 3 MAX (a = 3 × 2^", stringify!($BITS), " + 2^", stringify!($BITS), " - 1)")] 1531 #[doc = concat!("// + 5 7 (b = 5 × 2^", stringify!($BITS), " + 7)")] 1532 /// // --------- 1533 #[doc = concat!("// 9 6 (sum = 9 × 2^", stringify!($BITS), " + 6)")] 1534 /// 1535 #[doc = concat!("let (a1, a0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (3, ", stringify!($SelfT), "::MAX);")] 1536 #[doc = concat!("let (b1, b0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (5, 7);")] 1537 /// let carry0 = false; 1538 /// 1539 /// let (sum0, carry1) = a0.carrying_add(b0, carry0); 1540 /// assert_eq!(carry1, true); 1541 /// let (sum1, carry2) = a1.carrying_add(b1, carry1); 1542 /// assert_eq!(carry2, false); 1543 /// 1544 /// assert_eq!((sum1, sum0), (9, 6)); 1545 /// ``` 1546 #[unstable(feature = "bigint_helper_methods", issue = "85532")] 1547 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")] 1548 #[must_use = "this returns the result of the operation, \ 1549 without modifying the original"] 1550 #[inline] 1551 pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) { 1552 // note: longer-term this should be done via an intrinsic, but this has been shown 1553 // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic 1554 let (a, b) = self.overflowing_add(rhs); 1555 let (c, d) = a.overflowing_add(carry as $SelfT); 1556 (c, b || d) 1557 } 1558 1559 /// Calculates `self` + `rhs` with a signed `rhs` 1560 /// 1561 /// Returns a tuple of the addition along with a boolean indicating 1562 /// whether an arithmetic overflow would occur. If an overflow would 1563 /// have occurred then the wrapped value is returned. 1564 /// 1565 /// # Examples 1566 /// 1567 /// Basic usage: 1568 /// 1569 /// ``` 1570 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(2), (3, false));")] 1571 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(-2), (", stringify!($SelfT), "::MAX, true));")] 1572 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_add_signed(4), (1, true));")] 1573 /// ``` 1574 #[stable(feature = "mixed_integer_ops", since = "1.66.0")] 1575 #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")] 1576 #[must_use = "this returns the result of the operation, \ 1577 without modifying the original"] 1578 #[inline] 1579 pub const fn overflowing_add_signed(self, rhs: $SignedT) -> (Self, bool) { 1580 let (res, overflowed) = self.overflowing_add(rhs as Self); 1581 (res, overflowed ^ (rhs < 0)) 1582 } 1583 1584 /// Calculates `self` - `rhs` 1585 /// 1586 /// Returns a tuple of the subtraction along with a boolean indicating 1587 /// whether an arithmetic overflow would occur. If an overflow would 1588 /// have occurred then the wrapped value is returned. 1589 /// 1590 /// # Examples 1591 /// 1592 /// Basic usage 1593 /// 1594 /// ``` 1595 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")] 1596 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")] 1597 /// ``` 1598 #[stable(feature = "wrapping", since = "1.7.0")] 1599 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] 1600 #[must_use = "this returns the result of the operation, \ 1601 without modifying the original"] 1602 #[inline(always)] 1603 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) { 1604 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT); 1605 (a as Self, b) 1606 } 1607 1608 /// Calculates `self` − `rhs` − `borrow` and returns a tuple 1609 /// containing the difference and the output borrow. 1610 /// 1611 /// Performs "ternary subtraction" by subtracting both an integer 1612 /// operand and a borrow-in bit from `self`, and returns an output 1613 /// integer and a borrow-out bit. This allows chaining together multiple 1614 /// subtractions to create a wider subtraction, and can be useful for 1615 /// bignum subtraction. 1616 /// 1617 /// # Examples 1618 /// 1619 /// ``` 1620 /// #![feature(bigint_helper_methods)] 1621 /// 1622 #[doc = concat!("// 9 6 (a = 9 × 2^", stringify!($BITS), " + 6)")] 1623 #[doc = concat!("// - 5 7 (b = 5 × 2^", stringify!($BITS), " + 7)")] 1624 /// // --------- 1625 #[doc = concat!("// 3 MAX (diff = 3 × 2^", stringify!($BITS), " + 2^", stringify!($BITS), " - 1)")] 1626 /// 1627 #[doc = concat!("let (a1, a0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (9, 6);")] 1628 #[doc = concat!("let (b1, b0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (5, 7);")] 1629 /// let borrow0 = false; 1630 /// 1631 /// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0); 1632 /// assert_eq!(borrow1, true); 1633 /// let (diff1, borrow2) = a1.borrowing_sub(b1, borrow1); 1634 /// assert_eq!(borrow2, false); 1635 /// 1636 #[doc = concat!("assert_eq!((diff1, diff0), (3, ", stringify!($SelfT), "::MAX));")] 1637 /// ``` 1638 #[unstable(feature = "bigint_helper_methods", issue = "85532")] 1639 #[rustc_const_unstable(feature = "const_bigint_helper_methods", issue = "85532")] 1640 #[must_use = "this returns the result of the operation, \ 1641 without modifying the original"] 1642 #[inline] 1643 pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) { 1644 // note: longer-term this should be done via an intrinsic, but this has been shown 1645 // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic 1646 let (a, b) = self.overflowing_sub(rhs); 1647 let (c, d) = a.overflowing_sub(borrow as $SelfT); 1648 (c, b || d) 1649 } 1650 1651 /// Computes the absolute difference between `self` and `other`. 1652 /// 1653 /// # Examples 1654 /// 1655 /// Basic usage: 1656 /// 1657 /// ``` 1658 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(80), 20", stringify!($SelfT), ");")] 1659 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(110), 10", stringify!($SelfT), ");")] 1660 /// ``` 1661 #[stable(feature = "int_abs_diff", since = "1.60.0")] 1662 #[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")] 1663 #[must_use = "this returns the result of the operation, \ 1664 without modifying the original"] 1665 #[inline] 1666 pub const fn abs_diff(self, other: Self) -> Self { 1667 if mem::size_of::<Self>() == 1 { 1668 // Trick LLVM into generating the psadbw instruction when SSE2 1669 // is available and this function is autovectorized for u8's. 1670 (self as i32).wrapping_sub(other as i32).abs() as Self 1671 } else { 1672 if self < other { 1673 other - self 1674 } else { 1675 self - other 1676 } 1677 } 1678 } 1679 1680 /// Calculates the multiplication of `self` and `rhs`. 1681 /// 1682 /// Returns a tuple of the multiplication along with a boolean 1683 /// indicating whether an arithmetic overflow would occur. If an 1684 /// overflow would have occurred then the wrapped value is returned. 1685 /// 1686 /// # Examples 1687 /// 1688 /// Basic usage: 1689 /// 1690 /// Please note that this example is shared between integer types. 1691 /// Which explains why `u32` is used here. 1692 /// 1693 /// ``` 1694 /// assert_eq!(5u32.overflowing_mul(2), (10, false)); 1695 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true)); 1696 /// ``` 1697 #[stable(feature = "wrapping", since = "1.7.0")] 1698 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] 1699 #[must_use = "this returns the result of the operation, \ 1700 without modifying the original"] 1701 #[inline(always)] 1702 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) { 1703 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT); 1704 (a as Self, b) 1705 } 1706 1707 /// Calculates the divisor when `self` is divided by `rhs`. 1708 /// 1709 /// Returns a tuple of the divisor along with a boolean indicating 1710 /// whether an arithmetic overflow would occur. Note that for unsigned 1711 /// integers overflow never occurs, so the second value is always 1712 /// `false`. 1713 /// 1714 /// # Panics 1715 /// 1716 /// This function will panic if `rhs` is 0. 1717 /// 1718 /// # Examples 1719 /// 1720 /// Basic usage 1721 /// 1722 /// ``` 1723 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));")] 1724 /// ``` 1725 #[inline(always)] 1726 #[stable(feature = "wrapping", since = "1.7.0")] 1727 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")] 1728 #[must_use = "this returns the result of the operation, \ 1729 without modifying the original"] 1730 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) { 1731 (self / rhs, false) 1732 } 1733 1734 /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`. 1735 /// 1736 /// Returns a tuple of the divisor along with a boolean indicating 1737 /// whether an arithmetic overflow would occur. Note that for unsigned 1738 /// integers overflow never occurs, so the second value is always 1739 /// `false`. 1740 /// Since, for the positive integers, all common 1741 /// definitions of division are equal, this 1742 /// is exactly equal to `self.overflowing_div(rhs)`. 1743 /// 1744 /// # Panics 1745 /// 1746 /// This function will panic if `rhs` is 0. 1747 /// 1748 /// # Examples 1749 /// 1750 /// Basic usage 1751 /// 1752 /// ``` 1753 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));")] 1754 /// ``` 1755 #[inline(always)] 1756 #[stable(feature = "euclidean_division", since = "1.38.0")] 1757 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")] 1758 #[must_use = "this returns the result of the operation, \ 1759 without modifying the original"] 1760 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) { 1761 (self / rhs, false) 1762 } 1763 1764 /// Calculates the remainder when `self` is divided by `rhs`. 1765 /// 1766 /// Returns a tuple of the remainder after dividing along with a boolean 1767 /// indicating whether an arithmetic overflow would occur. Note that for 1768 /// unsigned integers overflow never occurs, so the second value is 1769 /// always `false`. 1770 /// 1771 /// # Panics 1772 /// 1773 /// This function will panic if `rhs` is 0. 1774 /// 1775 /// # Examples 1776 /// 1777 /// Basic usage 1778 /// 1779 /// ``` 1780 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));")] 1781 /// ``` 1782 #[inline(always)] 1783 #[stable(feature = "wrapping", since = "1.7.0")] 1784 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")] 1785 #[must_use = "this returns the result of the operation, \ 1786 without modifying the original"] 1787 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) { 1788 (self % rhs, false) 1789 } 1790 1791 /// Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division. 1792 /// 1793 /// Returns a tuple of the modulo after dividing along with a boolean 1794 /// indicating whether an arithmetic overflow would occur. Note that for 1795 /// unsigned integers overflow never occurs, so the second value is 1796 /// always `false`. 1797 /// Since, for the positive integers, all common 1798 /// definitions of division are equal, this operation 1799 /// is exactly equal to `self.overflowing_rem(rhs)`. 1800 /// 1801 /// # Panics 1802 /// 1803 /// This function will panic if `rhs` is 0. 1804 /// 1805 /// # Examples 1806 /// 1807 /// Basic usage 1808 /// 1809 /// ``` 1810 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));")] 1811 /// ``` 1812 #[inline(always)] 1813 #[stable(feature = "euclidean_division", since = "1.38.0")] 1814 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")] 1815 #[must_use = "this returns the result of the operation, \ 1816 without modifying the original"] 1817 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) { 1818 (self % rhs, false) 1819 } 1820 1821 /// Negates self in an overflowing fashion. 1822 /// 1823 /// Returns `!self + 1` using wrapping operations to return the value 1824 /// that represents the negation of this unsigned value. Note that for 1825 /// positive unsigned values overflow always occurs, but negating 0 does 1826 /// not overflow. 1827 /// 1828 /// # Examples 1829 /// 1830 /// Basic usage 1831 /// 1832 /// ``` 1833 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));")] 1834 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT), ", true));")] 1835 /// ``` 1836 #[inline(always)] 1837 #[stable(feature = "wrapping", since = "1.7.0")] 1838 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] 1839 #[must_use = "this returns the result of the operation, \ 1840 without modifying the original"] 1841 pub const fn overflowing_neg(self) -> (Self, bool) { 1842 ((!self).wrapping_add(1), self != 0) 1843 } 1844 1845 /// Shifts self left by `rhs` bits. 1846 /// 1847 /// Returns a tuple of the shifted version of self along with a boolean 1848 /// indicating whether the shift value was larger than or equal to the 1849 /// number of bits. If the shift value is too large, then value is 1850 /// masked (N-1) where N is the number of bits, and this value is then 1851 /// used to perform the shift. 1852 /// 1853 /// # Examples 1854 /// 1855 /// Basic usage 1856 /// 1857 /// ``` 1858 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));")] 1859 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));")] 1860 /// ``` 1861 #[stable(feature = "wrapping", since = "1.7.0")] 1862 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] 1863 #[must_use = "this returns the result of the operation, \ 1864 without modifying the original"] 1865 #[inline(always)] 1866 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) { 1867 (self.wrapping_shl(rhs), rhs >= Self::BITS) 1868 } 1869 1870 /// Shifts self right by `rhs` bits. 1871 /// 1872 /// Returns a tuple of the shifted version of self along with a boolean 1873 /// indicating whether the shift value was larger than or equal to the 1874 /// number of bits. If the shift value is too large, then value is 1875 /// masked (N-1) where N is the number of bits, and this value is then 1876 /// used to perform the shift. 1877 /// 1878 /// # Examples 1879 /// 1880 /// Basic usage 1881 /// 1882 /// ``` 1883 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));")] 1884 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));")] 1885 /// ``` 1886 #[stable(feature = "wrapping", since = "1.7.0")] 1887 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")] 1888 #[must_use = "this returns the result of the operation, \ 1889 without modifying the original"] 1890 #[inline(always)] 1891 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) { 1892 (self.wrapping_shr(rhs), rhs >= Self::BITS) 1893 } 1894 1895 /// Raises self to the power of `exp`, using exponentiation by squaring. 1896 /// 1897 /// Returns a tuple of the exponentiation along with a bool indicating 1898 /// whether an overflow happened. 1899 /// 1900 /// # Examples 1901 /// 1902 /// Basic usage: 1903 /// 1904 /// ``` 1905 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));")] 1906 /// assert_eq!(3u8.overflowing_pow(6), (217, true)); 1907 /// ``` 1908 #[stable(feature = "no_panic_pow", since = "1.34.0")] 1909 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")] 1910 #[must_use = "this returns the result of the operation, \ 1911 without modifying the original"] 1912 #[inline] 1913 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) { 1914 if exp == 0{ 1915 return (1,false); 1916 } 1917 let mut base = self; 1918 let mut acc: Self = 1; 1919 let mut overflown = false; 1920 // Scratch space for storing results of overflowing_mul. 1921 let mut r; 1922 1923 while exp > 1 { 1924 if (exp & 1) == 1 { 1925 r = acc.overflowing_mul(base); 1926 acc = r.0; 1927 overflown |= r.1; 1928 } 1929 exp /= 2; 1930 r = base.overflowing_mul(base); 1931 base = r.0; 1932 overflown |= r.1; 1933 } 1934 1935 // since exp!=0, finally the exp must be 1. 1936 // Deal with the final bit of the exponent separately, since 1937 // squaring the base afterwards is not necessary and may cause a 1938 // needless overflow. 1939 r = acc.overflowing_mul(base); 1940 r.1 |= overflown; 1941 1942 r 1943 } 1944 1945 /// Raises self to the power of `exp`, using exponentiation by squaring. 1946 /// 1947 /// # Examples 1948 /// 1949 /// Basic usage: 1950 /// 1951 /// ``` 1952 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".pow(5), 32);")] 1953 /// ``` 1954 #[stable(feature = "rust1", since = "1.0.0")] 1955 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")] 1956 #[must_use = "this returns the result of the operation, \ 1957 without modifying the original"] 1958 #[inline] 1959 #[rustc_inherit_overflow_checks] 1960 pub const fn pow(self, mut exp: u32) -> Self { 1961 if exp == 0 { 1962 return 1; 1963 } 1964 let mut base = self; 1965 let mut acc = 1; 1966 1967 while exp > 1 { 1968 if (exp & 1) == 1 { 1969 acc = acc * base; 1970 } 1971 exp /= 2; 1972 base = base * base; 1973 } 1974 1975 // since exp!=0, finally the exp must be 1. 1976 // Deal with the final bit of the exponent separately, since 1977 // squaring the base afterwards is not necessary and may cause a 1978 // needless overflow. 1979 acc * base 1980 } 1981 1982 /// Performs Euclidean division. 1983 /// 1984 /// Since, for the positive integers, all common 1985 /// definitions of division are equal, this 1986 /// is exactly equal to `self / rhs`. 1987 /// 1988 /// # Panics 1989 /// 1990 /// This function will panic if `rhs` is 0. 1991 /// 1992 /// # Examples 1993 /// 1994 /// Basic usage: 1995 /// 1996 /// ``` 1997 #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type")] 1998 /// ``` 1999 #[stable(feature = "euclidean_division", since = "1.38.0")] 2000 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")] 2001 #[must_use = "this returns the result of the operation, \ 2002 without modifying the original"] 2003 #[inline(always)] 2004 #[rustc_inherit_overflow_checks] 2005 pub const fn div_euclid(self, rhs: Self) -> Self { 2006 self / rhs 2007 } 2008 2009 2010 /// Calculates the least remainder of `self (mod rhs)`. 2011 /// 2012 /// Since, for the positive integers, all common 2013 /// definitions of division are equal, this 2014 /// is exactly equal to `self % rhs`. 2015 /// 2016 /// # Panics 2017 /// 2018 /// This function will panic if `rhs` is 0. 2019 /// 2020 /// # Examples 2021 /// 2022 /// Basic usage: 2023 /// 2024 /// ``` 2025 #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type")] 2026 /// ``` 2027 #[stable(feature = "euclidean_division", since = "1.38.0")] 2028 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")] 2029 #[must_use = "this returns the result of the operation, \ 2030 without modifying the original"] 2031 #[inline(always)] 2032 #[rustc_inherit_overflow_checks] 2033 pub const fn rem_euclid(self, rhs: Self) -> Self { 2034 self % rhs 2035 } 2036 2037 /// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity. 2038 /// 2039 /// This is the same as performing `self / rhs` for all unsigned integers. 2040 /// 2041 /// # Panics 2042 /// 2043 /// This function will panic if `rhs` is zero. 2044 /// 2045 /// # Examples 2046 /// 2047 /// Basic usage: 2048 /// 2049 /// ``` 2050 /// #![feature(int_roundings)] 2051 #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".div_floor(4), 1);")] 2052 /// ``` 2053 #[unstable(feature = "int_roundings", issue = "88581")] 2054 #[must_use = "this returns the result of the operation, \ 2055 without modifying the original"] 2056 #[inline(always)] 2057 pub const fn div_floor(self, rhs: Self) -> Self { 2058 self / rhs 2059 } 2060 2061 /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity. 2062 /// 2063 /// # Panics 2064 /// 2065 /// This function will panic if `rhs` is zero. 2066 /// 2067 /// ## Overflow behavior 2068 /// 2069 /// On overflow, this function will panic if overflow checks are enabled (default in debug 2070 /// mode) and wrap if overflow checks are disabled (default in release mode). 2071 /// 2072 /// # Examples 2073 /// 2074 /// Basic usage: 2075 /// 2076 /// ``` 2077 /// #![feature(int_roundings)] 2078 #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".div_ceil(4), 2);")] 2079 /// ``` 2080 #[unstable(feature = "int_roundings", issue = "88581")] 2081 #[must_use = "this returns the result of the operation, \ 2082 without modifying the original"] 2083 #[inline] 2084 #[rustc_inherit_overflow_checks] 2085 pub const fn div_ceil(self, rhs: Self) -> Self { 2086 let d = self / rhs; 2087 let r = self % rhs; 2088 if r > 0 && rhs > 0 { 2089 d + 1 2090 } else { 2091 d 2092 } 2093 } 2094 2095 /// Calculates the smallest value greater than or equal to `self` that 2096 /// is a multiple of `rhs`. 2097 /// 2098 /// # Panics 2099 /// 2100 /// This function will panic if `rhs` is zero. 2101 /// 2102 /// ## Overflow behavior 2103 /// 2104 /// On overflow, this function will panic if overflow checks are enabled (default in debug 2105 /// mode) and wrap if overflow checks are disabled (default in release mode). 2106 /// 2107 /// # Examples 2108 /// 2109 /// Basic usage: 2110 /// 2111 /// ``` 2112 /// #![feature(int_roundings)] 2113 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(8), 16);")] 2114 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(8), 24);")] 2115 /// ``` 2116 #[unstable(feature = "int_roundings", issue = "88581")] 2117 #[must_use = "this returns the result of the operation, \ 2118 without modifying the original"] 2119 #[inline] 2120 #[rustc_inherit_overflow_checks] 2121 pub const fn next_multiple_of(self, rhs: Self) -> Self { 2122 match self % rhs { 2123 0 => self, 2124 r => self + (rhs - r) 2125 } 2126 } 2127 2128 /// Calculates the smallest value greater than or equal to `self` that 2129 /// is a multiple of `rhs`. Returns `None` if `rhs` is zero or the 2130 /// operation would result in overflow. 2131 /// 2132 /// # Examples 2133 /// 2134 /// Basic usage: 2135 /// 2136 /// ``` 2137 /// #![feature(int_roundings)] 2138 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(16));")] 2139 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(24));")] 2140 #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".checked_next_multiple_of(0), None);")] 2141 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_multiple_of(2), None);")] 2142 /// ``` 2143 #[unstable(feature = "int_roundings", issue = "88581")] 2144 #[must_use = "this returns the result of the operation, \ 2145 without modifying the original"] 2146 #[inline] 2147 pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> { 2148 match try_opt!(self.checked_rem(rhs)) { 2149 0 => Some(self), 2150 // rhs - r cannot overflow because r is smaller than rhs 2151 r => self.checked_add(rhs - r) 2152 } 2153 } 2154 2155 /// Returns `true` if and only if `self == 2^k` for some `k`. 2156 /// 2157 /// # Examples 2158 /// 2159 /// Basic usage: 2160 /// 2161 /// ``` 2162 #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")] 2163 #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")] 2164 /// ``` 2165 #[must_use] 2166 #[stable(feature = "rust1", since = "1.0.0")] 2167 #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")] 2168 #[inline(always)] 2169 pub const fn is_power_of_two(self) -> bool { 2170 self.count_ones() == 1 2171 } 2172 2173 // Returns one less than next power of two. 2174 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8) 2175 // 2176 // 8u8.one_less_than_next_power_of_two() == 7 2177 // 6u8.one_less_than_next_power_of_two() == 7 2178 // 2179 // This method cannot overflow, as in the `next_power_of_two` 2180 // overflow cases it instead ends up returning the maximum value 2181 // of the type, and can return 0 for 0. 2182 #[inline] 2183 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")] 2184 const fn one_less_than_next_power_of_two(self) -> Self { 2185 if self <= 1 { return 0; } 2186 2187 let p = self - 1; 2188 // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros. 2189 // That means the shift is always in-bounds, and some processors 2190 // (such as intel pre-haswell) have more efficient ctlz 2191 // intrinsics when the argument is non-zero. 2192 let z = unsafe { intrinsics::ctlz_nonzero(p) }; 2193 <$SelfT>::MAX >> z 2194 } 2195 2196 /// Returns the smallest power of two greater than or equal to `self`. 2197 /// 2198 /// When return value overflows (i.e., `self > (1 << (N-1))` for type 2199 /// `uN`), it panics in debug mode and the return value is wrapped to 0 in 2200 /// release mode (the only situation in which method can return 0). 2201 /// 2202 /// # Examples 2203 /// 2204 /// Basic usage: 2205 /// 2206 /// ``` 2207 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);")] 2208 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);")] 2209 /// ``` 2210 #[stable(feature = "rust1", since = "1.0.0")] 2211 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")] 2212 #[must_use = "this returns the result of the operation, \ 2213 without modifying the original"] 2214 #[inline] 2215 #[rustc_inherit_overflow_checks] 2216 pub const fn next_power_of_two(self) -> Self { 2217 self.one_less_than_next_power_of_two() + 1 2218 } 2219 2220 /// Returns the smallest power of two greater than or equal to `n`. If 2221 /// the next power of two is greater than the type's maximum value, 2222 /// `None` is returned, otherwise the power of two is wrapped in `Some`. 2223 /// 2224 /// # Examples 2225 /// 2226 /// Basic usage: 2227 /// 2228 /// ``` 2229 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_next_power_of_two(), Some(2));")] 2230 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));")] 2231 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_power_of_two(), None);")] 2232 /// ``` 2233 #[inline] 2234 #[stable(feature = "rust1", since = "1.0.0")] 2235 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")] 2236 #[must_use = "this returns the result of the operation, \ 2237 without modifying the original"] 2238 pub const fn checked_next_power_of_two(self) -> Option<Self> { 2239 self.one_less_than_next_power_of_two().checked_add(1) 2240 } 2241 2242 /// Returns the smallest power of two greater than or equal to `n`. If 2243 /// the next power of two is greater than the type's maximum value, 2244 /// the return value is wrapped to `0`. 2245 /// 2246 /// # Examples 2247 /// 2248 /// Basic usage: 2249 /// 2250 /// ``` 2251 /// #![feature(wrapping_next_power_of_two)] 2252 /// 2253 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);")] 2254 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);")] 2255 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_next_power_of_two(), 0);")] 2256 /// ``` 2257 #[inline] 2258 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463", 2259 reason = "needs decision on wrapping behaviour")] 2260 #[rustc_const_unstable(feature = "wrapping_next_power_of_two", issue = "32463")] 2261 #[must_use = "this returns the result of the operation, \ 2262 without modifying the original"] 2263 pub const fn wrapping_next_power_of_two(self) -> Self { 2264 self.one_less_than_next_power_of_two().wrapping_add(1) 2265 } 2266 2267 /// Return the memory representation of this integer as a byte array in 2268 /// big-endian (network) byte order. 2269 /// 2270 #[doc = $to_xe_bytes_doc] 2271 /// 2272 /// # Examples 2273 /// 2274 /// ``` 2275 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();")] 2276 #[doc = concat!("assert_eq!(bytes, ", $be_bytes, ");")] 2277 /// ``` 2278 #[stable(feature = "int_to_from_bytes", since = "1.32.0")] 2279 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")] 2280 #[must_use = "this returns the result of the operation, \ 2281 without modifying the original"] 2282 #[inline] 2283 pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] { 2284 self.to_be().to_ne_bytes() 2285 } 2286 2287 /// Return the memory representation of this integer as a byte array in 2288 /// little-endian byte order. 2289 /// 2290 #[doc = $to_xe_bytes_doc] 2291 /// 2292 /// # Examples 2293 /// 2294 /// ``` 2295 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();")] 2296 #[doc = concat!("assert_eq!(bytes, ", $le_bytes, ");")] 2297 /// ``` 2298 #[stable(feature = "int_to_from_bytes", since = "1.32.0")] 2299 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")] 2300 #[must_use = "this returns the result of the operation, \ 2301 without modifying the original"] 2302 #[inline] 2303 pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] { 2304 self.to_le().to_ne_bytes() 2305 } 2306 2307 /// Return the memory representation of this integer as a byte array in 2308 /// native byte order. 2309 /// 2310 /// As the target platform's native endianness is used, portable code 2311 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, 2312 /// instead. 2313 /// 2314 #[doc = $to_xe_bytes_doc] 2315 /// 2316 /// [`to_be_bytes`]: Self::to_be_bytes 2317 /// [`to_le_bytes`]: Self::to_le_bytes 2318 /// 2319 /// # Examples 2320 /// 2321 /// ``` 2322 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();")] 2323 /// assert_eq!( 2324 /// bytes, 2325 /// if cfg!(target_endian = "big") { 2326 #[doc = concat!(" ", $be_bytes)] 2327 /// } else { 2328 #[doc = concat!(" ", $le_bytes)] 2329 /// } 2330 /// ); 2331 /// ``` 2332 #[stable(feature = "int_to_from_bytes", since = "1.32.0")] 2333 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")] 2334 #[must_use = "this returns the result of the operation, \ 2335 without modifying the original"] 2336 // SAFETY: const sound because integers are plain old datatypes so we can always 2337 // transmute them to arrays of bytes 2338 #[inline] 2339 pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] { 2340 // SAFETY: integers are plain old datatypes so we can always transmute them to 2341 // arrays of bytes 2342 unsafe { mem::transmute(self) } 2343 } 2344 2345 /// Create a native endian integer value from its representation 2346 /// as a byte array in big endian. 2347 /// 2348 #[doc = $from_xe_bytes_doc] 2349 /// 2350 /// # Examples 2351 /// 2352 /// ``` 2353 #[doc = concat!("let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");")] 2354 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")] 2355 /// ``` 2356 /// 2357 /// When starting from a slice rather than an array, fallible conversion APIs can be used: 2358 /// 2359 /// ``` 2360 #[doc = concat!("fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")] 2361 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")] 2362 /// *input = rest; 2363 #[doc = concat!(" ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())")] 2364 /// } 2365 /// ``` 2366 #[stable(feature = "int_to_from_bytes", since = "1.32.0")] 2367 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")] 2368 #[must_use] 2369 #[inline] 2370 pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self { 2371 Self::from_be(Self::from_ne_bytes(bytes)) 2372 } 2373 2374 /// Create a native endian integer value from its representation 2375 /// as a byte array in little endian. 2376 /// 2377 #[doc = $from_xe_bytes_doc] 2378 /// 2379 /// # Examples 2380 /// 2381 /// ``` 2382 #[doc = concat!("let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");")] 2383 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")] 2384 /// ``` 2385 /// 2386 /// When starting from a slice rather than an array, fallible conversion APIs can be used: 2387 /// 2388 /// ``` 2389 #[doc = concat!("fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")] 2390 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")] 2391 /// *input = rest; 2392 #[doc = concat!(" ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())")] 2393 /// } 2394 /// ``` 2395 #[stable(feature = "int_to_from_bytes", since = "1.32.0")] 2396 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")] 2397 #[must_use] 2398 #[inline] 2399 pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self { 2400 Self::from_le(Self::from_ne_bytes(bytes)) 2401 } 2402 2403 /// Create a native endian integer value from its memory representation 2404 /// as a byte array in native endianness. 2405 /// 2406 /// As the target platform's native endianness is used, portable code 2407 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as 2408 /// appropriate instead. 2409 /// 2410 /// [`from_be_bytes`]: Self::from_be_bytes 2411 /// [`from_le_bytes`]: Self::from_le_bytes 2412 /// 2413 #[doc = $from_xe_bytes_doc] 2414 /// 2415 /// # Examples 2416 /// 2417 /// ``` 2418 #[doc = concat!("let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {")] 2419 #[doc = concat!(" ", $be_bytes, "")] 2420 /// } else { 2421 #[doc = concat!(" ", $le_bytes, "")] 2422 /// }); 2423 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")] 2424 /// ``` 2425 /// 2426 /// When starting from a slice rather than an array, fallible conversion APIs can be used: 2427 /// 2428 /// ``` 2429 #[doc = concat!("fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")] 2430 #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<", stringify!($SelfT), ">());")] 2431 /// *input = rest; 2432 #[doc = concat!(" ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())")] 2433 /// } 2434 /// ``` 2435 #[stable(feature = "int_to_from_bytes", since = "1.32.0")] 2436 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")] 2437 #[must_use] 2438 // SAFETY: const sound because integers are plain old datatypes so we can always 2439 // transmute to them 2440 #[inline] 2441 pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self { 2442 // SAFETY: integers are plain old datatypes so we can always transmute to them 2443 unsafe { mem::transmute(bytes) } 2444 } 2445 2446 /// New code should prefer to use 2447 #[doc = concat!("[`", stringify!($SelfT), "::MIN", "`] instead.")] 2448 /// 2449 /// Returns the smallest value that can be represented by this integer type. 2450 #[stable(feature = "rust1", since = "1.0.0")] 2451 #[rustc_promotable] 2452 #[inline(always)] 2453 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")] 2454 #[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on this type")] 2455 pub const fn min_value() -> Self { Self::MIN } 2456 2457 /// New code should prefer to use 2458 #[doc = concat!("[`", stringify!($SelfT), "::MAX", "`] instead.")] 2459 /// 2460 /// Returns the largest value that can be represented by this integer type. 2461 #[stable(feature = "rust1", since = "1.0.0")] 2462 #[rustc_promotable] 2463 #[inline(always)] 2464 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")] 2465 #[deprecated(since = "TBD", note = "replaced by the `MAX` associated constant on this type")] 2466 pub const fn max_value() -> Self { Self::MAX } 2467 } 2468 } 2469