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