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