core/num/uint_macros.rs
1macro_rules! uint_impl {
2 (
3 Self = $SelfT:ty,
4 ActualT = $ActualT:ident,
5 SignedT = $SignedT:ident,
6
7 // These are all for use *only* in doc comments.
8 // As such, they're all passed as literals -- passing them as a string
9 // literal is fine if they need to be multiple code tokens.
10 // In non-comments, use the associated constants rather than these.
11 BITS = $BITS:literal,
12 BITS_MINUS_ONE = $BITS_MINUS_ONE:literal,
13 MAX = $MaxV:literal,
14 rot = $rot:literal,
15 rot_op = $rot_op:literal,
16 rot_result = $rot_result:literal,
17 fsh_op = $fsh_op:literal,
18 fshl_result = $fshl_result:literal,
19 fshr_result = $fshr_result:literal,
20 swap_op = $swap_op:literal,
21 swapped = $swapped:literal,
22 reversed = $reversed:literal,
23 le_bytes = $le_bytes:literal,
24 be_bytes = $be_bytes:literal,
25 to_xe_bytes_doc = $to_xe_bytes_doc:expr,
26 from_xe_bytes_doc = $from_xe_bytes_doc:expr,
27 bound_condition = $bound_condition:literal,
28 ) => {
29 /// The smallest value that can be represented by this integer type.
30 ///
31 /// # Examples
32 ///
33 /// ```
34 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MIN, 0);")]
35 /// ```
36 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
37 pub const MIN: Self = 0;
38
39 /// The largest value that can be represented by this integer type
40 #[doc = concat!("(2<sup>", $BITS, "</sup> − 1", $bound_condition, ").")]
41 ///
42 /// # Examples
43 ///
44 /// ```
45 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX, ", stringify!($MaxV), ");")]
46 /// ```
47 #[stable(feature = "assoc_int_consts", since = "1.43.0")]
48 pub const MAX: Self = !0;
49
50 /// The size of this integer type in bits.
51 ///
52 /// # Examples
53 ///
54 /// ```
55 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::BITS, ", stringify!($BITS), ");")]
56 /// ```
57 #[stable(feature = "int_bits_const", since = "1.53.0")]
58 pub const BITS: u32 = Self::MAX.count_ones();
59
60 /// Returns the number of ones in the binary representation of `self`.
61 ///
62 /// # Examples
63 ///
64 /// ```
65 #[doc = concat!("let n = 0b01001100", stringify!($SelfT), ";")]
66 /// assert_eq!(n.count_ones(), 3);
67 ///
68 #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")]
69 #[doc = concat!("assert_eq!(max.count_ones(), ", stringify!($BITS), ");")]
70 ///
71 #[doc = concat!("let zero = 0", stringify!($SelfT), ";")]
72 /// assert_eq!(zero.count_ones(), 0);
73 /// ```
74 #[stable(feature = "rust1", since = "1.0.0")]
75 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
76 #[doc(alias = "popcount")]
77 #[doc(alias = "popcnt")]
78 #[must_use = "this returns the result of the operation, \
79 without modifying the original"]
80 #[inline(always)]
81 pub const fn count_ones(self) -> u32 {
82 return intrinsics::ctpop(self);
83 }
84
85 /// Returns the number of zeros in the binary representation of `self`.
86 ///
87 /// # Examples
88 ///
89 /// ```
90 #[doc = concat!("let zero = 0", stringify!($SelfT), ";")]
91 #[doc = concat!("assert_eq!(zero.count_zeros(), ", stringify!($BITS), ");")]
92 ///
93 #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")]
94 /// assert_eq!(max.count_zeros(), 0);
95 /// ```
96 #[stable(feature = "rust1", since = "1.0.0")]
97 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
98 #[must_use = "this returns the result of the operation, \
99 without modifying the original"]
100 #[inline(always)]
101 pub const fn count_zeros(self) -> u32 {
102 (!self).count_ones()
103 }
104
105 /// Returns the number of leading zeros in the binary representation of `self`.
106 ///
107 /// Depending on what you're doing with the value, you might also be interested in the
108 /// [`ilog2`] function which returns a consistent number, even if the type widens.
109 ///
110 /// # Examples
111 ///
112 /// ```
113 #[doc = concat!("let n = ", stringify!($SelfT), "::MAX >> 2;")]
114 /// assert_eq!(n.leading_zeros(), 2);
115 ///
116 #[doc = concat!("let zero = 0", stringify!($SelfT), ";")]
117 #[doc = concat!("assert_eq!(zero.leading_zeros(), ", stringify!($BITS), ");")]
118 ///
119 #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")]
120 /// assert_eq!(max.leading_zeros(), 0);
121 /// ```
122 #[doc = concat!("[`ilog2`]: ", stringify!($SelfT), "::ilog2")]
123 #[stable(feature = "rust1", since = "1.0.0")]
124 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
125 #[must_use = "this returns the result of the operation, \
126 without modifying the original"]
127 #[inline(always)]
128 pub const fn leading_zeros(self) -> u32 {
129 return intrinsics::ctlz(self as $ActualT);
130 }
131
132 /// Returns the number of trailing zeros in the binary representation
133 /// of `self`.
134 ///
135 /// # Examples
136 ///
137 /// ```
138 #[doc = concat!("let n = 0b0101000", stringify!($SelfT), ";")]
139 /// assert_eq!(n.trailing_zeros(), 3);
140 ///
141 #[doc = concat!("let zero = 0", stringify!($SelfT), ";")]
142 #[doc = concat!("assert_eq!(zero.trailing_zeros(), ", stringify!($BITS), ");")]
143 ///
144 #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")]
145 #[doc = concat!("assert_eq!(max.trailing_zeros(), 0);")]
146 /// ```
147 #[stable(feature = "rust1", since = "1.0.0")]
148 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
149 #[must_use = "this returns the result of the operation, \
150 without modifying the original"]
151 #[inline(always)]
152 pub const fn trailing_zeros(self) -> u32 {
153 return intrinsics::cttz(self);
154 }
155
156 /// Returns the number of leading ones in the binary representation of `self`.
157 ///
158 /// # Examples
159 ///
160 /// ```
161 #[doc = concat!("let n = !(", stringify!($SelfT), "::MAX >> 2);")]
162 /// assert_eq!(n.leading_ones(), 2);
163 ///
164 #[doc = concat!("let zero = 0", stringify!($SelfT), ";")]
165 /// assert_eq!(zero.leading_ones(), 0);
166 ///
167 #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")]
168 #[doc = concat!("assert_eq!(max.leading_ones(), ", stringify!($BITS), ");")]
169 /// ```
170 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
171 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
172 #[must_use = "this returns the result of the operation, \
173 without modifying the original"]
174 #[inline(always)]
175 pub const fn leading_ones(self) -> u32 {
176 (!self).leading_zeros()
177 }
178
179 /// Returns the number of trailing ones in the binary representation
180 /// of `self`.
181 ///
182 /// # Examples
183 ///
184 /// ```
185 #[doc = concat!("let n = 0b1010111", stringify!($SelfT), ";")]
186 /// assert_eq!(n.trailing_ones(), 3);
187 ///
188 #[doc = concat!("let zero = 0", stringify!($SelfT), ";")]
189 /// assert_eq!(zero.trailing_ones(), 0);
190 ///
191 #[doc = concat!("let max = ", stringify!($SelfT),"::MAX;")]
192 #[doc = concat!("assert_eq!(max.trailing_ones(), ", stringify!($BITS), ");")]
193 /// ```
194 #[stable(feature = "leading_trailing_ones", since = "1.46.0")]
195 #[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
196 #[must_use = "this returns the result of the operation, \
197 without modifying the original"]
198 #[inline(always)]
199 pub const fn trailing_ones(self) -> u32 {
200 (!self).trailing_zeros()
201 }
202
203 /// Returns the minimum number of bits required to represent `self`.
204 ///
205 /// This method returns zero if `self` is zero.
206 ///
207 /// # Examples
208 ///
209 /// ```
210 /// #![feature(uint_bit_width)]
211 ///
212 #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".bit_width(), 0);")]
213 #[doc = concat!("assert_eq!(0b111_", stringify!($SelfT), ".bit_width(), 3);")]
214 #[doc = concat!("assert_eq!(0b1110_", stringify!($SelfT), ".bit_width(), 4);")]
215 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.bit_width(), ", stringify!($BITS), ");")]
216 /// ```
217 #[unstable(feature = "uint_bit_width", issue = "142326")]
218 #[must_use = "this returns the result of the operation, \
219 without modifying the original"]
220 #[inline(always)]
221 pub const fn bit_width(self) -> u32 {
222 Self::BITS - self.leading_zeros()
223 }
224
225 /// Returns `self` with only the most significant bit set, or `0` if
226 /// the input is `0`.
227 ///
228 /// # Examples
229 ///
230 /// ```
231 /// #![feature(isolate_most_least_significant_one)]
232 ///
233 #[doc = concat!("let n: ", stringify!($SelfT), " = 0b_01100100;")]
234 ///
235 /// assert_eq!(n.isolate_highest_one(), 0b_01000000);
236 #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".isolate_highest_one(), 0);")]
237 /// ```
238 #[unstable(feature = "isolate_most_least_significant_one", issue = "136909")]
239 #[must_use = "this returns the result of the operation, \
240 without modifying the original"]
241 #[inline(always)]
242 pub const fn isolate_highest_one(self) -> Self {
243 self & (((1 as $SelfT) << (<$SelfT>::BITS - 1)).wrapping_shr(self.leading_zeros()))
244 }
245
246 /// Returns `self` with only the least significant bit set, or `0` if
247 /// the input is `0`.
248 ///
249 /// # Examples
250 ///
251 /// ```
252 /// #![feature(isolate_most_least_significant_one)]
253 ///
254 #[doc = concat!("let n: ", stringify!($SelfT), " = 0b_01100100;")]
255 ///
256 /// assert_eq!(n.isolate_lowest_one(), 0b_00000100);
257 #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".isolate_lowest_one(), 0);")]
258 /// ```
259 #[unstable(feature = "isolate_most_least_significant_one", issue = "136909")]
260 #[must_use = "this returns the result of the operation, \
261 without modifying the original"]
262 #[inline(always)]
263 pub const fn isolate_lowest_one(self) -> Self {
264 self & self.wrapping_neg()
265 }
266
267 /// Returns the index of the highest bit set to one in `self`, or `None`
268 /// if `self` is `0`.
269 ///
270 /// # Examples
271 ///
272 /// ```
273 /// #![feature(int_lowest_highest_one)]
274 ///
275 #[doc = concat!("assert_eq!(0b0_", stringify!($SelfT), ".highest_one(), None);")]
276 #[doc = concat!("assert_eq!(0b1_", stringify!($SelfT), ".highest_one(), Some(0));")]
277 #[doc = concat!("assert_eq!(0b1_0000_", stringify!($SelfT), ".highest_one(), Some(4));")]
278 #[doc = concat!("assert_eq!(0b1_1111_", stringify!($SelfT), ".highest_one(), Some(4));")]
279 /// ```
280 #[unstable(feature = "int_lowest_highest_one", issue = "145203")]
281 #[must_use = "this returns the result of the operation, \
282 without modifying the original"]
283 #[inline(always)]
284 pub const fn highest_one(self) -> Option<u32> {
285 match NonZero::new(self) {
286 Some(v) => Some(v.highest_one()),
287 None => None,
288 }
289 }
290
291 /// Returns the index of the lowest bit set to one in `self`, or `None`
292 /// if `self` is `0`.
293 ///
294 /// # Examples
295 ///
296 /// ```
297 /// #![feature(int_lowest_highest_one)]
298 ///
299 #[doc = concat!("assert_eq!(0b0_", stringify!($SelfT), ".lowest_one(), None);")]
300 #[doc = concat!("assert_eq!(0b1_", stringify!($SelfT), ".lowest_one(), Some(0));")]
301 #[doc = concat!("assert_eq!(0b1_0000_", stringify!($SelfT), ".lowest_one(), Some(4));")]
302 #[doc = concat!("assert_eq!(0b1_1111_", stringify!($SelfT), ".lowest_one(), Some(0));")]
303 /// ```
304 #[unstable(feature = "int_lowest_highest_one", issue = "145203")]
305 #[must_use = "this returns the result of the operation, \
306 without modifying the original"]
307 #[inline(always)]
308 pub const fn lowest_one(self) -> Option<u32> {
309 match NonZero::new(self) {
310 Some(v) => Some(v.lowest_one()),
311 None => None,
312 }
313 }
314
315 /// Returns the bit pattern of `self` reinterpreted as a signed integer of the same size.
316 ///
317 /// This produces the same result as an `as` cast, but ensures that the bit-width remains
318 /// the same.
319 ///
320 /// # Examples
321 ///
322 /// ```
323 #[doc = concat!("let n = ", stringify!($SelfT), "::MAX;")]
324 ///
325 #[doc = concat!("assert_eq!(n.cast_signed(), -1", stringify!($SignedT), ");")]
326 /// ```
327 #[stable(feature = "integer_sign_cast", since = "1.87.0")]
328 #[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
329 #[must_use = "this returns the result of the operation, \
330 without modifying the original"]
331 #[inline(always)]
332 pub const fn cast_signed(self) -> $SignedT {
333 self as $SignedT
334 }
335
336 /// Shifts the bits to the left by a specified amount, `n`,
337 /// wrapping the truncated bits to the end of the resulting integer.
338 ///
339 /// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
340 /// particular, a rotation by the number of bits in `self` returns the input value
341 /// unchanged.
342 ///
343 /// Please note this isn't the same operation as the `<<` shifting operator!
344 ///
345 /// # Examples
346 ///
347 /// ```
348 #[doc = concat!("let n = ", $rot_op, stringify!($SelfT), ";")]
349 #[doc = concat!("let m = ", $rot_result, ";")]
350 ///
351 #[doc = concat!("assert_eq!(n.rotate_left(", $rot, "), m);")]
352 #[doc = concat!("assert_eq!(n.rotate_left(1024), n);")]
353 /// ```
354 #[stable(feature = "rust1", since = "1.0.0")]
355 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
356 #[must_use = "this returns the result of the operation, \
357 without modifying the original"]
358 #[inline(always)]
359 #[rustc_allow_const_fn_unstable(const_trait_impl)] // for the intrinsic fallback
360 pub const fn rotate_left(self, n: u32) -> Self {
361 return intrinsics::rotate_left(self, n);
362 }
363
364 /// Shifts the bits to the right by a specified amount, `n`,
365 /// wrapping the truncated bits to the beginning of the resulting
366 /// integer.
367 ///
368 /// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
369 /// particular, a rotation by the number of bits in `self` returns the input value
370 /// unchanged.
371 ///
372 /// Please note this isn't the same operation as the `>>` shifting operator!
373 ///
374 /// # Examples
375 ///
376 /// ```
377 #[doc = concat!("let n = ", $rot_result, stringify!($SelfT), ";")]
378 #[doc = concat!("let m = ", $rot_op, ";")]
379 ///
380 #[doc = concat!("assert_eq!(n.rotate_right(", $rot, "), m);")]
381 #[doc = concat!("assert_eq!(n.rotate_right(1024), n);")]
382 /// ```
383 #[stable(feature = "rust1", since = "1.0.0")]
384 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
385 #[must_use = "this returns the result of the operation, \
386 without modifying the original"]
387 #[inline(always)]
388 #[rustc_allow_const_fn_unstable(const_trait_impl)] // for the intrinsic fallback
389 pub const fn rotate_right(self, n: u32) -> Self {
390 return intrinsics::rotate_right(self, n);
391 }
392
393 /// Performs a left funnel shift (concatenates `self` with `rhs`, with `self`
394 /// making up the most significant half, then shifts the combined value left
395 /// by `n`, and most significant half is extracted to produce the result).
396 ///
397 /// Please note this isn't the same operation as the `<<` shifting operator or
398 /// [`rotate_left`](Self::rotate_left), although `a.funnel_shl(a, n)` is *equivalent*
399 /// to `a.rotate_left(n)`.
400 ///
401 /// # Panics
402 ///
403 /// If `n` is greater than or equal to the number of bits in `self`
404 ///
405 /// # Examples
406 ///
407 /// Basic usage:
408 ///
409 /// ```
410 /// #![feature(funnel_shifts)]
411 #[doc = concat!("let a = ", $rot_op, stringify!($SelfT), ";")]
412 #[doc = concat!("let b = ", $fsh_op, stringify!($SelfT), ";")]
413 #[doc = concat!("let m = ", $fshl_result, ";")]
414 ///
415 #[doc = concat!("assert_eq!(a.funnel_shl(b, ", $rot, "), m);")]
416 /// ```
417 #[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
418 #[unstable(feature = "funnel_shifts", issue = "145686")]
419 #[must_use = "this returns the result of the operation, \
420 without modifying the original"]
421 #[inline(always)]
422 pub const fn funnel_shl(self, rhs: Self, n: u32) -> Self {
423 assert!(n < Self::BITS, "attempt to funnel shift left with overflow");
424 // SAFETY: just checked that `shift` is in-range
425 unsafe { intrinsics::unchecked_funnel_shl(self, rhs, n) }
426 }
427
428 /// Performs a right funnel shift (concatenates `self` and `rhs`, with `self`
429 /// making up the most significant half, then shifts the combined value right
430 /// by `n`, and least significant half is extracted to produce the result).
431 ///
432 /// Please note this isn't the same operation as the `>>` shifting operator or
433 /// [`rotate_right`](Self::rotate_right), although `a.funnel_shr(a, n)` is *equivalent*
434 /// to `a.rotate_right(n)`.
435 ///
436 /// # Panics
437 ///
438 /// If `n` is greater than or equal to the number of bits in `self`
439 ///
440 /// # Examples
441 ///
442 /// Basic usage:
443 ///
444 /// ```
445 /// #![feature(funnel_shifts)]
446 #[doc = concat!("let a = ", $rot_op, stringify!($SelfT), ";")]
447 #[doc = concat!("let b = ", $fsh_op, stringify!($SelfT), ";")]
448 #[doc = concat!("let m = ", $fshr_result, ";")]
449 ///
450 #[doc = concat!("assert_eq!(a.funnel_shr(b, ", $rot, "), m);")]
451 /// ```
452 #[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
453 #[unstable(feature = "funnel_shifts", issue = "145686")]
454 #[must_use = "this returns the result of the operation, \
455 without modifying the original"]
456 #[inline(always)]
457 pub const fn funnel_shr(self, rhs: Self, n: u32) -> Self {
458 assert!(n < Self::BITS, "attempt to funnel shift right with overflow");
459 // SAFETY: just checked that `shift` is in-range
460 unsafe { intrinsics::unchecked_funnel_shr(self, rhs, n) }
461 }
462
463 /// Reverses the byte order of the integer.
464 ///
465 /// # Examples
466 ///
467 /// ```
468 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
469 /// let m = n.swap_bytes();
470 ///
471 #[doc = concat!("assert_eq!(m, ", $swapped, ");")]
472 /// ```
473 #[stable(feature = "rust1", since = "1.0.0")]
474 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
475 #[must_use = "this returns the result of the operation, \
476 without modifying the original"]
477 #[inline(always)]
478 pub const fn swap_bytes(self) -> Self {
479 intrinsics::bswap(self as $ActualT) as Self
480 }
481
482 /// Returns an integer with the bit locations specified by `mask` packed
483 /// contiguously into the least significant bits of the result.
484 /// ```
485 /// #![feature(uint_gather_scatter_bits)]
486 #[doc = concat!("let n: ", stringify!($SelfT), " = 0b1011_1100;")]
487 ///
488 /// assert_eq!(n.gather_bits(0b0010_0100), 0b0000_0011);
489 /// assert_eq!(n.gather_bits(0xF0), 0b0000_1011);
490 /// ```
491 #[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
492 #[must_use = "this returns the result of the operation, \
493 without modifying the original"]
494 #[inline]
495 pub const fn gather_bits(self, mask: Self) -> Self {
496 crate::num::int_bits::$ActualT::gather_impl(self as $ActualT, mask as $ActualT) as $SelfT
497 }
498
499 /// Returns an integer with the least significant bits of `self`
500 /// distributed to the bit locations specified by `mask`.
501 /// ```
502 /// #![feature(uint_gather_scatter_bits)]
503 #[doc = concat!("let n: ", stringify!($SelfT), " = 0b1010_1101;")]
504 ///
505 /// assert_eq!(n.scatter_bits(0b0101_0101), 0b0101_0001);
506 /// assert_eq!(n.scatter_bits(0xF0), 0b1101_0000);
507 /// ```
508 #[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
509 #[must_use = "this returns the result of the operation, \
510 without modifying the original"]
511 #[inline]
512 pub const fn scatter_bits(self, mask: Self) -> Self {
513 crate::num::int_bits::$ActualT::scatter_impl(self as $ActualT, mask as $ActualT) as $SelfT
514 }
515
516 /// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
517 /// second least-significant bit becomes second most-significant bit, etc.
518 ///
519 /// # Examples
520 ///
521 /// ```
522 #[doc = concat!("let n = ", $swap_op, stringify!($SelfT), ";")]
523 /// let m = n.reverse_bits();
524 ///
525 #[doc = concat!("assert_eq!(m, ", $reversed, ");")]
526 #[doc = concat!("assert_eq!(0, 0", stringify!($SelfT), ".reverse_bits());")]
527 /// ```
528 #[stable(feature = "reverse_bits", since = "1.37.0")]
529 #[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
530 #[must_use = "this returns the result of the operation, \
531 without modifying the original"]
532 #[inline(always)]
533 pub const fn reverse_bits(self) -> Self {
534 intrinsics::bitreverse(self as $ActualT) as Self
535 }
536
537 /// Converts an integer from big endian to the target's endianness.
538 ///
539 /// On big endian this is a no-op. On little endian the bytes are
540 /// swapped.
541 ///
542 /// # Examples
543 ///
544 /// ```
545 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
546 ///
547 /// if cfg!(target_endian = "big") {
548 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n)")]
549 /// } else {
550 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_be(n), n.swap_bytes())")]
551 /// }
552 /// ```
553 #[stable(feature = "rust1", since = "1.0.0")]
554 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
555 #[must_use]
556 #[inline(always)]
557 pub const fn from_be(x: Self) -> Self {
558 #[cfg(target_endian = "big")]
559 {
560 x
561 }
562 #[cfg(not(target_endian = "big"))]
563 {
564 x.swap_bytes()
565 }
566 }
567
568 /// Converts an integer from little endian to the target's endianness.
569 ///
570 /// On little endian this is a no-op. On big endian the bytes are
571 /// swapped.
572 ///
573 /// # Examples
574 ///
575 /// ```
576 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
577 ///
578 /// if cfg!(target_endian = "little") {
579 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n)")]
580 /// } else {
581 #[doc = concat!(" assert_eq!(", stringify!($SelfT), "::from_le(n), n.swap_bytes())")]
582 /// }
583 /// ```
584 #[stable(feature = "rust1", since = "1.0.0")]
585 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
586 #[must_use]
587 #[inline(always)]
588 pub const fn from_le(x: Self) -> Self {
589 #[cfg(target_endian = "little")]
590 {
591 x
592 }
593 #[cfg(not(target_endian = "little"))]
594 {
595 x.swap_bytes()
596 }
597 }
598
599 /// Converts `self` to big endian from the target's endianness.
600 ///
601 /// On big endian this is a no-op. On little endian the bytes are
602 /// swapped.
603 ///
604 /// # Examples
605 ///
606 /// ```
607 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
608 ///
609 /// if cfg!(target_endian = "big") {
610 /// assert_eq!(n.to_be(), n)
611 /// } else {
612 /// assert_eq!(n.to_be(), n.swap_bytes())
613 /// }
614 /// ```
615 #[stable(feature = "rust1", since = "1.0.0")]
616 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
617 #[must_use = "this returns the result of the operation, \
618 without modifying the original"]
619 #[inline(always)]
620 pub const fn to_be(self) -> Self { // or not to be?
621 #[cfg(target_endian = "big")]
622 {
623 self
624 }
625 #[cfg(not(target_endian = "big"))]
626 {
627 self.swap_bytes()
628 }
629 }
630
631 /// Converts `self` to little endian from the target's endianness.
632 ///
633 /// On little endian this is a no-op. On big endian the bytes are
634 /// swapped.
635 ///
636 /// # Examples
637 ///
638 /// ```
639 #[doc = concat!("let n = 0x1A", stringify!($SelfT), ";")]
640 ///
641 /// if cfg!(target_endian = "little") {
642 /// assert_eq!(n.to_le(), n)
643 /// } else {
644 /// assert_eq!(n.to_le(), n.swap_bytes())
645 /// }
646 /// ```
647 #[stable(feature = "rust1", since = "1.0.0")]
648 #[rustc_const_stable(feature = "const_math", since = "1.32.0")]
649 #[must_use = "this returns the result of the operation, \
650 without modifying the original"]
651 #[inline(always)]
652 pub const fn to_le(self) -> Self {
653 #[cfg(target_endian = "little")]
654 {
655 self
656 }
657 #[cfg(not(target_endian = "little"))]
658 {
659 self.swap_bytes()
660 }
661 }
662
663 /// Checked integer addition. Computes `self + rhs`, returning `None`
664 /// if overflow occurred.
665 ///
666 /// # Examples
667 ///
668 /// ```
669 #[doc = concat!(
670 "assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(1), ",
671 "Some(", stringify!($SelfT), "::MAX - 1));"
672 )]
673 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add(3), None);")]
674 /// ```
675 #[stable(feature = "rust1", since = "1.0.0")]
676 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
677 #[must_use = "this returns the result of the operation, \
678 without modifying the original"]
679 #[inline]
680 pub const fn checked_add(self, rhs: Self) -> Option<Self> {
681 // This used to use `overflowing_add`, but that means it ends up being
682 // a `wrapping_add`, losing some optimization opportunities. Notably,
683 // phrasing it this way helps `.checked_add(1)` optimize to a check
684 // against `MAX` and a `add nuw`.
685 // Per <https://github.com/rust-lang/rust/pull/124114#issuecomment-2066173305>,
686 // LLVM is happy to re-form the intrinsic later if useful.
687
688 if intrinsics::unlikely(intrinsics::add_with_overflow(self, rhs).1) {
689 None
690 } else {
691 // SAFETY: Just checked it doesn't overflow
692 Some(unsafe { intrinsics::unchecked_add(self, rhs) })
693 }
694 }
695
696 /// Strict integer addition. Computes `self + rhs`, panicking
697 /// if overflow occurred.
698 ///
699 /// # Panics
700 ///
701 /// ## Overflow behavior
702 ///
703 /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
704 ///
705 /// # Examples
706 ///
707 /// ```
708 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).strict_add(1), ", stringify!($SelfT), "::MAX - 1);")]
709 /// ```
710 ///
711 /// The following panics because of overflow:
712 ///
713 /// ```should_panic
714 #[doc = concat!("let _ = (", stringify!($SelfT), "::MAX - 2).strict_add(3);")]
715 /// ```
716 #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
717 #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
718 #[must_use = "this returns the result of the operation, \
719 without modifying the original"]
720 #[inline]
721 #[track_caller]
722 pub const fn strict_add(self, rhs: Self) -> Self {
723 let (a, b) = self.overflowing_add(rhs);
724 if b { overflow_panic::add() } else { a }
725 }
726
727 /// Unchecked integer addition. Computes `self + rhs`, assuming overflow
728 /// cannot occur.
729 ///
730 /// Calling `x.unchecked_add(y)` is semantically equivalent to calling
731 /// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
732 ///
733 /// If you're just trying to avoid the panic in debug mode, then **do not**
734 /// use this. Instead, you're looking for [`wrapping_add`].
735 ///
736 /// # Safety
737 ///
738 /// This results in undefined behavior when
739 #[doc = concat!("`self + rhs > ", stringify!($SelfT), "::MAX` or `self + rhs < ", stringify!($SelfT), "::MIN`,")]
740 /// i.e. when [`checked_add`] would return `None`.
741 ///
742 /// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
743 #[doc = concat!("[`checked_add`]: ", stringify!($SelfT), "::checked_add")]
744 #[doc = concat!("[`wrapping_add`]: ", stringify!($SelfT), "::wrapping_add")]
745 #[stable(feature = "unchecked_math", since = "1.79.0")]
746 #[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
747 #[must_use = "this returns the result of the operation, \
748 without modifying the original"]
749 #[inline(always)]
750 #[track_caller]
751 pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
752 assert_unsafe_precondition!(
753 check_language_ub,
754 concat!(stringify!($SelfT), "::unchecked_add cannot overflow"),
755 (
756 lhs: $SelfT = self,
757 rhs: $SelfT = rhs,
758 ) => !lhs.overflowing_add(rhs).1,
759 );
760
761 // SAFETY: this is guaranteed to be safe by the caller.
762 unsafe {
763 intrinsics::unchecked_add(self, rhs)
764 }
765 }
766
767 /// Checked addition with a signed integer. Computes `self + rhs`,
768 /// returning `None` if overflow occurred.
769 ///
770 /// # Examples
771 ///
772 /// ```
773 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_signed(2), Some(3));")]
774 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_add_signed(-2), None);")]
775 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_add_signed(3), None);")]
776 /// ```
777 #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
778 #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
779 #[must_use = "this returns the result of the operation, \
780 without modifying the original"]
781 #[inline]
782 pub const fn checked_add_signed(self, rhs: $SignedT) -> Option<Self> {
783 let (a, b) = self.overflowing_add_signed(rhs);
784 if intrinsics::unlikely(b) { None } else { Some(a) }
785 }
786
787 /// Strict addition with a signed integer. Computes `self + rhs`,
788 /// panicking if overflow occurred.
789 ///
790 /// # Panics
791 ///
792 /// ## Overflow behavior
793 ///
794 /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
795 ///
796 /// # Examples
797 ///
798 /// ```
799 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".strict_add_signed(2), 3);")]
800 /// ```
801 ///
802 /// The following panic because of overflow:
803 ///
804 /// ```should_panic
805 #[doc = concat!("let _ = 1", stringify!($SelfT), ".strict_add_signed(-2);")]
806 /// ```
807 ///
808 /// ```should_panic
809 #[doc = concat!("let _ = (", stringify!($SelfT), "::MAX - 2).strict_add_signed(3);")]
810 /// ```
811 #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
812 #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
813 #[must_use = "this returns the result of the operation, \
814 without modifying the original"]
815 #[inline]
816 #[track_caller]
817 pub const fn strict_add_signed(self, rhs: $SignedT) -> Self {
818 let (a, b) = self.overflowing_add_signed(rhs);
819 if b { overflow_panic::add() } else { a }
820 }
821
822 /// Checked integer subtraction. Computes `self - rhs`, returning
823 /// `None` if overflow occurred.
824 ///
825 /// # Examples
826 ///
827 /// ```
828 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub(1), Some(0));")]
829 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".checked_sub(1), None);")]
830 /// ```
831 #[stable(feature = "rust1", since = "1.0.0")]
832 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
833 #[must_use = "this returns the result of the operation, \
834 without modifying the original"]
835 #[inline]
836 pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
837 // Per PR#103299, there's no advantage to the `overflowing` intrinsic
838 // for *unsigned* subtraction and we just emit the manual check anyway.
839 // Thus, rather than using `overflowing_sub` that produces a wrapping
840 // subtraction, check it ourself so we can use an unchecked one.
841
842 if self < rhs {
843 None
844 } else {
845 // SAFETY: just checked this can't overflow
846 Some(unsafe { intrinsics::unchecked_sub(self, rhs) })
847 }
848 }
849
850 /// Strict integer subtraction. Computes `self - rhs`, panicking if
851 /// overflow occurred.
852 ///
853 /// # Panics
854 ///
855 /// ## Overflow behavior
856 ///
857 /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
858 ///
859 /// # Examples
860 ///
861 /// ```
862 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".strict_sub(1), 0);")]
863 /// ```
864 ///
865 /// The following panics because of overflow:
866 ///
867 /// ```should_panic
868 #[doc = concat!("let _ = 0", stringify!($SelfT), ".strict_sub(1);")]
869 /// ```
870 #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
871 #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
872 #[must_use = "this returns the result of the operation, \
873 without modifying the original"]
874 #[inline]
875 #[track_caller]
876 pub const fn strict_sub(self, rhs: Self) -> Self {
877 let (a, b) = self.overflowing_sub(rhs);
878 if b { overflow_panic::sub() } else { a }
879 }
880
881 /// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
882 /// cannot occur.
883 ///
884 /// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
885 /// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
886 ///
887 /// If you're just trying to avoid the panic in debug mode, then **do not**
888 /// use this. Instead, you're looking for [`wrapping_sub`].
889 ///
890 /// If you find yourself writing code like this:
891 ///
892 /// ```
893 /// # let foo = 30_u32;
894 /// # let bar = 20;
895 /// if foo >= bar {
896 /// // SAFETY: just checked it will not overflow
897 /// let diff = unsafe { foo.unchecked_sub(bar) };
898 /// // ... use diff ...
899 /// }
900 /// ```
901 ///
902 /// Consider changing it to
903 ///
904 /// ```
905 /// # let foo = 30_u32;
906 /// # let bar = 20;
907 /// if let Some(diff) = foo.checked_sub(bar) {
908 /// // ... use diff ...
909 /// }
910 /// ```
911 ///
912 /// As that does exactly the same thing -- including telling the optimizer
913 /// that the subtraction cannot overflow -- but avoids needing `unsafe`.
914 ///
915 /// # Safety
916 ///
917 /// This results in undefined behavior when
918 #[doc = concat!("`self - rhs > ", stringify!($SelfT), "::MAX` or `self - rhs < ", stringify!($SelfT), "::MIN`,")]
919 /// i.e. when [`checked_sub`] would return `None`.
920 ///
921 /// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
922 #[doc = concat!("[`checked_sub`]: ", stringify!($SelfT), "::checked_sub")]
923 #[doc = concat!("[`wrapping_sub`]: ", stringify!($SelfT), "::wrapping_sub")]
924 #[stable(feature = "unchecked_math", since = "1.79.0")]
925 #[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
926 #[must_use = "this returns the result of the operation, \
927 without modifying the original"]
928 #[inline(always)]
929 #[track_caller]
930 pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
931 assert_unsafe_precondition!(
932 check_language_ub,
933 concat!(stringify!($SelfT), "::unchecked_sub cannot overflow"),
934 (
935 lhs: $SelfT = self,
936 rhs: $SelfT = rhs,
937 ) => !lhs.overflowing_sub(rhs).1,
938 );
939
940 // SAFETY: this is guaranteed to be safe by the caller.
941 unsafe {
942 intrinsics::unchecked_sub(self, rhs)
943 }
944 }
945
946 /// Checked subtraction with a signed integer. Computes `self - rhs`,
947 /// returning `None` if overflow occurred.
948 ///
949 /// # Examples
950 ///
951 /// ```
952 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub_signed(2), None);")]
953 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_sub_signed(-2), Some(3));")]
954 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).checked_sub_signed(-4), None);")]
955 /// ```
956 #[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
957 #[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
958 #[must_use = "this returns the result of the operation, \
959 without modifying the original"]
960 #[inline]
961 pub const fn checked_sub_signed(self, rhs: $SignedT) -> Option<Self> {
962 let (res, overflow) = self.overflowing_sub_signed(rhs);
963
964 if !overflow {
965 Some(res)
966 } else {
967 None
968 }
969 }
970
971 /// Strict subtraction with a signed integer. Computes `self - rhs`,
972 /// panicking if overflow occurred.
973 ///
974 /// # Panics
975 ///
976 /// ## Overflow behavior
977 ///
978 /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
979 ///
980 /// # Examples
981 ///
982 /// ```
983 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".strict_sub_signed(2), 1);")]
984 /// ```
985 ///
986 /// The following panic because of overflow:
987 ///
988 /// ```should_panic
989 #[doc = concat!("let _ = 1", stringify!($SelfT), ".strict_sub_signed(2);")]
990 /// ```
991 ///
992 /// ```should_panic
993 #[doc = concat!("let _ = (", stringify!($SelfT), "::MAX).strict_sub_signed(-1);")]
994 /// ```
995 #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
996 #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
997 #[must_use = "this returns the result of the operation, \
998 without modifying the original"]
999 #[inline]
1000 #[track_caller]
1001 pub const fn strict_sub_signed(self, rhs: $SignedT) -> Self {
1002 let (a, b) = self.overflowing_sub_signed(rhs);
1003 if b { overflow_panic::sub() } else { a }
1004 }
1005
1006 #[doc = concat!(
1007 "Checked integer subtraction. Computes `self - rhs` and checks if the result fits into an [`",
1008 stringify!($SignedT), "`], returning `None` if overflow occurred."
1009 )]
1010 ///
1011 /// # Examples
1012 ///
1013 /// ```
1014 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_signed_diff(2), Some(8));")]
1015 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_signed_diff(10), Some(-8));")]
1016 #[doc = concat!(
1017 "assert_eq!(",
1018 stringify!($SelfT),
1019 "::MAX.checked_signed_diff(",
1020 stringify!($SignedT),
1021 "::MAX as ",
1022 stringify!($SelfT),
1023 "), None);"
1024 )]
1025 #[doc = concat!(
1026 "assert_eq!((",
1027 stringify!($SignedT),
1028 "::MAX as ",
1029 stringify!($SelfT),
1030 ").checked_signed_diff(",
1031 stringify!($SelfT),
1032 "::MAX), Some(",
1033 stringify!($SignedT),
1034 "::MIN));"
1035 )]
1036 #[doc = concat!(
1037 "assert_eq!((",
1038 stringify!($SignedT),
1039 "::MAX as ",
1040 stringify!($SelfT),
1041 " + 1).checked_signed_diff(0), None);"
1042 )]
1043 #[doc = concat!(
1044 "assert_eq!(",
1045 stringify!($SelfT),
1046 "::MAX.checked_signed_diff(",
1047 stringify!($SelfT),
1048 "::MAX), Some(0));"
1049 )]
1050 /// ```
1051 #[stable(feature = "unsigned_signed_diff", since = "1.91.0")]
1052 #[rustc_const_stable(feature = "unsigned_signed_diff", since = "1.91.0")]
1053 #[inline]
1054 pub const fn checked_signed_diff(self, rhs: Self) -> Option<$SignedT> {
1055 let res = self.wrapping_sub(rhs) as $SignedT;
1056 let overflow = (self >= rhs) == (res < 0);
1057
1058 if !overflow {
1059 Some(res)
1060 } else {
1061 None
1062 }
1063 }
1064
1065 /// Checked integer multiplication. Computes `self * rhs`, returning
1066 /// `None` if overflow occurred.
1067 ///
1068 /// # Examples
1069 ///
1070 /// ```
1071 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_mul(1), Some(5));")]
1072 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_mul(2), None);")]
1073 /// ```
1074 #[stable(feature = "rust1", since = "1.0.0")]
1075 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
1076 #[must_use = "this returns the result of the operation, \
1077 without modifying the original"]
1078 #[inline]
1079 pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
1080 let (a, b) = self.overflowing_mul(rhs);
1081 if intrinsics::unlikely(b) { None } else { Some(a) }
1082 }
1083
1084 /// Strict integer multiplication. Computes `self * rhs`, panicking if
1085 /// overflow occurred.
1086 ///
1087 /// # Panics
1088 ///
1089 /// ## Overflow behavior
1090 ///
1091 /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
1092 ///
1093 /// # Examples
1094 ///
1095 /// ```
1096 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".strict_mul(1), 5);")]
1097 /// ```
1098 ///
1099 /// The following panics because of overflow:
1100 ///
1101 /// ``` should_panic
1102 #[doc = concat!("let _ = ", stringify!($SelfT), "::MAX.strict_mul(2);")]
1103 /// ```
1104 #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
1105 #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
1106 #[must_use = "this returns the result of the operation, \
1107 without modifying the original"]
1108 #[inline]
1109 #[track_caller]
1110 pub const fn strict_mul(self, rhs: Self) -> Self {
1111 let (a, b) = self.overflowing_mul(rhs);
1112 if b { overflow_panic::mul() } else { a }
1113 }
1114
1115 /// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
1116 /// cannot occur.
1117 ///
1118 /// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
1119 /// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
1120 ///
1121 /// If you're just trying to avoid the panic in debug mode, then **do not**
1122 /// use this. Instead, you're looking for [`wrapping_mul`].
1123 ///
1124 /// # Safety
1125 ///
1126 /// This results in undefined behavior when
1127 #[doc = concat!("`self * rhs > ", stringify!($SelfT), "::MAX` or `self * rhs < ", stringify!($SelfT), "::MIN`,")]
1128 /// i.e. when [`checked_mul`] would return `None`.
1129 ///
1130 /// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
1131 #[doc = concat!("[`checked_mul`]: ", stringify!($SelfT), "::checked_mul")]
1132 #[doc = concat!("[`wrapping_mul`]: ", stringify!($SelfT), "::wrapping_mul")]
1133 #[stable(feature = "unchecked_math", since = "1.79.0")]
1134 #[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
1135 #[must_use = "this returns the result of the operation, \
1136 without modifying the original"]
1137 #[inline(always)]
1138 #[track_caller]
1139 pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
1140 assert_unsafe_precondition!(
1141 check_language_ub,
1142 concat!(stringify!($SelfT), "::unchecked_mul cannot overflow"),
1143 (
1144 lhs: $SelfT = self,
1145 rhs: $SelfT = rhs,
1146 ) => !lhs.overflowing_mul(rhs).1,
1147 );
1148
1149 // SAFETY: this is guaranteed to be safe by the caller.
1150 unsafe {
1151 intrinsics::unchecked_mul(self, rhs)
1152 }
1153 }
1154
1155 /// Checked integer division. Computes `self / rhs`, returning `None`
1156 /// if `rhs == 0`.
1157 ///
1158 /// # Examples
1159 ///
1160 /// ```
1161 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".checked_div(2), Some(64));")]
1162 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_div(0), None);")]
1163 /// ```
1164 #[stable(feature = "rust1", since = "1.0.0")]
1165 #[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
1166 #[must_use = "this returns the result of the operation, \
1167 without modifying the original"]
1168 #[inline]
1169 pub const fn checked_div(self, rhs: Self) -> Option<Self> {
1170 if intrinsics::unlikely(rhs == 0) {
1171 None
1172 } else {
1173 // SAFETY: div by zero has been checked above and unsigned types have no other
1174 // failure modes for division
1175 Some(unsafe { intrinsics::unchecked_div(self, rhs) })
1176 }
1177 }
1178
1179 /// Strict integer division. Computes `self / rhs`.
1180 ///
1181 /// Strict division on unsigned types is just normal division. There's no
1182 /// way overflow could ever happen. This function exists so that all
1183 /// operations are accounted for in the strict operations.
1184 ///
1185 /// # Panics
1186 ///
1187 /// This function will panic if `rhs` is zero.
1188 ///
1189 /// # Examples
1190 ///
1191 /// ```
1192 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".strict_div(10), 10);")]
1193 /// ```
1194 ///
1195 /// The following panics because of division by zero:
1196 ///
1197 /// ```should_panic
1198 #[doc = concat!("let _ = (1", stringify!($SelfT), ").strict_div(0);")]
1199 /// ```
1200 #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
1201 #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
1202 #[must_use = "this returns the result of the operation, \
1203 without modifying the original"]
1204 #[inline(always)]
1205 #[track_caller]
1206 pub const fn strict_div(self, rhs: Self) -> Self {
1207 self / rhs
1208 }
1209
1210 /// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
1211 /// if `rhs == 0`.
1212 ///
1213 /// # Examples
1214 ///
1215 /// ```
1216 #[doc = concat!("assert_eq!(128", stringify!($SelfT), ".checked_div_euclid(2), Some(64));")]
1217 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_div_euclid(0), None);")]
1218 /// ```
1219 #[stable(feature = "euclidean_division", since = "1.38.0")]
1220 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1221 #[must_use = "this returns the result of the operation, \
1222 without modifying the original"]
1223 #[inline]
1224 pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
1225 if intrinsics::unlikely(rhs == 0) {
1226 None
1227 } else {
1228 Some(self.div_euclid(rhs))
1229 }
1230 }
1231
1232 /// Strict Euclidean division. Computes `self.div_euclid(rhs)`.
1233 ///
1234 /// Strict division on unsigned types is just normal division. There's no
1235 /// way overflow could ever happen. This function exists so that all
1236 /// operations are accounted for in the strict operations. Since, for the
1237 /// positive integers, all common definitions of division are equal, this
1238 /// is exactly equal to `self.strict_div(rhs)`.
1239 ///
1240 /// # Panics
1241 ///
1242 /// This function will panic if `rhs` is zero.
1243 ///
1244 /// # Examples
1245 ///
1246 /// ```
1247 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".strict_div_euclid(10), 10);")]
1248 /// ```
1249 /// The following panics because of division by zero:
1250 ///
1251 /// ```should_panic
1252 #[doc = concat!("let _ = (1", stringify!($SelfT), ").strict_div_euclid(0);")]
1253 /// ```
1254 #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
1255 #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
1256 #[must_use = "this returns the result of the operation, \
1257 without modifying the original"]
1258 #[inline(always)]
1259 #[track_caller]
1260 pub const fn strict_div_euclid(self, rhs: Self) -> Self {
1261 self / rhs
1262 }
1263
1264 /// Checked integer division without remainder. Computes `self / rhs`,
1265 /// returning `None` if `rhs == 0` or if `self % rhs != 0`.
1266 ///
1267 /// # Examples
1268 ///
1269 /// ```
1270 /// #![feature(exact_div)]
1271 #[doc = concat!("assert_eq!(64", stringify!($SelfT), ".checked_div_exact(2), Some(32));")]
1272 #[doc = concat!("assert_eq!(64", stringify!($SelfT), ".checked_div_exact(32), Some(2));")]
1273 #[doc = concat!("assert_eq!(64", stringify!($SelfT), ".checked_div_exact(0), None);")]
1274 #[doc = concat!("assert_eq!(65", stringify!($SelfT), ".checked_div_exact(2), None);")]
1275 /// ```
1276 #[unstable(
1277 feature = "exact_div",
1278 issue = "139911",
1279 )]
1280 #[must_use = "this returns the result of the operation, \
1281 without modifying the original"]
1282 #[inline]
1283 pub const fn checked_div_exact(self, rhs: Self) -> Option<Self> {
1284 if intrinsics::unlikely(rhs == 0) {
1285 None
1286 } else {
1287 // SAFETY: division by zero is checked above
1288 unsafe {
1289 if intrinsics::unlikely(intrinsics::unchecked_rem(self, rhs) != 0) {
1290 None
1291 } else {
1292 Some(intrinsics::exact_div(self, rhs))
1293 }
1294 }
1295 }
1296 }
1297
1298 /// Integer division without remainder. Computes `self / rhs`, returning `None` if `self % rhs != 0`.
1299 ///
1300 /// # Panics
1301 ///
1302 /// This function will panic if `rhs == 0`.
1303 ///
1304 /// # Examples
1305 ///
1306 /// ```
1307 /// #![feature(exact_div)]
1308 #[doc = concat!("assert_eq!(64", stringify!($SelfT), ".div_exact(2), Some(32));")]
1309 #[doc = concat!("assert_eq!(64", stringify!($SelfT), ".div_exact(32), Some(2));")]
1310 #[doc = concat!("assert_eq!(65", stringify!($SelfT), ".div_exact(2), None);")]
1311 /// ```
1312 #[unstable(
1313 feature = "exact_div",
1314 issue = "139911",
1315 )]
1316 #[must_use = "this returns the result of the operation, \
1317 without modifying the original"]
1318 #[inline]
1319 #[rustc_inherit_overflow_checks]
1320 pub const fn div_exact(self, rhs: Self) -> Option<Self> {
1321 if self % rhs != 0 {
1322 None
1323 } else {
1324 Some(self / rhs)
1325 }
1326 }
1327
1328 /// Unchecked integer division without remainder. Computes `self / rhs`.
1329 ///
1330 /// # Safety
1331 ///
1332 /// This results in undefined behavior when `rhs == 0` or `self % rhs != 0`,
1333 /// i.e. when [`checked_div_exact`](Self::checked_div_exact) would return `None`.
1334 #[unstable(
1335 feature = "exact_div",
1336 issue = "139911",
1337 )]
1338 #[must_use = "this returns the result of the operation, \
1339 without modifying the original"]
1340 #[inline]
1341 pub const unsafe fn unchecked_div_exact(self, rhs: Self) -> Self {
1342 assert_unsafe_precondition!(
1343 check_language_ub,
1344 concat!(stringify!($SelfT), "::unchecked_div_exact divide by zero or leave a remainder"),
1345 (
1346 lhs: $SelfT = self,
1347 rhs: $SelfT = rhs,
1348 ) => rhs > 0 && lhs % rhs == 0,
1349 );
1350 // SAFETY: Same precondition
1351 unsafe { intrinsics::exact_div(self, rhs) }
1352 }
1353
1354 /// Checked integer remainder. Computes `self % rhs`, returning `None`
1355 /// if `rhs == 0`.
1356 ///
1357 /// # Examples
1358 ///
1359 /// ```
1360 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(2), Some(1));")]
1361 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem(0), None);")]
1362 /// ```
1363 #[stable(feature = "wrapping", since = "1.7.0")]
1364 #[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
1365 #[must_use = "this returns the result of the operation, \
1366 without modifying the original"]
1367 #[inline]
1368 pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
1369 if intrinsics::unlikely(rhs == 0) {
1370 None
1371 } else {
1372 // SAFETY: div by zero has been checked above and unsigned types have no other
1373 // failure modes for division
1374 Some(unsafe { intrinsics::unchecked_rem(self, rhs) })
1375 }
1376 }
1377
1378 /// Strict integer remainder. Computes `self % rhs`.
1379 ///
1380 /// Strict remainder calculation on unsigned types is just the regular
1381 /// remainder calculation. There's no way overflow could ever happen.
1382 /// This function exists so that all operations are accounted for in the
1383 /// strict operations.
1384 ///
1385 /// # Panics
1386 ///
1387 /// This function will panic if `rhs` is zero.
1388 ///
1389 /// # Examples
1390 ///
1391 /// ```
1392 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".strict_rem(10), 0);")]
1393 /// ```
1394 ///
1395 /// The following panics because of division by zero:
1396 ///
1397 /// ```should_panic
1398 #[doc = concat!("let _ = 5", stringify!($SelfT), ".strict_rem(0);")]
1399 /// ```
1400 #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
1401 #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
1402 #[must_use = "this returns the result of the operation, \
1403 without modifying the original"]
1404 #[inline(always)]
1405 #[track_caller]
1406 pub const fn strict_rem(self, rhs: Self) -> Self {
1407 self % rhs
1408 }
1409
1410 /// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
1411 /// if `rhs == 0`.
1412 ///
1413 /// # Examples
1414 ///
1415 /// ```
1416 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(2), Some(1));")]
1417 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_rem_euclid(0), None);")]
1418 /// ```
1419 #[stable(feature = "euclidean_division", since = "1.38.0")]
1420 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
1421 #[must_use = "this returns the result of the operation, \
1422 without modifying the original"]
1423 #[inline]
1424 pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
1425 if intrinsics::unlikely(rhs == 0) {
1426 None
1427 } else {
1428 Some(self.rem_euclid(rhs))
1429 }
1430 }
1431
1432 /// Strict Euclidean modulo. Computes `self.rem_euclid(rhs)`.
1433 ///
1434 /// Strict modulo calculation on unsigned types is just the regular
1435 /// remainder calculation. There's no way overflow could ever happen.
1436 /// This function exists so that all operations are accounted for in the
1437 /// strict operations. Since, for the positive integers, all common
1438 /// definitions of division are equal, this is exactly equal to
1439 /// `self.strict_rem(rhs)`.
1440 ///
1441 /// # Panics
1442 ///
1443 /// This function will panic if `rhs` is zero.
1444 ///
1445 /// # Examples
1446 ///
1447 /// ```
1448 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".strict_rem_euclid(10), 0);")]
1449 /// ```
1450 ///
1451 /// The following panics because of division by zero:
1452 ///
1453 /// ```should_panic
1454 #[doc = concat!("let _ = 5", stringify!($SelfT), ".strict_rem_euclid(0);")]
1455 /// ```
1456 #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
1457 #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
1458 #[must_use = "this returns the result of the operation, \
1459 without modifying the original"]
1460 #[inline(always)]
1461 #[track_caller]
1462 pub const fn strict_rem_euclid(self, rhs: Self) -> Self {
1463 self % rhs
1464 }
1465
1466 /// Same value as `self | other`, but UB if any bit position is set in both inputs.
1467 ///
1468 /// This is a situational micro-optimization for places where you'd rather
1469 /// use addition on some platforms and bitwise or on other platforms, based
1470 /// on exactly which instructions combine better with whatever else you're
1471 /// doing. Note that there's no reason to bother using this for places
1472 /// where it's clear from the operations involved that they can't overlap.
1473 /// For example, if you're combining `u16`s into a `u32` with
1474 /// `((a as u32) << 16) | (b as u32)`, that's fine, as the backend will
1475 /// know those sides of the `|` are disjoint without needing help.
1476 ///
1477 /// # Examples
1478 ///
1479 /// ```
1480 /// #![feature(disjoint_bitor)]
1481 ///
1482 /// // SAFETY: `1` and `4` have no bits in common.
1483 /// unsafe {
1484 #[doc = concat!(" assert_eq!(1_", stringify!($SelfT), ".unchecked_disjoint_bitor(4), 5);")]
1485 /// }
1486 /// ```
1487 ///
1488 /// # Safety
1489 ///
1490 /// Requires that `(self & other) == 0`, otherwise it's immediate UB.
1491 ///
1492 /// Equivalently, requires that `(self | other) == (self + other)`.
1493 #[unstable(feature = "disjoint_bitor", issue = "135758")]
1494 #[rustc_const_unstable(feature = "disjoint_bitor", issue = "135758")]
1495 #[inline]
1496 pub const unsafe fn unchecked_disjoint_bitor(self, other: Self) -> Self {
1497 assert_unsafe_precondition!(
1498 check_language_ub,
1499 concat!(stringify!($SelfT), "::unchecked_disjoint_bitor cannot have overlapping bits"),
1500 (
1501 lhs: $SelfT = self,
1502 rhs: $SelfT = other,
1503 ) => (lhs & rhs) == 0,
1504 );
1505
1506 // SAFETY: Same precondition
1507 unsafe { intrinsics::disjoint_bitor(self, other) }
1508 }
1509
1510 /// Returns the logarithm of the number with respect to an arbitrary base,
1511 /// rounded down.
1512 ///
1513 /// This method might not be optimized owing to implementation details;
1514 /// `ilog2` can produce results more efficiently for base 2, and `ilog10`
1515 /// can produce results more efficiently for base 10.
1516 ///
1517 /// # Panics
1518 ///
1519 /// This function will panic if `self` is zero, or if `base` is less than 2.
1520 ///
1521 /// # Examples
1522 ///
1523 /// ```
1524 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".ilog(5), 1);")]
1525 /// ```
1526 #[stable(feature = "int_log", since = "1.67.0")]
1527 #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1528 #[must_use = "this returns the result of the operation, \
1529 without modifying the original"]
1530 #[inline]
1531 #[track_caller]
1532 pub const fn ilog(self, base: Self) -> u32 {
1533 assert!(base >= 2, "base of integer logarithm must be at least 2");
1534 if let Some(log) = self.checked_ilog(base) {
1535 log
1536 } else {
1537 int_log10::panic_for_nonpositive_argument()
1538 }
1539 }
1540
1541 /// Returns the base 2 logarithm of the number, rounded down.
1542 ///
1543 /// # Panics
1544 ///
1545 /// This function will panic if `self` is zero.
1546 ///
1547 /// # Examples
1548 ///
1549 /// ```
1550 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".ilog2(), 1);")]
1551 /// ```
1552 #[stable(feature = "int_log", since = "1.67.0")]
1553 #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1554 #[must_use = "this returns the result of the operation, \
1555 without modifying the original"]
1556 #[inline]
1557 #[track_caller]
1558 pub const fn ilog2(self) -> u32 {
1559 if let Some(log) = self.checked_ilog2() {
1560 log
1561 } else {
1562 int_log10::panic_for_nonpositive_argument()
1563 }
1564 }
1565
1566 /// Returns the base 10 logarithm of the number, rounded down.
1567 ///
1568 /// # Panics
1569 ///
1570 /// This function will panic if `self` is zero.
1571 ///
1572 /// # Example
1573 ///
1574 /// ```
1575 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".ilog10(), 1);")]
1576 /// ```
1577 #[stable(feature = "int_log", since = "1.67.0")]
1578 #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1579 #[must_use = "this returns the result of the operation, \
1580 without modifying the original"]
1581 #[inline]
1582 #[track_caller]
1583 pub const fn ilog10(self) -> u32 {
1584 if let Some(log) = self.checked_ilog10() {
1585 log
1586 } else {
1587 int_log10::panic_for_nonpositive_argument()
1588 }
1589 }
1590
1591 /// Returns the logarithm of the number with respect to an arbitrary base,
1592 /// rounded down.
1593 ///
1594 /// Returns `None` if the number is zero, or if the base is not at least 2.
1595 ///
1596 /// This method might not be optimized owing to implementation details;
1597 /// `checked_ilog2` can produce results more efficiently for base 2, and
1598 /// `checked_ilog10` can produce results more efficiently for base 10.
1599 ///
1600 /// # Examples
1601 ///
1602 /// ```
1603 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".checked_ilog(5), Some(1));")]
1604 /// ```
1605 #[stable(feature = "int_log", since = "1.67.0")]
1606 #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1607 #[must_use = "this returns the result of the operation, \
1608 without modifying the original"]
1609 #[inline]
1610 pub const fn checked_ilog(self, base: Self) -> Option<u32> {
1611 // Inform compiler of optimizations when the base is known at
1612 // compile time and there's a cheaper method available.
1613 //
1614 // Note: Like all optimizations, this is not guaranteed to be
1615 // applied by the compiler. If you want those specific bases,
1616 // use `.checked_ilog2()` or `.checked_ilog10()` directly.
1617 if core::intrinsics::is_val_statically_known(base) {
1618 if base == 2 {
1619 return self.checked_ilog2();
1620 } else if base == 10 {
1621 return self.checked_ilog10();
1622 }
1623 }
1624
1625 if self <= 0 || base <= 1 {
1626 None
1627 } else if self < base {
1628 Some(0)
1629 } else {
1630 // Since base >= self, n >= 1
1631 let mut n = 1;
1632 let mut r = base;
1633
1634 // Optimization for 128 bit wide integers.
1635 if Self::BITS == 128 {
1636 // The following is a correct lower bound for ⌊log(base,self)⌋ because
1637 //
1638 // log(base,self) = log(2,self) / log(2,base)
1639 // ≥ ⌊log(2,self)⌋ / (⌊log(2,base)⌋ + 1)
1640 //
1641 // hence
1642 //
1643 // ⌊log(base,self)⌋ ≥ ⌊ ⌊log(2,self)⌋ / (⌊log(2,base)⌋ + 1) ⌋ .
1644 n = self.ilog2() / (base.ilog2() + 1);
1645 r = base.pow(n);
1646 }
1647
1648 while r <= self / base {
1649 n += 1;
1650 r *= base;
1651 }
1652 Some(n)
1653 }
1654 }
1655
1656 /// Returns the base 2 logarithm of the number, rounded down.
1657 ///
1658 /// Returns `None` if the number is zero.
1659 ///
1660 /// # Examples
1661 ///
1662 /// ```
1663 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_ilog2(), Some(1));")]
1664 /// ```
1665 #[stable(feature = "int_log", since = "1.67.0")]
1666 #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1667 #[must_use = "this returns the result of the operation, \
1668 without modifying the original"]
1669 #[inline]
1670 pub const fn checked_ilog2(self) -> Option<u32> {
1671 match NonZero::new(self) {
1672 Some(x) => Some(x.ilog2()),
1673 None => None,
1674 }
1675 }
1676
1677 /// Returns the base 10 logarithm of the number, rounded down.
1678 ///
1679 /// Returns `None` if the number is zero.
1680 ///
1681 /// # Examples
1682 ///
1683 /// ```
1684 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".checked_ilog10(), Some(1));")]
1685 /// ```
1686 #[stable(feature = "int_log", since = "1.67.0")]
1687 #[rustc_const_stable(feature = "int_log", since = "1.67.0")]
1688 #[must_use = "this returns the result of the operation, \
1689 without modifying the original"]
1690 #[inline]
1691 pub const fn checked_ilog10(self) -> Option<u32> {
1692 match NonZero::new(self) {
1693 Some(x) => Some(x.ilog10()),
1694 None => None,
1695 }
1696 }
1697
1698 /// Checked negation. Computes `-self`, returning `None` unless `self ==
1699 /// 0`.
1700 ///
1701 /// Note that negating any positive integer will overflow.
1702 ///
1703 /// # Examples
1704 ///
1705 /// ```
1706 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".checked_neg(), Some(0));")]
1707 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".checked_neg(), None);")]
1708 /// ```
1709 #[stable(feature = "wrapping", since = "1.7.0")]
1710 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
1711 #[must_use = "this returns the result of the operation, \
1712 without modifying the original"]
1713 #[inline]
1714 pub const fn checked_neg(self) -> Option<Self> {
1715 let (a, b) = self.overflowing_neg();
1716 if intrinsics::unlikely(b) { None } else { Some(a) }
1717 }
1718
1719 /// Strict negation. Computes `-self`, panicking unless `self ==
1720 /// 0`.
1721 ///
1722 /// Note that negating any positive integer will overflow.
1723 ///
1724 /// # Panics
1725 ///
1726 /// ## Overflow behavior
1727 ///
1728 /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
1729 ///
1730 /// # Examples
1731 ///
1732 /// ```
1733 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".strict_neg(), 0);")]
1734 /// ```
1735 ///
1736 /// The following panics because of overflow:
1737 ///
1738 /// ```should_panic
1739 #[doc = concat!("let _ = 1", stringify!($SelfT), ".strict_neg();")]
1740 /// ```
1741 #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
1742 #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
1743 #[must_use = "this returns the result of the operation, \
1744 without modifying the original"]
1745 #[inline]
1746 #[track_caller]
1747 pub const fn strict_neg(self) -> Self {
1748 let (a, b) = self.overflowing_neg();
1749 if b { overflow_panic::neg() } else { a }
1750 }
1751
1752 /// Checked shift left. Computes `self << rhs`, returning `None`
1753 /// if `rhs` is larger than or equal to the number of bits in `self`.
1754 ///
1755 /// # Examples
1756 ///
1757 /// ```
1758 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".checked_shl(4), Some(0x10));")]
1759 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shl(129), None);")]
1760 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shl(", stringify!($BITS_MINUS_ONE), "), Some(0));")]
1761 /// ```
1762 #[stable(feature = "wrapping", since = "1.7.0")]
1763 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
1764 #[must_use = "this returns the result of the operation, \
1765 without modifying the original"]
1766 #[inline]
1767 pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
1768 // Not using overflowing_shl as that's a wrapping shift
1769 if rhs < Self::BITS {
1770 // SAFETY: just checked the RHS is in-range
1771 Some(unsafe { self.unchecked_shl(rhs) })
1772 } else {
1773 None
1774 }
1775 }
1776
1777 /// Strict shift left. Computes `self << rhs`, panicking if `rhs` is larger
1778 /// than or equal to the number of bits in `self`.
1779 ///
1780 /// # Panics
1781 ///
1782 /// ## Overflow behavior
1783 ///
1784 /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
1785 ///
1786 /// # Examples
1787 ///
1788 /// ```
1789 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".strict_shl(4), 0x10);")]
1790 /// ```
1791 ///
1792 /// The following panics because of overflow:
1793 ///
1794 /// ```should_panic
1795 #[doc = concat!("let _ = 0x10", stringify!($SelfT), ".strict_shl(129);")]
1796 /// ```
1797 #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
1798 #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
1799 #[must_use = "this returns the result of the operation, \
1800 without modifying the original"]
1801 #[inline]
1802 #[track_caller]
1803 pub const fn strict_shl(self, rhs: u32) -> Self {
1804 let (a, b) = self.overflowing_shl(rhs);
1805 if b { overflow_panic::shl() } else { a }
1806 }
1807
1808 /// Unchecked shift left. Computes `self << rhs`, assuming that
1809 /// `rhs` is less than the number of bits in `self`.
1810 ///
1811 /// # Safety
1812 ///
1813 /// This results in undefined behavior if `rhs` is larger than
1814 /// or equal to the number of bits in `self`,
1815 /// i.e. when [`checked_shl`] would return `None`.
1816 ///
1817 #[doc = concat!("[`checked_shl`]: ", stringify!($SelfT), "::checked_shl")]
1818 #[stable(feature = "unchecked_shifts", since = "1.93.0")]
1819 #[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
1820 #[must_use = "this returns the result of the operation, \
1821 without modifying the original"]
1822 #[inline(always)]
1823 #[track_caller]
1824 pub const unsafe fn unchecked_shl(self, rhs: u32) -> Self {
1825 assert_unsafe_precondition!(
1826 check_language_ub,
1827 concat!(stringify!($SelfT), "::unchecked_shl cannot overflow"),
1828 (
1829 rhs: u32 = rhs,
1830 ) => rhs < <$ActualT>::BITS,
1831 );
1832
1833 // SAFETY: this is guaranteed to be safe by the caller.
1834 unsafe {
1835 intrinsics::unchecked_shl(self, rhs)
1836 }
1837 }
1838
1839 /// Unbounded shift left. Computes `self << rhs`, without bounding the value of `rhs`.
1840 ///
1841 /// If `rhs` is larger or equal to the number of bits in `self`,
1842 /// the entire value is shifted out, and `0` is returned.
1843 ///
1844 /// # Examples
1845 ///
1846 /// ```
1847 #[doc = concat!("assert_eq!(0x1_", stringify!($SelfT), ".unbounded_shl(4), 0x10);")]
1848 #[doc = concat!("assert_eq!(0x1_", stringify!($SelfT), ".unbounded_shl(129), 0);")]
1849 #[doc = concat!("assert_eq!(0b101_", stringify!($SelfT), ".unbounded_shl(0), 0b101);")]
1850 #[doc = concat!("assert_eq!(0b101_", stringify!($SelfT), ".unbounded_shl(1), 0b1010);")]
1851 #[doc = concat!("assert_eq!(0b101_", stringify!($SelfT), ".unbounded_shl(2), 0b10100);")]
1852 #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".unbounded_shl(", stringify!($BITS), "), 0);")]
1853 #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".unbounded_shl(1).unbounded_shl(", stringify!($BITS_MINUS_ONE), "), 0);")]
1854 ///
1855 #[doc = concat!("let start : ", stringify!($SelfT), " = 13;")]
1856 /// let mut running = start;
1857 /// for i in 0..160 {
1858 /// // The unbounded shift left by i is the same as `<< 1` i times
1859 /// assert_eq!(running, start.unbounded_shl(i));
1860 /// // Which is not always the case for a wrapping shift
1861 #[doc = concat!(" assert_eq!(running == start.wrapping_shl(i), i < ", stringify!($BITS), ");")]
1862 ///
1863 /// running <<= 1;
1864 /// }
1865 /// ```
1866 #[stable(feature = "unbounded_shifts", since = "1.87.0")]
1867 #[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
1868 #[must_use = "this returns the result of the operation, \
1869 without modifying the original"]
1870 #[inline]
1871 pub const fn unbounded_shl(self, rhs: u32) -> $SelfT{
1872 if rhs < Self::BITS {
1873 // SAFETY:
1874 // rhs is just checked to be in-range above
1875 unsafe { self.unchecked_shl(rhs) }
1876 } else {
1877 0
1878 }
1879 }
1880
1881 /// Exact shift left. Computes `self << rhs` as long as it can be reversed losslessly.
1882 ///
1883 /// Returns `None` if any non-zero bits would be shifted out or if `rhs` >=
1884 #[doc = concat!("`", stringify!($SelfT), "::BITS`.")]
1885 /// Otherwise, returns `Some(self << rhs)`.
1886 ///
1887 /// # Examples
1888 ///
1889 /// ```
1890 /// #![feature(exact_bitshifts)]
1891 ///
1892 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".shl_exact(4), Some(0x10));")]
1893 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".shl_exact(129), None);")]
1894 /// ```
1895 #[unstable(feature = "exact_bitshifts", issue = "144336")]
1896 #[must_use = "this returns the result of the operation, \
1897 without modifying the original"]
1898 #[inline]
1899 pub const fn shl_exact(self, rhs: u32) -> Option<$SelfT> {
1900 if rhs <= self.leading_zeros() && rhs < <$SelfT>::BITS {
1901 // SAFETY: rhs is checked above
1902 Some(unsafe { self.unchecked_shl(rhs) })
1903 } else {
1904 None
1905 }
1906 }
1907
1908 /// Unchecked exact shift left. Computes `self << rhs`, assuming the operation can be
1909 /// losslessly reversed `rhs` cannot be larger than
1910 #[doc = concat!("`", stringify!($SelfT), "::BITS`.")]
1911 ///
1912 /// # Safety
1913 ///
1914 /// This results in undefined behavior when `rhs > self.leading_zeros() || rhs >=
1915 #[doc = concat!(stringify!($SelfT), "::BITS`")]
1916 /// i.e. when
1917 #[doc = concat!("[`", stringify!($SelfT), "::shl_exact`]")]
1918 /// would return `None`.
1919 #[unstable(feature = "exact_bitshifts", issue = "144336")]
1920 #[must_use = "this returns the result of the operation, \
1921 without modifying the original"]
1922 #[inline]
1923 pub const unsafe fn unchecked_shl_exact(self, rhs: u32) -> $SelfT {
1924 assert_unsafe_precondition!(
1925 check_library_ub,
1926 concat!(stringify!($SelfT), "::unchecked_shl_exact cannot shift out non-zero bits"),
1927 (
1928 zeros: u32 = self.leading_zeros(),
1929 bits: u32 = <$SelfT>::BITS,
1930 rhs: u32 = rhs,
1931 ) => rhs <= zeros && rhs < bits,
1932 );
1933
1934 // SAFETY: this is guaranteed to be safe by the caller
1935 unsafe { self.unchecked_shl(rhs) }
1936 }
1937
1938 /// Checked shift right. Computes `self >> rhs`, returning `None`
1939 /// if `rhs` is larger than or equal to the number of bits in `self`.
1940 ///
1941 /// # Examples
1942 ///
1943 /// ```
1944 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(4), Some(0x1));")]
1945 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".checked_shr(129), None);")]
1946 /// ```
1947 #[stable(feature = "wrapping", since = "1.7.0")]
1948 #[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
1949 #[must_use = "this returns the result of the operation, \
1950 without modifying the original"]
1951 #[inline]
1952 pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
1953 // Not using overflowing_shr as that's a wrapping shift
1954 if rhs < Self::BITS {
1955 // SAFETY: just checked the RHS is in-range
1956 Some(unsafe { self.unchecked_shr(rhs) })
1957 } else {
1958 None
1959 }
1960 }
1961
1962 /// Strict shift right. Computes `self >> rhs`, panicking if `rhs` is
1963 /// larger than or equal to the number of bits in `self`.
1964 ///
1965 /// # Panics
1966 ///
1967 /// ## Overflow behavior
1968 ///
1969 /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
1970 ///
1971 /// # Examples
1972 ///
1973 /// ```
1974 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".strict_shr(4), 0x1);")]
1975 /// ```
1976 ///
1977 /// The following panics because of overflow:
1978 ///
1979 /// ```should_panic
1980 #[doc = concat!("let _ = 0x10", stringify!($SelfT), ".strict_shr(129);")]
1981 /// ```
1982 #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
1983 #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
1984 #[must_use = "this returns the result of the operation, \
1985 without modifying the original"]
1986 #[inline]
1987 #[track_caller]
1988 pub const fn strict_shr(self, rhs: u32) -> Self {
1989 let (a, b) = self.overflowing_shr(rhs);
1990 if b { overflow_panic::shr() } else { a }
1991 }
1992
1993 /// Unchecked shift right. Computes `self >> rhs`, assuming that
1994 /// `rhs` is less than the number of bits in `self`.
1995 ///
1996 /// # Safety
1997 ///
1998 /// This results in undefined behavior if `rhs` is larger than
1999 /// or equal to the number of bits in `self`,
2000 /// i.e. when [`checked_shr`] would return `None`.
2001 ///
2002 #[doc = concat!("[`checked_shr`]: ", stringify!($SelfT), "::checked_shr")]
2003 #[stable(feature = "unchecked_shifts", since = "1.93.0")]
2004 #[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
2005 #[must_use = "this returns the result of the operation, \
2006 without modifying the original"]
2007 #[inline(always)]
2008 #[track_caller]
2009 pub const unsafe fn unchecked_shr(self, rhs: u32) -> Self {
2010 assert_unsafe_precondition!(
2011 check_language_ub,
2012 concat!(stringify!($SelfT), "::unchecked_shr cannot overflow"),
2013 (
2014 rhs: u32 = rhs,
2015 ) => rhs < <$ActualT>::BITS,
2016 );
2017
2018 // SAFETY: this is guaranteed to be safe by the caller.
2019 unsafe {
2020 intrinsics::unchecked_shr(self, rhs)
2021 }
2022 }
2023
2024 /// Unbounded shift right. Computes `self >> rhs`, without bounding the value of `rhs`.
2025 ///
2026 /// If `rhs` is larger or equal to the number of bits in `self`,
2027 /// the entire value is shifted out, and `0` is returned.
2028 ///
2029 /// # Examples
2030 ///
2031 /// ```
2032 #[doc = concat!("assert_eq!(0x10_", stringify!($SelfT), ".unbounded_shr(4), 0x1);")]
2033 #[doc = concat!("assert_eq!(0x10_", stringify!($SelfT), ".unbounded_shr(129), 0);")]
2034 #[doc = concat!("assert_eq!(0b1010_", stringify!($SelfT), ".unbounded_shr(0), 0b1010);")]
2035 #[doc = concat!("assert_eq!(0b1010_", stringify!($SelfT), ".unbounded_shr(1), 0b101);")]
2036 #[doc = concat!("assert_eq!(0b1010_", stringify!($SelfT), ".unbounded_shr(2), 0b10);")]
2037 #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".unbounded_shr(", stringify!($BITS), "), 0);")]
2038 #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".unbounded_shr(1).unbounded_shr(", stringify!($BITS_MINUS_ONE), "), 0);")]
2039 ///
2040 #[doc = concat!("let start = ", stringify!($SelfT), "::rotate_right(13, 4);")]
2041 /// let mut running = start;
2042 /// for i in 0..160 {
2043 /// // The unbounded shift right by i is the same as `>> 1` i times
2044 /// assert_eq!(running, start.unbounded_shr(i));
2045 /// // Which is not always the case for a wrapping shift
2046 #[doc = concat!(" assert_eq!(running == start.wrapping_shr(i), i < ", stringify!($BITS), ");")]
2047 ///
2048 /// running >>= 1;
2049 /// }
2050 /// ```
2051 #[stable(feature = "unbounded_shifts", since = "1.87.0")]
2052 #[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
2053 #[must_use = "this returns the result of the operation, \
2054 without modifying the original"]
2055 #[inline]
2056 pub const fn unbounded_shr(self, rhs: u32) -> $SelfT{
2057 if rhs < Self::BITS {
2058 // SAFETY:
2059 // rhs is just checked to be in-range above
2060 unsafe { self.unchecked_shr(rhs) }
2061 } else {
2062 0
2063 }
2064 }
2065
2066 /// Exact shift right. Computes `self >> rhs` as long as it can be reversed losslessly.
2067 ///
2068 /// Returns `None` if any non-zero bits would be shifted out or if `rhs` >=
2069 #[doc = concat!("`", stringify!($SelfT), "::BITS`.")]
2070 /// Otherwise, returns `Some(self >> rhs)`.
2071 ///
2072 /// # Examples
2073 ///
2074 /// ```
2075 /// #![feature(exact_bitshifts)]
2076 ///
2077 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".shr_exact(4), Some(0x1));")]
2078 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".shr_exact(5), None);")]
2079 /// ```
2080 #[unstable(feature = "exact_bitshifts", issue = "144336")]
2081 #[must_use = "this returns the result of the operation, \
2082 without modifying the original"]
2083 #[inline]
2084 pub const fn shr_exact(self, rhs: u32) -> Option<$SelfT> {
2085 if rhs <= self.trailing_zeros() && rhs < <$SelfT>::BITS {
2086 // SAFETY: rhs is checked above
2087 Some(unsafe { self.unchecked_shr(rhs) })
2088 } else {
2089 None
2090 }
2091 }
2092
2093 /// Unchecked exact shift right. Computes `self >> rhs`, assuming the operation can be
2094 /// losslessly reversed and `rhs` cannot be larger than
2095 #[doc = concat!("`", stringify!($SelfT), "::BITS`.")]
2096 ///
2097 /// # Safety
2098 ///
2099 /// This results in undefined behavior when `rhs > self.trailing_zeros() || rhs >=
2100 #[doc = concat!(stringify!($SelfT), "::BITS`")]
2101 /// i.e. when
2102 #[doc = concat!("[`", stringify!($SelfT), "::shr_exact`]")]
2103 /// would return `None`.
2104 #[unstable(feature = "exact_bitshifts", issue = "144336")]
2105 #[must_use = "this returns the result of the operation, \
2106 without modifying the original"]
2107 #[inline]
2108 pub const unsafe fn unchecked_shr_exact(self, rhs: u32) -> $SelfT {
2109 assert_unsafe_precondition!(
2110 check_library_ub,
2111 concat!(stringify!($SelfT), "::unchecked_shr_exact cannot shift out non-zero bits"),
2112 (
2113 zeros: u32 = self.trailing_zeros(),
2114 bits: u32 = <$SelfT>::BITS,
2115 rhs: u32 = rhs,
2116 ) => rhs <= zeros && rhs < bits,
2117 );
2118
2119 // SAFETY: this is guaranteed to be safe by the caller
2120 unsafe { self.unchecked_shr(rhs) }
2121 }
2122
2123 /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
2124 /// overflow occurred.
2125 ///
2126 /// # Examples
2127 ///
2128 /// ```
2129 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_pow(5), Some(32));")]
2130 #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".checked_pow(0), Some(1));")]
2131 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_pow(2), None);")]
2132 /// ```
2133 #[stable(feature = "no_panic_pow", since = "1.34.0")]
2134 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2135 #[must_use = "this returns the result of the operation, \
2136 without modifying the original"]
2137 #[inline]
2138 pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
2139 if exp == 0 {
2140 return Some(1);
2141 }
2142 let mut base = self;
2143 let mut acc: Self = 1;
2144
2145 loop {
2146 if (exp & 1) == 1 {
2147 acc = try_opt!(acc.checked_mul(base));
2148 // since exp!=0, finally the exp must be 1.
2149 if exp == 1 {
2150 return Some(acc);
2151 }
2152 }
2153 exp /= 2;
2154 base = try_opt!(base.checked_mul(base));
2155 }
2156 }
2157
2158 /// Strict exponentiation. Computes `self.pow(exp)`, panicking if
2159 /// overflow occurred.
2160 ///
2161 /// # Panics
2162 ///
2163 /// ## Overflow behavior
2164 ///
2165 /// This function will always panic on overflow, regardless of whether overflow checks are enabled.
2166 ///
2167 /// # Examples
2168 ///
2169 /// ```
2170 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".strict_pow(5), 32);")]
2171 #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".strict_pow(0), 1);")]
2172 /// ```
2173 ///
2174 /// The following panics because of overflow:
2175 ///
2176 /// ```should_panic
2177 #[doc = concat!("let _ = ", stringify!($SelfT), "::MAX.strict_pow(2);")]
2178 /// ```
2179 #[stable(feature = "strict_overflow_ops", since = "1.91.0")]
2180 #[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
2181 #[must_use = "this returns the result of the operation, \
2182 without modifying the original"]
2183 #[inline]
2184 #[track_caller]
2185 pub const fn strict_pow(self, mut exp: u32) -> Self {
2186 if exp == 0 {
2187 return 1;
2188 }
2189 let mut base = self;
2190 let mut acc: Self = 1;
2191
2192 loop {
2193 if (exp & 1) == 1 {
2194 acc = acc.strict_mul(base);
2195 // since exp!=0, finally the exp must be 1.
2196 if exp == 1 {
2197 return acc;
2198 }
2199 }
2200 exp /= 2;
2201 base = base.strict_mul(base);
2202 }
2203 }
2204
2205 /// Saturating integer addition. Computes `self + rhs`, saturating at
2206 /// the numeric bounds instead of overflowing.
2207 ///
2208 /// # Examples
2209 ///
2210 /// ```
2211 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_add(1), 101);")]
2212 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_add(127), ", stringify!($SelfT), "::MAX);")]
2213 /// ```
2214 #[stable(feature = "rust1", since = "1.0.0")]
2215 #[must_use = "this returns the result of the operation, \
2216 without modifying the original"]
2217 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
2218 #[inline(always)]
2219 pub const fn saturating_add(self, rhs: Self) -> Self {
2220 intrinsics::saturating_add(self, rhs)
2221 }
2222
2223 /// Saturating addition with a signed integer. Computes `self + rhs`,
2224 /// saturating at the numeric bounds instead of overflowing.
2225 ///
2226 /// # Examples
2227 ///
2228 /// ```
2229 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_signed(2), 3);")]
2230 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_add_signed(-2), 0);")]
2231 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).saturating_add_signed(4), ", stringify!($SelfT), "::MAX);")]
2232 /// ```
2233 #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
2234 #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
2235 #[must_use = "this returns the result of the operation, \
2236 without modifying the original"]
2237 #[inline]
2238 pub const fn saturating_add_signed(self, rhs: $SignedT) -> Self {
2239 let (res, overflow) = self.overflowing_add(rhs as Self);
2240 if overflow == (rhs < 0) {
2241 res
2242 } else if overflow {
2243 Self::MAX
2244 } else {
2245 0
2246 }
2247 }
2248
2249 /// Saturating integer subtraction. Computes `self - rhs`, saturating
2250 /// at the numeric bounds instead of overflowing.
2251 ///
2252 /// # Examples
2253 ///
2254 /// ```
2255 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".saturating_sub(27), 73);")]
2256 #[doc = concat!("assert_eq!(13", stringify!($SelfT), ".saturating_sub(127), 0);")]
2257 /// ```
2258 #[stable(feature = "rust1", since = "1.0.0")]
2259 #[must_use = "this returns the result of the operation, \
2260 without modifying the original"]
2261 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
2262 #[inline(always)]
2263 pub const fn saturating_sub(self, rhs: Self) -> Self {
2264 intrinsics::saturating_sub(self, rhs)
2265 }
2266
2267 /// Saturating integer subtraction. Computes `self` - `rhs`, saturating at
2268 /// the numeric bounds instead of overflowing.
2269 ///
2270 /// # Examples
2271 ///
2272 /// ```
2273 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_sub_signed(2), 0);")]
2274 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".saturating_sub_signed(-2), 3);")]
2275 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).saturating_sub_signed(-4), ", stringify!($SelfT), "::MAX);")]
2276 /// ```
2277 #[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
2278 #[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
2279 #[must_use = "this returns the result of the operation, \
2280 without modifying the original"]
2281 #[inline]
2282 pub const fn saturating_sub_signed(self, rhs: $SignedT) -> Self {
2283 let (res, overflow) = self.overflowing_sub_signed(rhs);
2284
2285 if !overflow {
2286 res
2287 } else if rhs < 0 {
2288 Self::MAX
2289 } else {
2290 0
2291 }
2292 }
2293
2294 /// Saturating integer multiplication. Computes `self * rhs`,
2295 /// saturating at the numeric bounds instead of overflowing.
2296 ///
2297 /// # Examples
2298 ///
2299 /// ```
2300 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".saturating_mul(10), 20);")]
2301 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX).saturating_mul(10), ", stringify!($SelfT),"::MAX);")]
2302 /// ```
2303 #[stable(feature = "wrapping", since = "1.7.0")]
2304 #[rustc_const_stable(feature = "const_saturating_int_methods", since = "1.47.0")]
2305 #[must_use = "this returns the result of the operation, \
2306 without modifying the original"]
2307 #[inline]
2308 pub const fn saturating_mul(self, rhs: Self) -> Self {
2309 match self.checked_mul(rhs) {
2310 Some(x) => x,
2311 None => Self::MAX,
2312 }
2313 }
2314
2315 /// Saturating integer division. Computes `self / rhs`, saturating at the
2316 /// numeric bounds instead of overflowing.
2317 ///
2318 /// # Panics
2319 ///
2320 /// This function will panic if `rhs` is zero.
2321 ///
2322 /// # Examples
2323 ///
2324 /// ```
2325 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".saturating_div(2), 2);")]
2326 ///
2327 /// ```
2328 #[stable(feature = "saturating_div", since = "1.58.0")]
2329 #[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
2330 #[must_use = "this returns the result of the operation, \
2331 without modifying the original"]
2332 #[inline]
2333 #[track_caller]
2334 pub const fn saturating_div(self, rhs: Self) -> Self {
2335 // on unsigned types, there is no overflow in integer division
2336 self.wrapping_div(rhs)
2337 }
2338
2339 /// Saturating integer exponentiation. Computes `self.pow(exp)`,
2340 /// saturating at the numeric bounds instead of overflowing.
2341 ///
2342 /// # Examples
2343 ///
2344 /// ```
2345 #[doc = concat!("assert_eq!(4", stringify!($SelfT), ".saturating_pow(3), 64);")]
2346 #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".saturating_pow(0), 1);")]
2347 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.saturating_pow(2), ", stringify!($SelfT), "::MAX);")]
2348 /// ```
2349 #[stable(feature = "no_panic_pow", since = "1.34.0")]
2350 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2351 #[must_use = "this returns the result of the operation, \
2352 without modifying the original"]
2353 #[inline]
2354 pub const fn saturating_pow(self, exp: u32) -> Self {
2355 match self.checked_pow(exp) {
2356 Some(x) => x,
2357 None => Self::MAX,
2358 }
2359 }
2360
2361 /// Wrapping (modular) addition. Computes `self + rhs`,
2362 /// wrapping around at the boundary of the type.
2363 ///
2364 /// # Examples
2365 ///
2366 /// ```
2367 #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(55), 255);")]
2368 #[doc = concat!("assert_eq!(200", stringify!($SelfT), ".wrapping_add(", stringify!($SelfT), "::MAX), 199);")]
2369 /// ```
2370 #[stable(feature = "rust1", since = "1.0.0")]
2371 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2372 #[must_use = "this returns the result of the operation, \
2373 without modifying the original"]
2374 #[inline(always)]
2375 pub const fn wrapping_add(self, rhs: Self) -> Self {
2376 intrinsics::wrapping_add(self, rhs)
2377 }
2378
2379 /// Wrapping (modular) addition with a signed integer. Computes
2380 /// `self + rhs`, wrapping around at the boundary of the type.
2381 ///
2382 /// # Examples
2383 ///
2384 /// ```
2385 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(2), 3);")]
2386 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_add_signed(-2), ", stringify!($SelfT), "::MAX);")]
2387 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).wrapping_add_signed(4), 1);")]
2388 /// ```
2389 #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
2390 #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
2391 #[must_use = "this returns the result of the operation, \
2392 without modifying the original"]
2393 #[inline]
2394 pub const fn wrapping_add_signed(self, rhs: $SignedT) -> Self {
2395 self.wrapping_add(rhs as Self)
2396 }
2397
2398 /// Wrapping (modular) subtraction. Computes `self - rhs`,
2399 /// wrapping around at the boundary of the type.
2400 ///
2401 /// # Examples
2402 ///
2403 /// ```
2404 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(100), 0);")]
2405 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_sub(", stringify!($SelfT), "::MAX), 101);")]
2406 /// ```
2407 #[stable(feature = "rust1", since = "1.0.0")]
2408 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2409 #[must_use = "this returns the result of the operation, \
2410 without modifying the original"]
2411 #[inline(always)]
2412 pub const fn wrapping_sub(self, rhs: Self) -> Self {
2413 intrinsics::wrapping_sub(self, rhs)
2414 }
2415
2416 /// Wrapping (modular) subtraction with a signed integer. Computes
2417 /// `self - rhs`, wrapping around at the boundary of the type.
2418 ///
2419 /// # Examples
2420 ///
2421 /// ```
2422 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_sub_signed(2), ", stringify!($SelfT), "::MAX);")]
2423 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".wrapping_sub_signed(-2), 3);")]
2424 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).wrapping_sub_signed(-4), 1);")]
2425 /// ```
2426 #[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
2427 #[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
2428 #[must_use = "this returns the result of the operation, \
2429 without modifying the original"]
2430 #[inline]
2431 pub const fn wrapping_sub_signed(self, rhs: $SignedT) -> Self {
2432 self.wrapping_sub(rhs as Self)
2433 }
2434
2435 /// Wrapping (modular) multiplication. Computes `self *
2436 /// rhs`, wrapping around at the boundary of the type.
2437 ///
2438 /// # Examples
2439 ///
2440 /// Please note that this example is shared among integer types, which is why `u8` is used.
2441 ///
2442 /// ```
2443 /// assert_eq!(10u8.wrapping_mul(12), 120);
2444 /// assert_eq!(25u8.wrapping_mul(12), 44);
2445 /// ```
2446 #[stable(feature = "rust1", since = "1.0.0")]
2447 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2448 #[must_use = "this returns the result of the operation, \
2449 without modifying the original"]
2450 #[inline(always)]
2451 pub const fn wrapping_mul(self, rhs: Self) -> Self {
2452 intrinsics::wrapping_mul(self, rhs)
2453 }
2454
2455 /// Wrapping (modular) division. Computes `self / rhs`.
2456 ///
2457 /// Wrapped division on unsigned types is just normal division. There's
2458 /// no way wrapping could ever happen. This function exists so that all
2459 /// operations are accounted for in the wrapping operations.
2460 ///
2461 /// # Panics
2462 ///
2463 /// This function will panic if `rhs` is zero.
2464 ///
2465 /// # Examples
2466 ///
2467 /// ```
2468 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div(10), 10);")]
2469 /// ```
2470 #[stable(feature = "num_wrapping", since = "1.2.0")]
2471 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
2472 #[must_use = "this returns the result of the operation, \
2473 without modifying the original"]
2474 #[inline(always)]
2475 #[track_caller]
2476 pub const fn wrapping_div(self, rhs: Self) -> Self {
2477 self / rhs
2478 }
2479
2480 /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
2481 ///
2482 /// Wrapped division on unsigned types is just normal division. There's
2483 /// no way wrapping could ever happen. This function exists so that all
2484 /// operations are accounted for in the wrapping operations. Since, for
2485 /// the positive integers, all common definitions of division are equal,
2486 /// this is exactly equal to `self.wrapping_div(rhs)`.
2487 ///
2488 /// # Panics
2489 ///
2490 /// This function will panic if `rhs` is zero.
2491 ///
2492 /// # Examples
2493 ///
2494 /// ```
2495 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_div_euclid(10), 10);")]
2496 /// ```
2497 #[stable(feature = "euclidean_division", since = "1.38.0")]
2498 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2499 #[must_use = "this returns the result of the operation, \
2500 without modifying the original"]
2501 #[inline(always)]
2502 #[track_caller]
2503 pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
2504 self / rhs
2505 }
2506
2507 /// Wrapping (modular) remainder. Computes `self % rhs`.
2508 ///
2509 /// Wrapped remainder calculation on unsigned types is just the regular
2510 /// remainder calculation. There's no way wrapping could ever happen.
2511 /// This function exists so that all operations are accounted for in the
2512 /// wrapping operations.
2513 ///
2514 /// # Panics
2515 ///
2516 /// This function will panic if `rhs` is zero.
2517 ///
2518 /// # Examples
2519 ///
2520 /// ```
2521 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem(10), 0);")]
2522 /// ```
2523 #[stable(feature = "num_wrapping", since = "1.2.0")]
2524 #[rustc_const_stable(feature = "const_wrapping_int_methods", since = "1.52.0")]
2525 #[must_use = "this returns the result of the operation, \
2526 without modifying the original"]
2527 #[inline(always)]
2528 #[track_caller]
2529 pub const fn wrapping_rem(self, rhs: Self) -> Self {
2530 self % rhs
2531 }
2532
2533 /// Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
2534 ///
2535 /// Wrapped modulo calculation on unsigned types is just the regular
2536 /// remainder calculation. There's no way wrapping could ever happen.
2537 /// This function exists so that all operations are accounted for in the
2538 /// wrapping operations. Since, for the positive integers, all common
2539 /// definitions of division are equal, this is exactly equal to
2540 /// `self.wrapping_rem(rhs)`.
2541 ///
2542 /// # Panics
2543 ///
2544 /// This function will panic if `rhs` is zero.
2545 ///
2546 /// # Examples
2547 ///
2548 /// ```
2549 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".wrapping_rem_euclid(10), 0);")]
2550 /// ```
2551 #[stable(feature = "euclidean_division", since = "1.38.0")]
2552 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
2553 #[must_use = "this returns the result of the operation, \
2554 without modifying the original"]
2555 #[inline(always)]
2556 #[track_caller]
2557 pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
2558 self % rhs
2559 }
2560
2561 /// Wrapping (modular) negation. Computes `-self`,
2562 /// wrapping around at the boundary of the type.
2563 ///
2564 /// Since unsigned types do not have negative equivalents
2565 /// all applications of this function will wrap (except for `-0`).
2566 /// For values smaller than the corresponding signed type's maximum
2567 /// the result is the same as casting the corresponding signed value.
2568 /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
2569 /// `MAX` is the corresponding signed type's maximum.
2570 ///
2571 /// # Examples
2572 ///
2573 /// ```
2574 #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".wrapping_neg(), 0);")]
2575 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_neg(), 1);")]
2576 #[doc = concat!("assert_eq!(13_", stringify!($SelfT), ".wrapping_neg(), (!13) + 1);")]
2577 #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".wrapping_neg(), !(42 - 1));")]
2578 /// ```
2579 #[stable(feature = "num_wrapping", since = "1.2.0")]
2580 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2581 #[must_use = "this returns the result of the operation, \
2582 without modifying the original"]
2583 #[inline(always)]
2584 pub const fn wrapping_neg(self) -> Self {
2585 (0 as $SelfT).wrapping_sub(self)
2586 }
2587
2588 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
2589 /// where `mask` removes any high-order bits of `rhs` that
2590 /// would cause the shift to exceed the bitwidth of the type.
2591 ///
2592 /// Beware that, unlike most other `wrapping_*` methods on integers, this
2593 /// does *not* give the same result as doing the shift in infinite precision
2594 /// then truncating as needed. The behaviour matches what shift instructions
2595 /// do on many processors, and is what the `<<` operator does when overflow
2596 /// checks are disabled, but numerically it's weird. Consider, instead,
2597 /// using [`Self::unbounded_shl`] which has nicer behaviour.
2598 ///
2599 /// Note that this is *not* the same as a rotate-left; the
2600 /// RHS of a wrapping shift-left is restricted to the range
2601 /// of the type, rather than the bits shifted out of the LHS
2602 /// being returned to the other end. The primitive integer
2603 /// types all implement a [`rotate_left`](Self::rotate_left) function,
2604 /// which may be what you want instead.
2605 ///
2606 /// # Examples
2607 ///
2608 /// ```
2609 #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".wrapping_shl(7), 128);")]
2610 #[doc = concat!("assert_eq!(0b101_", stringify!($SelfT), ".wrapping_shl(0), 0b101);")]
2611 #[doc = concat!("assert_eq!(0b101_", stringify!($SelfT), ".wrapping_shl(1), 0b1010);")]
2612 #[doc = concat!("assert_eq!(0b101_", stringify!($SelfT), ".wrapping_shl(2), 0b10100);")]
2613 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_shl(2), ", stringify!($SelfT), "::MAX - 3);")]
2614 #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".wrapping_shl(", stringify!($BITS), "), 42);")]
2615 #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".wrapping_shl(1).wrapping_shl(", stringify!($BITS_MINUS_ONE), "), 0);")]
2616 #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".wrapping_shl(128), 1);")]
2617 #[doc = concat!("assert_eq!(5_", stringify!($SelfT), ".wrapping_shl(1025), 10);")]
2618 /// ```
2619 #[stable(feature = "num_wrapping", since = "1.2.0")]
2620 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2621 #[must_use = "this returns the result of the operation, \
2622 without modifying the original"]
2623 #[inline(always)]
2624 pub const fn wrapping_shl(self, rhs: u32) -> Self {
2625 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
2626 // out of bounds
2627 unsafe {
2628 self.unchecked_shl(rhs & (Self::BITS - 1))
2629 }
2630 }
2631
2632 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
2633 /// where `mask` removes any high-order bits of `rhs` that
2634 /// would cause the shift to exceed the bitwidth of the type.
2635 ///
2636 /// Beware that, unlike most other `wrapping_*` methods on integers, this
2637 /// does *not* give the same result as doing the shift in infinite precision
2638 /// then truncating as needed. The behaviour matches what shift instructions
2639 /// do on many processors, and is what the `>>` operator does when overflow
2640 /// checks are disabled, but numerically it's weird. Consider, instead,
2641 /// using [`Self::unbounded_shr`] which has nicer behaviour.
2642 ///
2643 /// Note that this is *not* the same as a rotate-right; the
2644 /// RHS of a wrapping shift-right is restricted to the range
2645 /// of the type, rather than the bits shifted out of the LHS
2646 /// being returned to the other end. The primitive integer
2647 /// types all implement a [`rotate_right`](Self::rotate_right) function,
2648 /// which may be what you want instead.
2649 ///
2650 /// # Examples
2651 ///
2652 /// ```
2653 #[doc = concat!("assert_eq!(128_", stringify!($SelfT), ".wrapping_shr(7), 1);")]
2654 #[doc = concat!("assert_eq!(0b1010_", stringify!($SelfT), ".wrapping_shr(0), 0b1010);")]
2655 #[doc = concat!("assert_eq!(0b1010_", stringify!($SelfT), ".wrapping_shr(1), 0b101);")]
2656 #[doc = concat!("assert_eq!(0b1010_", stringify!($SelfT), ".wrapping_shr(2), 0b10);")]
2657 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_shr(1), ", stringify!($SignedT), "::MAX.cast_unsigned());")]
2658 #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".wrapping_shr(", stringify!($BITS), "), 42);")]
2659 #[doc = concat!("assert_eq!(42_", stringify!($SelfT), ".wrapping_shr(1).wrapping_shr(", stringify!($BITS_MINUS_ONE), "), 0);")]
2660 #[doc = concat!("assert_eq!(128_", stringify!($SelfT), ".wrapping_shr(128), 128);")]
2661 #[doc = concat!("assert_eq!(10_", stringify!($SelfT), ".wrapping_shr(1025), 5);")]
2662 /// ```
2663 #[stable(feature = "num_wrapping", since = "1.2.0")]
2664 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2665 #[must_use = "this returns the result of the operation, \
2666 without modifying the original"]
2667 #[inline(always)]
2668 pub const fn wrapping_shr(self, rhs: u32) -> Self {
2669 // SAFETY: the masking by the bitsize of the type ensures that we do not shift
2670 // out of bounds
2671 unsafe {
2672 self.unchecked_shr(rhs & (Self::BITS - 1))
2673 }
2674 }
2675
2676 /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
2677 /// wrapping around at the boundary of the type.
2678 ///
2679 /// # Examples
2680 ///
2681 /// ```
2682 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_pow(5), 243);")]
2683 /// assert_eq!(3u8.wrapping_pow(6), 217);
2684 #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".wrapping_pow(0), 1);")]
2685 /// ```
2686 #[stable(feature = "no_panic_pow", since = "1.34.0")]
2687 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
2688 #[must_use = "this returns the result of the operation, \
2689 without modifying the original"]
2690 #[inline]
2691 pub const fn wrapping_pow(self, mut exp: u32) -> Self {
2692 if exp == 0 {
2693 return 1;
2694 }
2695 let mut base = self;
2696 let mut acc: Self = 1;
2697
2698 if intrinsics::is_val_statically_known(exp) {
2699 while exp > 1 {
2700 if (exp & 1) == 1 {
2701 acc = acc.wrapping_mul(base);
2702 }
2703 exp /= 2;
2704 base = base.wrapping_mul(base);
2705 }
2706
2707 // since exp!=0, finally the exp must be 1.
2708 // Deal with the final bit of the exponent separately, since
2709 // squaring the base afterwards is not necessary.
2710 acc.wrapping_mul(base)
2711 } else {
2712 // This is faster than the above when the exponent is not known
2713 // at compile time. We can't use the same code for the constant
2714 // exponent case because LLVM is currently unable to unroll
2715 // this loop.
2716 loop {
2717 if (exp & 1) == 1 {
2718 acc = acc.wrapping_mul(base);
2719 // since exp!=0, finally the exp must be 1.
2720 if exp == 1 {
2721 return acc;
2722 }
2723 }
2724 exp /= 2;
2725 base = base.wrapping_mul(base);
2726 }
2727 }
2728 }
2729
2730 /// Calculates `self` + `rhs`.
2731 ///
2732 /// Returns a tuple of the addition along with a boolean indicating
2733 /// whether an arithmetic overflow would occur. If an overflow would
2734 /// have occurred then the wrapped value is returned.
2735 ///
2736 /// # Examples
2737 ///
2738 /// ```
2739 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_add(2), (7, false));")]
2740 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));")]
2741 /// ```
2742 #[stable(feature = "wrapping", since = "1.7.0")]
2743 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2744 #[must_use = "this returns the result of the operation, \
2745 without modifying the original"]
2746 #[inline(always)]
2747 pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
2748 let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT);
2749 (a as Self, b)
2750 }
2751
2752 /// Calculates `self` + `rhs` + `carry` and returns a tuple containing
2753 /// the sum and the output carry (in that order).
2754 ///
2755 /// Performs "ternary addition" of two integer operands and a carry-in
2756 /// bit, and returns an output integer and a carry-out bit. This allows
2757 /// chaining together multiple additions to create a wider addition, and
2758 /// can be useful for bignum addition.
2759 ///
2760 #[doc = concat!("This can be thought of as a ", stringify!($BITS), "-bit \"full adder\", in the electronics sense.")]
2761 ///
2762 /// If the input carry is false, this method is equivalent to
2763 /// [`overflowing_add`](Self::overflowing_add), and the output carry is
2764 /// equal to the overflow flag. Note that although carry and overflow
2765 /// flags are similar for unsigned integers, they are different for
2766 /// signed integers.
2767 ///
2768 /// # Examples
2769 ///
2770 /// ```
2771 #[doc = concat!("// 3 MAX (a = 3 × 2^", stringify!($BITS), " + 2^", stringify!($BITS), " - 1)")]
2772 #[doc = concat!("// + 5 7 (b = 5 × 2^", stringify!($BITS), " + 7)")]
2773 /// // ---------
2774 #[doc = concat!("// 9 6 (sum = 9 × 2^", stringify!($BITS), " + 6)")]
2775 ///
2776 #[doc = concat!("let (a1, a0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (3, ", stringify!($SelfT), "::MAX);")]
2777 #[doc = concat!("let (b1, b0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (5, 7);")]
2778 /// let carry0 = false;
2779 ///
2780 /// let (sum0, carry1) = a0.carrying_add(b0, carry0);
2781 /// assert_eq!(carry1, true);
2782 /// let (sum1, carry2) = a1.carrying_add(b1, carry1);
2783 /// assert_eq!(carry2, false);
2784 ///
2785 /// assert_eq!((sum1, sum0), (9, 6));
2786 /// ```
2787 #[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
2788 #[rustc_const_unstable(feature = "bigint_helper_methods", issue = "85532")]
2789 #[must_use = "this returns the result of the operation, \
2790 without modifying the original"]
2791 #[inline]
2792 pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
2793 // note: longer-term this should be done via an intrinsic, but this has been shown
2794 // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
2795 let (a, c1) = self.overflowing_add(rhs);
2796 let (b, c2) = a.overflowing_add(carry as $SelfT);
2797 // Ideally LLVM would know this is disjoint without us telling them,
2798 // but it doesn't <https://github.com/llvm/llvm-project/issues/118162>
2799 // SAFETY: Only one of `c1` and `c2` can be set.
2800 // For c1 to be set we need to have overflowed, but if we did then
2801 // `a` is at most `MAX-1`, which means that `c2` cannot possibly
2802 // overflow because it's adding at most `1` (since it came from `bool`)
2803 (b, unsafe { intrinsics::disjoint_bitor(c1, c2) })
2804 }
2805
2806 /// Calculates `self` + `rhs` with a signed `rhs`.
2807 ///
2808 /// Returns a tuple of the addition along with a boolean indicating
2809 /// whether an arithmetic overflow would occur. If an overflow would
2810 /// have occurred then the wrapped value is returned.
2811 ///
2812 /// # Examples
2813 ///
2814 /// ```
2815 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(2), (3, false));")]
2816 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_add_signed(-2), (", stringify!($SelfT), "::MAX, true));")]
2817 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_add_signed(4), (1, true));")]
2818 /// ```
2819 #[stable(feature = "mixed_integer_ops", since = "1.66.0")]
2820 #[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
2821 #[must_use = "this returns the result of the operation, \
2822 without modifying the original"]
2823 #[inline]
2824 pub const fn overflowing_add_signed(self, rhs: $SignedT) -> (Self, bool) {
2825 let (res, overflowed) = self.overflowing_add(rhs as Self);
2826 (res, overflowed ^ (rhs < 0))
2827 }
2828
2829 /// Calculates `self` - `rhs`.
2830 ///
2831 /// Returns a tuple of the subtraction along with a boolean indicating
2832 /// whether an arithmetic overflow would occur. If an overflow would
2833 /// have occurred then the wrapped value is returned.
2834 ///
2835 /// # Examples
2836 ///
2837 /// ```
2838 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_sub(2), (3, false));")]
2839 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_sub(1), (", stringify!($SelfT), "::MAX, true));")]
2840 /// ```
2841 #[stable(feature = "wrapping", since = "1.7.0")]
2842 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2843 #[must_use = "this returns the result of the operation, \
2844 without modifying the original"]
2845 #[inline(always)]
2846 pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
2847 let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT);
2848 (a as Self, b)
2849 }
2850
2851 /// Calculates `self` − `rhs` − `borrow` and returns a tuple
2852 /// containing the difference and the output borrow.
2853 ///
2854 /// Performs "ternary subtraction" by subtracting both an integer
2855 /// operand and a borrow-in bit from `self`, and returns an output
2856 /// integer and a borrow-out bit. This allows chaining together multiple
2857 /// subtractions to create a wider subtraction, and can be useful for
2858 /// bignum subtraction.
2859 ///
2860 /// # Examples
2861 ///
2862 /// ```
2863 #[doc = concat!("// 9 6 (a = 9 × 2^", stringify!($BITS), " + 6)")]
2864 #[doc = concat!("// - 5 7 (b = 5 × 2^", stringify!($BITS), " + 7)")]
2865 /// // ---------
2866 #[doc = concat!("// 3 MAX (diff = 3 × 2^", stringify!($BITS), " + 2^", stringify!($BITS), " - 1)")]
2867 ///
2868 #[doc = concat!("let (a1, a0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (9, 6);")]
2869 #[doc = concat!("let (b1, b0): (", stringify!($SelfT), ", ", stringify!($SelfT), ") = (5, 7);")]
2870 /// let borrow0 = false;
2871 ///
2872 /// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);
2873 /// assert_eq!(borrow1, true);
2874 /// let (diff1, borrow2) = a1.borrowing_sub(b1, borrow1);
2875 /// assert_eq!(borrow2, false);
2876 ///
2877 #[doc = concat!("assert_eq!((diff1, diff0), (3, ", stringify!($SelfT), "::MAX));")]
2878 /// ```
2879 #[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
2880 #[rustc_const_unstable(feature = "bigint_helper_methods", issue = "85532")]
2881 #[must_use = "this returns the result of the operation, \
2882 without modifying the original"]
2883 #[inline]
2884 pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
2885 // note: longer-term this should be done via an intrinsic, but this has been shown
2886 // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic
2887 let (a, c1) = self.overflowing_sub(rhs);
2888 let (b, c2) = a.overflowing_sub(borrow as $SelfT);
2889 // SAFETY: Only one of `c1` and `c2` can be set.
2890 // For c1 to be set we need to have underflowed, but if we did then
2891 // `a` is nonzero, which means that `c2` cannot possibly
2892 // underflow because it's subtracting at most `1` (since it came from `bool`)
2893 (b, unsafe { intrinsics::disjoint_bitor(c1, c2) })
2894 }
2895
2896 /// Calculates `self` - `rhs` with a signed `rhs`
2897 ///
2898 /// Returns a tuple of the subtraction along with a boolean indicating
2899 /// whether an arithmetic overflow would occur. If an overflow would
2900 /// have occurred then the wrapped value is returned.
2901 ///
2902 /// # Examples
2903 ///
2904 /// ```
2905 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_sub_signed(2), (", stringify!($SelfT), "::MAX, true));")]
2906 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".overflowing_sub_signed(-2), (3, false));")]
2907 #[doc = concat!("assert_eq!((", stringify!($SelfT), "::MAX - 2).overflowing_sub_signed(-4), (1, true));")]
2908 /// ```
2909 #[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
2910 #[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
2911 #[must_use = "this returns the result of the operation, \
2912 without modifying the original"]
2913 #[inline]
2914 pub const fn overflowing_sub_signed(self, rhs: $SignedT) -> (Self, bool) {
2915 let (res, overflow) = self.overflowing_sub(rhs as Self);
2916
2917 (res, overflow ^ (rhs < 0))
2918 }
2919
2920 /// Computes the absolute difference between `self` and `other`.
2921 ///
2922 /// # Examples
2923 ///
2924 /// ```
2925 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(80), 20", stringify!($SelfT), ");")]
2926 #[doc = concat!("assert_eq!(100", stringify!($SelfT), ".abs_diff(110), 10", stringify!($SelfT), ");")]
2927 /// ```
2928 #[stable(feature = "int_abs_diff", since = "1.60.0")]
2929 #[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
2930 #[must_use = "this returns the result of the operation, \
2931 without modifying the original"]
2932 #[inline]
2933 pub const fn abs_diff(self, other: Self) -> Self {
2934 if size_of::<Self>() == 1 {
2935 // Trick LLVM into generating the psadbw instruction when SSE2
2936 // is available and this function is autovectorized for u8's.
2937 (self as i32).wrapping_sub(other as i32).unsigned_abs() as Self
2938 } else {
2939 if self < other {
2940 other - self
2941 } else {
2942 self - other
2943 }
2944 }
2945 }
2946
2947 /// Calculates the multiplication of `self` and `rhs`.
2948 ///
2949 /// Returns a tuple of the multiplication along with a boolean
2950 /// indicating whether an arithmetic overflow would occur. If an
2951 /// overflow would have occurred then the wrapped value is returned.
2952 ///
2953 /// If you want the *value* of the overflow, rather than just *whether*
2954 /// an overflow occurred, see [`Self::carrying_mul`].
2955 ///
2956 /// # Examples
2957 ///
2958 /// Please note that this example is shared among integer types, which is why `u32` is used.
2959 ///
2960 /// ```
2961 /// assert_eq!(5u32.overflowing_mul(2), (10, false));
2962 /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
2963 /// ```
2964 #[stable(feature = "wrapping", since = "1.7.0")]
2965 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
2966 #[must_use = "this returns the result of the operation, \
2967 without modifying the original"]
2968 #[inline(always)]
2969 pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
2970 let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT);
2971 (a as Self, b)
2972 }
2973
2974 /// Calculates the complete double-width product `self * rhs`.
2975 ///
2976 /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
2977 /// of the result as two separate values, in that order. As such,
2978 /// `a.widening_mul(b).0` produces the same result as `a.wrapping_mul(b)`.
2979 ///
2980 /// If you also need to add a value and carry to the wide result, then you want
2981 /// [`Self::carrying_mul_add`] instead.
2982 ///
2983 /// If you also need to add a carry to the wide result, then you want
2984 /// [`Self::carrying_mul`] instead.
2985 ///
2986 /// If you just want to know *whether* the multiplication overflowed, then you
2987 /// want [`Self::overflowing_mul`] instead.
2988 ///
2989 /// # Examples
2990 ///
2991 /// ```
2992 /// #![feature(bigint_helper_methods)]
2993 #[doc = concat!("assert_eq!(5_", stringify!($SelfT), ".widening_mul(7), (35, 0));")]
2994 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.widening_mul(", stringify!($SelfT), "::MAX), (1, ", stringify!($SelfT), "::MAX - 1));")]
2995 /// ```
2996 ///
2997 /// Compared to other `*_mul` methods:
2998 /// ```
2999 /// #![feature(bigint_helper_methods)]
3000 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::widening_mul(1 << ", stringify!($BITS_MINUS_ONE), ", 6), (0, 3));")]
3001 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::overflowing_mul(1 << ", stringify!($BITS_MINUS_ONE), ", 6), (0, true));")]
3002 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::wrapping_mul(1 << ", stringify!($BITS_MINUS_ONE), ", 6), 0);")]
3003 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::checked_mul(1 << ", stringify!($BITS_MINUS_ONE), ", 6), None);")]
3004 /// ```
3005 ///
3006 /// Please note that this example is shared among integer types, which is why `u32` is used.
3007 ///
3008 /// ```
3009 /// #![feature(bigint_helper_methods)]
3010 /// assert_eq!(5u32.widening_mul(2), (10, 0));
3011 /// assert_eq!(1_000_000_000u32.widening_mul(10), (1410065408, 2));
3012 /// ```
3013 #[unstable(feature = "bigint_helper_methods", issue = "85532")]
3014 #[rustc_const_unstable(feature = "bigint_helper_methods", issue = "85532")]
3015 #[must_use = "this returns the result of the operation, \
3016 without modifying the original"]
3017 #[inline]
3018 pub const fn widening_mul(self, rhs: Self) -> (Self, Self) {
3019 Self::carrying_mul_add(self, rhs, 0, 0)
3020 }
3021
3022 /// Calculates the "full multiplication" `self * rhs + carry`
3023 /// without the possibility to overflow.
3024 ///
3025 /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
3026 /// of the result as two separate values, in that order.
3027 ///
3028 /// Performs "long multiplication" which takes in an extra amount to add, and may return an
3029 /// additional amount of overflow. This allows for chaining together multiple
3030 /// multiplications to create "big integers" which represent larger values.
3031 ///
3032 /// If you also need to add a value, then use [`Self::carrying_mul_add`].
3033 ///
3034 /// # Examples
3035 ///
3036 /// Please note that this example is shared among integer types, which is why `u32` is used.
3037 ///
3038 /// ```
3039 /// assert_eq!(5u32.carrying_mul(2, 0), (10, 0));
3040 /// assert_eq!(5u32.carrying_mul(2, 10), (20, 0));
3041 /// assert_eq!(1_000_000_000u32.carrying_mul(10, 0), (1410065408, 2));
3042 /// assert_eq!(1_000_000_000u32.carrying_mul(10, 10), (1410065418, 2));
3043 #[doc = concat!("assert_eq!(",
3044 stringify!($SelfT), "::MAX.carrying_mul(", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX), ",
3045 "(0, ", stringify!($SelfT), "::MAX));"
3046 )]
3047 /// ```
3048 ///
3049 /// This is the core operation needed for scalar multiplication when
3050 /// implementing it for wider-than-native types.
3051 ///
3052 /// ```
3053 /// #![feature(bigint_helper_methods)]
3054 /// fn scalar_mul_eq(little_endian_digits: &mut Vec<u16>, multiplicand: u16) {
3055 /// let mut carry = 0;
3056 /// for d in little_endian_digits.iter_mut() {
3057 /// (*d, carry) = d.carrying_mul(multiplicand, carry);
3058 /// }
3059 /// if carry != 0 {
3060 /// little_endian_digits.push(carry);
3061 /// }
3062 /// }
3063 ///
3064 /// let mut v = vec![10, 20];
3065 /// scalar_mul_eq(&mut v, 3);
3066 /// assert_eq!(v, [30, 60]);
3067 ///
3068 /// assert_eq!(0x87654321_u64 * 0xFEED, 0x86D3D159E38D);
3069 /// let mut v = vec![0x4321, 0x8765];
3070 /// scalar_mul_eq(&mut v, 0xFEED);
3071 /// assert_eq!(v, [0xE38D, 0xD159, 0x86D3]);
3072 /// ```
3073 ///
3074 /// If `carry` is zero, this is similar to [`overflowing_mul`](Self::overflowing_mul),
3075 /// except that it gives the value of the overflow instead of just whether one happened:
3076 ///
3077 /// ```
3078 /// #![feature(bigint_helper_methods)]
3079 /// let r = u8::carrying_mul(7, 13, 0);
3080 /// assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(7, 13));
3081 /// let r = u8::carrying_mul(13, 42, 0);
3082 /// assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(13, 42));
3083 /// ```
3084 ///
3085 /// The value of the first field in the returned tuple matches what you'd get
3086 /// by combining the [`wrapping_mul`](Self::wrapping_mul) and
3087 /// [`wrapping_add`](Self::wrapping_add) methods:
3088 ///
3089 /// ```
3090 /// #![feature(bigint_helper_methods)]
3091 /// assert_eq!(
3092 /// 789_u16.carrying_mul(456, 123).0,
3093 /// 789_u16.wrapping_mul(456).wrapping_add(123),
3094 /// );
3095 /// ```
3096 #[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
3097 #[rustc_const_unstable(feature = "bigint_helper_methods", issue = "85532")]
3098 #[must_use = "this returns the result of the operation, \
3099 without modifying the original"]
3100 #[inline]
3101 pub const fn carrying_mul(self, rhs: Self, carry: Self) -> (Self, Self) {
3102 Self::carrying_mul_add(self, rhs, carry, 0)
3103 }
3104
3105 /// Calculates the "full multiplication" `self * rhs + carry + add`.
3106 ///
3107 /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
3108 /// of the result as two separate values, in that order.
3109 ///
3110 /// This cannot overflow, as the double-width result has exactly enough
3111 /// space for the largest possible result. This is equivalent to how, in
3112 /// decimal, 9 × 9 + 9 + 9 = 81 + 18 = 99 = 9×10⁰ + 9×10¹ = 10² - 1.
3113 ///
3114 /// Performs "long multiplication" which takes in an extra amount to add, and may return an
3115 /// additional amount of overflow. This allows for chaining together multiple
3116 /// multiplications to create "big integers" which represent larger values.
3117 ///
3118 /// If you don't need the `add` part, then you can use [`Self::carrying_mul`] instead.
3119 ///
3120 /// # Examples
3121 ///
3122 /// Please note that this example is shared between integer types,
3123 /// which explains why `u32` is used here.
3124 ///
3125 /// ```
3126 /// assert_eq!(5u32.carrying_mul_add(2, 0, 0), (10, 0));
3127 /// assert_eq!(5u32.carrying_mul_add(2, 10, 10), (30, 0));
3128 /// assert_eq!(1_000_000_000u32.carrying_mul_add(10, 0, 0), (1410065408, 2));
3129 /// assert_eq!(1_000_000_000u32.carrying_mul_add(10, 10, 10), (1410065428, 2));
3130 #[doc = concat!("assert_eq!(",
3131 stringify!($SelfT), "::MAX.carrying_mul_add(", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX), ",
3132 "(", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX));"
3133 )]
3134 /// ```
3135 ///
3136 /// This is the core per-digit operation for "grade school" O(n²) multiplication.
3137 ///
3138 /// Please note that this example is shared between integer types,
3139 /// using `u8` for simplicity of the demonstration.
3140 ///
3141 /// ```
3142 /// fn quadratic_mul<const N: usize>(a: [u8; N], b: [u8; N]) -> [u8; N] {
3143 /// let mut out = [0; N];
3144 /// for j in 0..N {
3145 /// let mut carry = 0;
3146 /// for i in 0..(N - j) {
3147 /// (out[j + i], carry) = u8::carrying_mul_add(a[i], b[j], out[j + i], carry);
3148 /// }
3149 /// }
3150 /// out
3151 /// }
3152 ///
3153 /// // -1 * -1 == 1
3154 /// assert_eq!(quadratic_mul([0xFF; 3], [0xFF; 3]), [1, 0, 0]);
3155 ///
3156 /// assert_eq!(u32::wrapping_mul(0x9e3779b9, 0x7f4a7c15), 0xcffc982d);
3157 /// assert_eq!(
3158 /// quadratic_mul(u32::to_le_bytes(0x9e3779b9), u32::to_le_bytes(0x7f4a7c15)),
3159 /// u32::to_le_bytes(0xcffc982d)
3160 /// );
3161 /// ```
3162 #[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
3163 #[rustc_const_unstable(feature = "bigint_helper_methods", issue = "85532")]
3164 #[must_use = "this returns the result of the operation, \
3165 without modifying the original"]
3166 #[inline]
3167 pub const fn carrying_mul_add(self, rhs: Self, carry: Self, add: Self) -> (Self, Self) {
3168 intrinsics::carrying_mul_add(self, rhs, carry, add)
3169 }
3170
3171 /// Calculates the divisor when `self` is divided by `rhs`.
3172 ///
3173 /// Returns a tuple of the divisor along with a boolean indicating
3174 /// whether an arithmetic overflow would occur. Note that for unsigned
3175 /// integers overflow never occurs, so the second value is always
3176 /// `false`.
3177 ///
3178 /// # Panics
3179 ///
3180 /// This function will panic if `rhs` is zero.
3181 ///
3182 /// # Examples
3183 ///
3184 /// ```
3185 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div(2), (2, false));")]
3186 /// ```
3187 #[inline(always)]
3188 #[stable(feature = "wrapping", since = "1.7.0")]
3189 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
3190 #[must_use = "this returns the result of the operation, \
3191 without modifying the original"]
3192 #[track_caller]
3193 pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
3194 (self / rhs, false)
3195 }
3196
3197 /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
3198 ///
3199 /// Returns a tuple of the divisor along with a boolean indicating
3200 /// whether an arithmetic overflow would occur. Note that for unsigned
3201 /// integers overflow never occurs, so the second value is always
3202 /// `false`.
3203 /// Since, for the positive integers, all common
3204 /// definitions of division are equal, this
3205 /// is exactly equal to `self.overflowing_div(rhs)`.
3206 ///
3207 /// # Panics
3208 ///
3209 /// This function will panic if `rhs` is zero.
3210 ///
3211 /// # Examples
3212 ///
3213 /// ```
3214 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));")]
3215 /// ```
3216 #[inline(always)]
3217 #[stable(feature = "euclidean_division", since = "1.38.0")]
3218 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
3219 #[must_use = "this returns the result of the operation, \
3220 without modifying the original"]
3221 #[track_caller]
3222 pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
3223 (self / rhs, false)
3224 }
3225
3226 /// Calculates the remainder when `self` is divided by `rhs`.
3227 ///
3228 /// Returns a tuple of the remainder after dividing along with a boolean
3229 /// indicating whether an arithmetic overflow would occur. Note that for
3230 /// unsigned integers overflow never occurs, so the second value is
3231 /// always `false`.
3232 ///
3233 /// # Panics
3234 ///
3235 /// This function will panic if `rhs` is zero.
3236 ///
3237 /// # Examples
3238 ///
3239 /// ```
3240 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem(2), (1, false));")]
3241 /// ```
3242 #[inline(always)]
3243 #[stable(feature = "wrapping", since = "1.7.0")]
3244 #[rustc_const_stable(feature = "const_overflowing_int_methods", since = "1.52.0")]
3245 #[must_use = "this returns the result of the operation, \
3246 without modifying the original"]
3247 #[track_caller]
3248 pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
3249 (self % rhs, false)
3250 }
3251
3252 /// Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
3253 ///
3254 /// Returns a tuple of the modulo after dividing along with a boolean
3255 /// indicating whether an arithmetic overflow would occur. Note that for
3256 /// unsigned integers overflow never occurs, so the second value is
3257 /// always `false`.
3258 /// Since, for the positive integers, all common
3259 /// definitions of division are equal, this operation
3260 /// is exactly equal to `self.overflowing_rem(rhs)`.
3261 ///
3262 /// # Panics
3263 ///
3264 /// This function will panic if `rhs` is zero.
3265 ///
3266 /// # Examples
3267 ///
3268 /// ```
3269 #[doc = concat!("assert_eq!(5", stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));")]
3270 /// ```
3271 #[inline(always)]
3272 #[stable(feature = "euclidean_division", since = "1.38.0")]
3273 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
3274 #[must_use = "this returns the result of the operation, \
3275 without modifying the original"]
3276 #[track_caller]
3277 pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
3278 (self % rhs, false)
3279 }
3280
3281 /// Negates self in an overflowing fashion.
3282 ///
3283 /// Returns `!self + 1` using wrapping operations to return the value
3284 /// that represents the negation of this unsigned value. Note that for
3285 /// positive unsigned values overflow always occurs, but negating 0 does
3286 /// not overflow.
3287 ///
3288 /// # Examples
3289 ///
3290 /// ```
3291 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".overflowing_neg(), (0, false));")]
3292 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".overflowing_neg(), (-2i32 as ", stringify!($SelfT), ", true));")]
3293 /// ```
3294 #[inline(always)]
3295 #[stable(feature = "wrapping", since = "1.7.0")]
3296 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3297 #[must_use = "this returns the result of the operation, \
3298 without modifying the original"]
3299 pub const fn overflowing_neg(self) -> (Self, bool) {
3300 ((!self).wrapping_add(1), self != 0)
3301 }
3302
3303 /// Shifts self left by `rhs` bits.
3304 ///
3305 /// Returns a tuple of the shifted version of self along with a boolean
3306 /// indicating whether the shift value was larger than or equal to the
3307 /// number of bits. If the shift value is too large, then value is
3308 /// masked (N-1) where N is the number of bits, and this value is then
3309 /// used to perform the shift.
3310 ///
3311 /// # Examples
3312 ///
3313 /// ```
3314 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(4), (0x10, false));")]
3315 #[doc = concat!("assert_eq!(0x1", stringify!($SelfT), ".overflowing_shl(132), (0x10, true));")]
3316 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shl(", stringify!($BITS_MINUS_ONE), "), (0, false));")]
3317 /// ```
3318 #[stable(feature = "wrapping", since = "1.7.0")]
3319 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3320 #[must_use = "this returns the result of the operation, \
3321 without modifying the original"]
3322 #[inline(always)]
3323 pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
3324 (self.wrapping_shl(rhs), rhs >= Self::BITS)
3325 }
3326
3327 /// Shifts self right by `rhs` bits.
3328 ///
3329 /// Returns a tuple of the shifted version of self along with a boolean
3330 /// indicating whether the shift value was larger than or equal to the
3331 /// number of bits. If the shift value is too large, then value is
3332 /// masked (N-1) where N is the number of bits, and this value is then
3333 /// used to perform the shift.
3334 ///
3335 /// # Examples
3336 ///
3337 /// ```
3338 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(4), (0x1, false));")]
3339 #[doc = concat!("assert_eq!(0x10", stringify!($SelfT), ".overflowing_shr(132), (0x1, true));")]
3340 /// ```
3341 #[stable(feature = "wrapping", since = "1.7.0")]
3342 #[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
3343 #[must_use = "this returns the result of the operation, \
3344 without modifying the original"]
3345 #[inline(always)]
3346 pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
3347 (self.wrapping_shr(rhs), rhs >= Self::BITS)
3348 }
3349
3350 /// Raises self to the power of `exp`, using exponentiation by squaring.
3351 ///
3352 /// Returns a tuple of the exponentiation along with a bool indicating
3353 /// whether an overflow happened.
3354 ///
3355 /// # Examples
3356 ///
3357 /// ```
3358 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".overflowing_pow(5), (243, false));")]
3359 #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".overflowing_pow(0), (1, false));")]
3360 /// assert_eq!(3u8.overflowing_pow(6), (217, true));
3361 /// ```
3362 #[stable(feature = "no_panic_pow", since = "1.34.0")]
3363 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
3364 #[must_use = "this returns the result of the operation, \
3365 without modifying the original"]
3366 #[inline]
3367 pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
3368 if exp == 0{
3369 return (1,false);
3370 }
3371 let mut base = self;
3372 let mut acc: Self = 1;
3373 let mut overflown = false;
3374 // Scratch space for storing results of overflowing_mul.
3375 let mut r;
3376
3377 loop {
3378 if (exp & 1) == 1 {
3379 r = acc.overflowing_mul(base);
3380 // since exp!=0, finally the exp must be 1.
3381 if exp == 1 {
3382 r.1 |= overflown;
3383 return r;
3384 }
3385 acc = r.0;
3386 overflown |= r.1;
3387 }
3388 exp /= 2;
3389 r = base.overflowing_mul(base);
3390 base = r.0;
3391 overflown |= r.1;
3392 }
3393 }
3394
3395 /// Raises self to the power of `exp`, using exponentiation by squaring.
3396 ///
3397 /// # Examples
3398 ///
3399 /// ```
3400 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".pow(5), 32);")]
3401 #[doc = concat!("assert_eq!(0_", stringify!($SelfT), ".pow(0), 1);")]
3402 /// ```
3403 #[stable(feature = "rust1", since = "1.0.0")]
3404 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
3405 #[must_use = "this returns the result of the operation, \
3406 without modifying the original"]
3407 #[inline]
3408 #[rustc_inherit_overflow_checks]
3409 pub const fn pow(self, mut exp: u32) -> Self {
3410 if exp == 0 {
3411 return 1;
3412 }
3413 let mut base = self;
3414 let mut acc = 1;
3415
3416 if intrinsics::is_val_statically_known(exp) {
3417 while exp > 1 {
3418 if (exp & 1) == 1 {
3419 acc = acc * base;
3420 }
3421 exp /= 2;
3422 base = base * base;
3423 }
3424
3425 // since exp!=0, finally the exp must be 1.
3426 // Deal with the final bit of the exponent separately, since
3427 // squaring the base afterwards is not necessary and may cause a
3428 // needless overflow.
3429 acc * base
3430 } else {
3431 // This is faster than the above when the exponent is not known
3432 // at compile time. We can't use the same code for the constant
3433 // exponent case because LLVM is currently unable to unroll
3434 // this loop.
3435 loop {
3436 if (exp & 1) == 1 {
3437 acc = acc * base;
3438 // since exp!=0, finally the exp must be 1.
3439 if exp == 1 {
3440 return acc;
3441 }
3442 }
3443 exp /= 2;
3444 base = base * base;
3445 }
3446 }
3447 }
3448
3449 /// Returns the square root of the number, rounded down.
3450 ///
3451 /// # Examples
3452 ///
3453 /// ```
3454 #[doc = concat!("assert_eq!(10", stringify!($SelfT), ".isqrt(), 3);")]
3455 /// ```
3456 #[stable(feature = "isqrt", since = "1.84.0")]
3457 #[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
3458 #[must_use = "this returns the result of the operation, \
3459 without modifying the original"]
3460 #[inline]
3461 pub const fn isqrt(self) -> Self {
3462 let result = crate::num::int_sqrt::$ActualT(self as $ActualT) as $SelfT;
3463
3464 // Inform the optimizer what the range of outputs is. If testing
3465 // `core` crashes with no panic message and a `num::int_sqrt::u*`
3466 // test failed, it's because your edits caused these assertions or
3467 // the assertions in `fn isqrt` of `nonzero.rs` to become false.
3468 //
3469 // SAFETY: Integer square root is a monotonically nondecreasing
3470 // function, which means that increasing the input will never
3471 // cause the output to decrease. Thus, since the input for unsigned
3472 // integers is bounded by `[0, <$ActualT>::MAX]`, sqrt(n) will be
3473 // bounded by `[sqrt(0), sqrt(<$ActualT>::MAX)]`.
3474 unsafe {
3475 const MAX_RESULT: $SelfT = crate::num::int_sqrt::$ActualT(<$ActualT>::MAX) as $SelfT;
3476 crate::hint::assert_unchecked(result <= MAX_RESULT);
3477 }
3478
3479 result
3480 }
3481
3482 /// Performs Euclidean division.
3483 ///
3484 /// Since, for the positive integers, all common
3485 /// definitions of division are equal, this
3486 /// is exactly equal to `self / rhs`.
3487 ///
3488 /// # Panics
3489 ///
3490 /// This function will panic if `rhs` is zero.
3491 ///
3492 /// # Examples
3493 ///
3494 /// ```
3495 #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type")]
3496 /// ```
3497 #[stable(feature = "euclidean_division", since = "1.38.0")]
3498 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
3499 #[must_use = "this returns the result of the operation, \
3500 without modifying the original"]
3501 #[inline(always)]
3502 #[track_caller]
3503 pub const fn div_euclid(self, rhs: Self) -> Self {
3504 self / rhs
3505 }
3506
3507
3508 /// Calculates the least remainder of `self` when divided by
3509 /// `rhs`.
3510 ///
3511 /// Since, for the positive integers, all common
3512 /// definitions of division are equal, this
3513 /// is exactly equal to `self % rhs`.
3514 ///
3515 /// # Panics
3516 ///
3517 /// This function will panic if `rhs` is zero.
3518 ///
3519 /// # Examples
3520 ///
3521 /// ```
3522 #[doc = concat!("assert_eq!(7", stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type")]
3523 /// ```
3524 #[doc(alias = "modulo", alias = "mod")]
3525 #[stable(feature = "euclidean_division", since = "1.38.0")]
3526 #[rustc_const_stable(feature = "const_euclidean_int_methods", since = "1.52.0")]
3527 #[must_use = "this returns the result of the operation, \
3528 without modifying the original"]
3529 #[inline(always)]
3530 #[track_caller]
3531 pub const fn rem_euclid(self, rhs: Self) -> Self {
3532 self % rhs
3533 }
3534
3535 /// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
3536 ///
3537 /// This is the same as performing `self / rhs` for all unsigned integers.
3538 ///
3539 /// # Panics
3540 ///
3541 /// This function will panic if `rhs` is zero.
3542 ///
3543 /// # Examples
3544 ///
3545 /// ```
3546 /// #![feature(int_roundings)]
3547 #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".div_floor(4), 1);")]
3548 /// ```
3549 #[unstable(feature = "int_roundings", issue = "88581")]
3550 #[must_use = "this returns the result of the operation, \
3551 without modifying the original"]
3552 #[inline(always)]
3553 #[track_caller]
3554 pub const fn div_floor(self, rhs: Self) -> Self {
3555 self / rhs
3556 }
3557
3558 /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
3559 ///
3560 /// # Panics
3561 ///
3562 /// This function will panic if `rhs` is zero.
3563 ///
3564 /// # Examples
3565 ///
3566 /// ```
3567 #[doc = concat!("assert_eq!(7_", stringify!($SelfT), ".div_ceil(4), 2);")]
3568 /// ```
3569 #[stable(feature = "int_roundings1", since = "1.73.0")]
3570 #[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
3571 #[must_use = "this returns the result of the operation, \
3572 without modifying the original"]
3573 #[inline]
3574 #[track_caller]
3575 pub const fn div_ceil(self, rhs: Self) -> Self {
3576 let d = self / rhs;
3577 let r = self % rhs;
3578 if r > 0 {
3579 d + 1
3580 } else {
3581 d
3582 }
3583 }
3584
3585 /// Calculates the smallest value greater than or equal to `self` that
3586 /// is a multiple of `rhs`.
3587 ///
3588 /// # Panics
3589 ///
3590 /// This function will panic if `rhs` is zero.
3591 ///
3592 /// ## Overflow behavior
3593 ///
3594 /// On overflow, this function will panic if overflow checks are enabled (default in debug
3595 /// mode) and wrap if overflow checks are disabled (default in release mode).
3596 ///
3597 /// # Examples
3598 ///
3599 /// ```
3600 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".next_multiple_of(8), 16);")]
3601 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".next_multiple_of(8), 24);")]
3602 /// ```
3603 #[stable(feature = "int_roundings1", since = "1.73.0")]
3604 #[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
3605 #[must_use = "this returns the result of the operation, \
3606 without modifying the original"]
3607 #[inline]
3608 #[rustc_inherit_overflow_checks]
3609 pub const fn next_multiple_of(self, rhs: Self) -> Self {
3610 match self % rhs {
3611 0 => self,
3612 r => self + (rhs - r)
3613 }
3614 }
3615
3616 /// Calculates the smallest value greater than or equal to `self` that
3617 /// is a multiple of `rhs`. Returns `None` if `rhs` is zero or the
3618 /// operation would result in overflow.
3619 ///
3620 /// # Examples
3621 ///
3622 /// ```
3623 #[doc = concat!("assert_eq!(16_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(16));")]
3624 #[doc = concat!("assert_eq!(23_", stringify!($SelfT), ".checked_next_multiple_of(8), Some(24));")]
3625 #[doc = concat!("assert_eq!(1_", stringify!($SelfT), ".checked_next_multiple_of(0), None);")]
3626 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_multiple_of(2), None);")]
3627 /// ```
3628 #[stable(feature = "int_roundings1", since = "1.73.0")]
3629 #[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
3630 #[must_use = "this returns the result of the operation, \
3631 without modifying the original"]
3632 #[inline]
3633 pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
3634 match try_opt!(self.checked_rem(rhs)) {
3635 0 => Some(self),
3636 // rhs - r cannot overflow because r is smaller than rhs
3637 r => self.checked_add(rhs - r)
3638 }
3639 }
3640
3641 /// Returns `true` if `self` is an integer multiple of `rhs`, and false otherwise.
3642 ///
3643 /// This function is equivalent to `self % rhs == 0`, except that it will not panic
3644 /// for `rhs == 0`. Instead, `0.is_multiple_of(0) == true`, and for any non-zero `n`,
3645 /// `n.is_multiple_of(0) == false`.
3646 ///
3647 /// # Examples
3648 ///
3649 /// ```
3650 #[doc = concat!("assert!(6_", stringify!($SelfT), ".is_multiple_of(2));")]
3651 #[doc = concat!("assert!(!5_", stringify!($SelfT), ".is_multiple_of(2));")]
3652 ///
3653 #[doc = concat!("assert!(0_", stringify!($SelfT), ".is_multiple_of(0));")]
3654 #[doc = concat!("assert!(!6_", stringify!($SelfT), ".is_multiple_of(0));")]
3655 /// ```
3656 #[stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
3657 #[rustc_const_stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
3658 #[must_use]
3659 #[inline]
3660 pub const fn is_multiple_of(self, rhs: Self) -> bool {
3661 match rhs {
3662 0 => self == 0,
3663 _ => self % rhs == 0,
3664 }
3665 }
3666
3667 /// Returns `true` if and only if `self == 2^k` for some unsigned integer `k`.
3668 ///
3669 /// # Examples
3670 ///
3671 /// ```
3672 #[doc = concat!("assert!(16", stringify!($SelfT), ".is_power_of_two());")]
3673 #[doc = concat!("assert!(!10", stringify!($SelfT), ".is_power_of_two());")]
3674 /// ```
3675 #[must_use]
3676 #[stable(feature = "rust1", since = "1.0.0")]
3677 #[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
3678 #[inline(always)]
3679 pub const fn is_power_of_two(self) -> bool {
3680 self.count_ones() == 1
3681 }
3682
3683 // Returns one less than next power of two.
3684 // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8)
3685 //
3686 // 8u8.one_less_than_next_power_of_two() == 7
3687 // 6u8.one_less_than_next_power_of_two() == 7
3688 //
3689 // This method cannot overflow, as in the `next_power_of_two`
3690 // overflow cases it instead ends up returning the maximum value
3691 // of the type, and can return 0 for 0.
3692 #[inline]
3693 const fn one_less_than_next_power_of_two(self) -> Self {
3694 if self <= 1 { return 0; }
3695
3696 let p = self - 1;
3697 // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros.
3698 // That means the shift is always in-bounds, and some processors
3699 // (such as intel pre-haswell) have more efficient ctlz
3700 // intrinsics when the argument is non-zero.
3701 let z = unsafe { intrinsics::ctlz_nonzero(p) };
3702 <$SelfT>::MAX >> z
3703 }
3704
3705 /// Returns the smallest power of two greater than or equal to `self`.
3706 ///
3707 /// When return value overflows (i.e., `self > (1 << (N-1))` for type
3708 /// `uN`), it panics in debug mode and the return value is wrapped to 0 in
3709 /// release mode (the only situation in which this method can return 0).
3710 ///
3711 /// # Examples
3712 ///
3713 /// ```
3714 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".next_power_of_two(), 2);")]
3715 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".next_power_of_two(), 4);")]
3716 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".next_power_of_two(), 1);")]
3717 /// ```
3718 #[stable(feature = "rust1", since = "1.0.0")]
3719 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
3720 #[must_use = "this returns the result of the operation, \
3721 without modifying the original"]
3722 #[inline]
3723 #[rustc_inherit_overflow_checks]
3724 pub const fn next_power_of_two(self) -> Self {
3725 self.one_less_than_next_power_of_two() + 1
3726 }
3727
3728 /// Returns the smallest power of two greater than or equal to `self`. If
3729 /// the next power of two is greater than the type's maximum value,
3730 /// `None` is returned, otherwise the power of two is wrapped in `Some`.
3731 ///
3732 /// # Examples
3733 ///
3734 /// ```
3735 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".checked_next_power_of_two(), Some(2));")]
3736 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".checked_next_power_of_two(), Some(4));")]
3737 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.checked_next_power_of_two(), None);")]
3738 /// ```
3739 #[inline]
3740 #[stable(feature = "rust1", since = "1.0.0")]
3741 #[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
3742 #[must_use = "this returns the result of the operation, \
3743 without modifying the original"]
3744 pub const fn checked_next_power_of_two(self) -> Option<Self> {
3745 self.one_less_than_next_power_of_two().checked_add(1)
3746 }
3747
3748 /// Returns the smallest power of two greater than or equal to `n`. If
3749 /// the next power of two is greater than the type's maximum value,
3750 /// the return value is wrapped to `0`.
3751 ///
3752 /// # Examples
3753 ///
3754 /// ```
3755 /// #![feature(wrapping_next_power_of_two)]
3756 ///
3757 #[doc = concat!("assert_eq!(2", stringify!($SelfT), ".wrapping_next_power_of_two(), 2);")]
3758 #[doc = concat!("assert_eq!(3", stringify!($SelfT), ".wrapping_next_power_of_two(), 4);")]
3759 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.wrapping_next_power_of_two(), 0);")]
3760 /// ```
3761 #[inline]
3762 #[unstable(feature = "wrapping_next_power_of_two", issue = "32463",
3763 reason = "needs decision on wrapping behavior")]
3764 #[must_use = "this returns the result of the operation, \
3765 without modifying the original"]
3766 pub const fn wrapping_next_power_of_two(self) -> Self {
3767 self.one_less_than_next_power_of_two().wrapping_add(1)
3768 }
3769
3770 /// Returns the memory representation of this integer as a byte array in
3771 /// big-endian (network) byte order.
3772 ///
3773 #[doc = $to_xe_bytes_doc]
3774 ///
3775 /// # Examples
3776 ///
3777 /// ```
3778 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_be_bytes();")]
3779 #[doc = concat!("assert_eq!(bytes, ", $be_bytes, ");")]
3780 /// ```
3781 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3782 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3783 #[must_use = "this returns the result of the operation, \
3784 without modifying the original"]
3785 #[inline]
3786 pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
3787 self.to_be().to_ne_bytes()
3788 }
3789
3790 /// Returns the memory representation of this integer as a byte array in
3791 /// little-endian byte order.
3792 ///
3793 #[doc = $to_xe_bytes_doc]
3794 ///
3795 /// # Examples
3796 ///
3797 /// ```
3798 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_le_bytes();")]
3799 #[doc = concat!("assert_eq!(bytes, ", $le_bytes, ");")]
3800 /// ```
3801 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3802 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3803 #[must_use = "this returns the result of the operation, \
3804 without modifying the original"]
3805 #[inline]
3806 pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
3807 self.to_le().to_ne_bytes()
3808 }
3809
3810 /// Returns the memory representation of this integer as a byte array in
3811 /// native byte order.
3812 ///
3813 /// As the target platform's native endianness is used, portable code
3814 /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
3815 /// instead.
3816 ///
3817 #[doc = $to_xe_bytes_doc]
3818 ///
3819 /// [`to_be_bytes`]: Self::to_be_bytes
3820 /// [`to_le_bytes`]: Self::to_le_bytes
3821 ///
3822 /// # Examples
3823 ///
3824 /// ```
3825 #[doc = concat!("let bytes = ", $swap_op, stringify!($SelfT), ".to_ne_bytes();")]
3826 /// assert_eq!(
3827 /// bytes,
3828 /// if cfg!(target_endian = "big") {
3829 #[doc = concat!(" ", $be_bytes)]
3830 /// } else {
3831 #[doc = concat!(" ", $le_bytes)]
3832 /// }
3833 /// );
3834 /// ```
3835 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3836 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3837 #[must_use = "this returns the result of the operation, \
3838 without modifying the original"]
3839 #[allow(unnecessary_transmutes)]
3840 // SAFETY: const sound because integers are plain old datatypes so we can always
3841 // transmute them to arrays of bytes
3842 #[inline]
3843 pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
3844 // SAFETY: integers are plain old datatypes so we can always transmute them to
3845 // arrays of bytes
3846 unsafe { mem::transmute(self) }
3847 }
3848
3849 /// Creates a native endian integer value from its representation
3850 /// as a byte array in big endian.
3851 ///
3852 #[doc = $from_xe_bytes_doc]
3853 ///
3854 /// # Examples
3855 ///
3856 /// ```
3857 #[doc = concat!("let value = ", stringify!($SelfT), "::from_be_bytes(", $be_bytes, ");")]
3858 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
3859 /// ```
3860 ///
3861 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
3862 ///
3863 /// ```
3864 #[doc = concat!("fn read_be_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
3865 #[doc = concat!(" let (int_bytes, rest) = input.split_at(size_of::<", stringify!($SelfT), ">());")]
3866 /// *input = rest;
3867 #[doc = concat!(" ", stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())")]
3868 /// }
3869 /// ```
3870 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3871 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3872 #[must_use]
3873 #[inline]
3874 pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
3875 Self::from_be(Self::from_ne_bytes(bytes))
3876 }
3877
3878 /// Creates a native endian integer value from its representation
3879 /// as a byte array in little endian.
3880 ///
3881 #[doc = $from_xe_bytes_doc]
3882 ///
3883 /// # Examples
3884 ///
3885 /// ```
3886 #[doc = concat!("let value = ", stringify!($SelfT), "::from_le_bytes(", $le_bytes, ");")]
3887 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
3888 /// ```
3889 ///
3890 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
3891 ///
3892 /// ```
3893 #[doc = concat!("fn read_le_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
3894 #[doc = concat!(" let (int_bytes, rest) = input.split_at(size_of::<", stringify!($SelfT), ">());")]
3895 /// *input = rest;
3896 #[doc = concat!(" ", stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())")]
3897 /// }
3898 /// ```
3899 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3900 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3901 #[must_use]
3902 #[inline]
3903 pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
3904 Self::from_le(Self::from_ne_bytes(bytes))
3905 }
3906
3907 /// Creates a native endian integer value from its memory representation
3908 /// as a byte array in native endianness.
3909 ///
3910 /// As the target platform's native endianness is used, portable code
3911 /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
3912 /// appropriate instead.
3913 ///
3914 /// [`from_be_bytes`]: Self::from_be_bytes
3915 /// [`from_le_bytes`]: Self::from_le_bytes
3916 ///
3917 #[doc = $from_xe_bytes_doc]
3918 ///
3919 /// # Examples
3920 ///
3921 /// ```
3922 #[doc = concat!("let value = ", stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big\") {")]
3923 #[doc = concat!(" ", $be_bytes, "")]
3924 /// } else {
3925 #[doc = concat!(" ", $le_bytes, "")]
3926 /// });
3927 #[doc = concat!("assert_eq!(value, ", $swap_op, ");")]
3928 /// ```
3929 ///
3930 /// When starting from a slice rather than an array, fallible conversion APIs can be used:
3931 ///
3932 /// ```
3933 #[doc = concat!("fn read_ne_", stringify!($SelfT), "(input: &mut &[u8]) -> ", stringify!($SelfT), " {")]
3934 #[doc = concat!(" let (int_bytes, rest) = input.split_at(size_of::<", stringify!($SelfT), ">());")]
3935 /// *input = rest;
3936 #[doc = concat!(" ", stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())")]
3937 /// }
3938 /// ```
3939 #[stable(feature = "int_to_from_bytes", since = "1.32.0")]
3940 #[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
3941 #[allow(unnecessary_transmutes)]
3942 #[must_use]
3943 // SAFETY: const sound because integers are plain old datatypes so we can always
3944 // transmute to them
3945 #[inline]
3946 pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
3947 // SAFETY: integers are plain old datatypes so we can always transmute to them
3948 unsafe { mem::transmute(bytes) }
3949 }
3950
3951 /// New code should prefer to use
3952 #[doc = concat!("[`", stringify!($SelfT), "::MIN", "`] instead.")]
3953 ///
3954 /// Returns the smallest value that can be represented by this integer type.
3955 #[stable(feature = "rust1", since = "1.0.0")]
3956 #[rustc_promotable]
3957 #[inline(always)]
3958 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
3959 #[deprecated(since = "TBD", note = "replaced by the `MIN` associated constant on this type")]
3960 #[rustc_diagnostic_item = concat!(stringify!($SelfT), "_legacy_fn_min_value")]
3961 pub const fn min_value() -> Self { Self::MIN }
3962
3963 /// New code should prefer to use
3964 #[doc = concat!("[`", stringify!($SelfT), "::MAX", "`] instead.")]
3965 ///
3966 /// Returns the largest value that can be represented by this integer type.
3967 #[stable(feature = "rust1", since = "1.0.0")]
3968 #[rustc_promotable]
3969 #[inline(always)]
3970 #[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
3971 #[deprecated(since = "TBD", note = "replaced by the `MAX` associated constant on this type")]
3972 #[rustc_diagnostic_item = concat!(stringify!($SelfT), "_legacy_fn_max_value")]
3973 pub const fn max_value() -> Self { Self::MAX }
3974 }
3975}