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