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