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