1 | macro_rules! int_impl { |
2 | ( |
3 | Self = $SelfT:ty, |
4 | ActualT = $ActualT:ident, |
5 | UnsignedT = $UnsignedT:ty, |
6 | |
7 | // There 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 | #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces |
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 | #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces |
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 | #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces |
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 remainder. Computes `self % rhs`, returning `None` if |
1022 | /// `rhs == 0` or the division results in overflow. |
1023 | /// |
1024 | /// # Examples |
1025 | /// |
1026 | /// Basic usage: |
1027 | /// |
1028 | /// ``` |
1029 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".checked_rem(2), Some(1));" )] |
1030 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".checked_rem(0), None);" )] |
1031 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MIN.checked_rem(-1), None);" )] |
1032 | /// ``` |
1033 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
1034 | #[rustc_const_stable(feature = "const_checked_int_div" , since = "1.52.0" )] |
1035 | #[must_use = "this returns the result of the operation, \ |
1036 | without modifying the original" ] |
1037 | #[inline] |
1038 | pub const fn checked_rem(self, rhs: Self) -> Option<Self> { |
1039 | if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1))) { |
1040 | None |
1041 | } else { |
1042 | // SAFETY: div by zero and by INT_MIN have been checked above |
1043 | Some(unsafe { intrinsics::unchecked_rem(self, rhs) }) |
1044 | } |
1045 | } |
1046 | |
1047 | /// Strict integer remainder. Computes `self % rhs`, panicking if |
1048 | /// the division results in overflow. |
1049 | /// |
1050 | /// # Panics |
1051 | /// |
1052 | /// This function will panic if `rhs` is zero. |
1053 | /// |
1054 | /// ## Overflow behavior |
1055 | /// |
1056 | /// This function will always panic on overflow, regardless of whether overflow checks are enabled. |
1057 | /// |
1058 | /// The only case where such an overflow can occur is `x % y` for `MIN / -1` on a |
1059 | /// signed type (where `MIN` is the negative minimal value), which is invalid due to implementation artifacts. |
1060 | /// |
1061 | /// # Examples |
1062 | /// |
1063 | /// Basic usage: |
1064 | /// |
1065 | /// ``` |
1066 | /// #![feature(strict_overflow_ops)] |
1067 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".strict_rem(2), 1);" )] |
1068 | /// ``` |
1069 | /// |
1070 | /// The following panics because of division by zero: |
1071 | /// |
1072 | /// ```should_panic |
1073 | /// #![feature(strict_overflow_ops)] |
1074 | #[doc = concat!("let _ = 5" , stringify!($SelfT), ".strict_rem(0);" )] |
1075 | /// ``` |
1076 | /// |
1077 | /// The following panics because of overflow: |
1078 | /// |
1079 | /// ```should_panic |
1080 | /// #![feature(strict_overflow_ops)] |
1081 | #[doc = concat!("let _ = " , stringify!($SelfT), "::MIN.strict_rem(-1);" )] |
1082 | /// ``` |
1083 | #[unstable(feature = "strict_overflow_ops" , issue = "118260" )] |
1084 | #[must_use = "this returns the result of the operation, \ |
1085 | without modifying the original" ] |
1086 | #[inline] |
1087 | #[track_caller] |
1088 | pub const fn strict_rem(self, rhs: Self) -> Self { |
1089 | let (a, b) = self.overflowing_rem(rhs); |
1090 | if b { overflow_panic::rem() } else { a } |
1091 | } |
1092 | |
1093 | /// Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None` |
1094 | /// if `rhs == 0` or the division results in overflow. |
1095 | /// |
1096 | /// # Examples |
1097 | /// |
1098 | /// Basic usage: |
1099 | /// |
1100 | /// ``` |
1101 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".checked_rem_euclid(2), Some(1));" )] |
1102 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".checked_rem_euclid(0), None);" )] |
1103 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MIN.checked_rem_euclid(-1), None);" )] |
1104 | /// ``` |
1105 | #[stable(feature = "euclidean_division" , since = "1.38.0" )] |
1106 | #[rustc_const_stable(feature = "const_euclidean_int_methods" , since = "1.52.0" )] |
1107 | #[must_use = "this returns the result of the operation, \ |
1108 | without modifying the original" ] |
1109 | #[inline] |
1110 | pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> { |
1111 | // Using `&` helps LLVM see that it is the same check made in division. |
1112 | if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) { |
1113 | None |
1114 | } else { |
1115 | Some(self.rem_euclid(rhs)) |
1116 | } |
1117 | } |
1118 | |
1119 | /// Strict Euclidean remainder. Computes `self.rem_euclid(rhs)`, panicking if |
1120 | /// the division results in overflow. |
1121 | /// |
1122 | /// # Panics |
1123 | /// |
1124 | /// This function will panic if `rhs` is zero. |
1125 | /// |
1126 | /// ## Overflow behavior |
1127 | /// |
1128 | /// This function will always panic on overflow, regardless of whether overflow checks are enabled. |
1129 | /// |
1130 | /// The only case where such an overflow can occur is `x % y` for `MIN / -1` on a |
1131 | /// signed type (where `MIN` is the negative minimal value), which is invalid due to implementation artifacts. |
1132 | /// |
1133 | /// # Examples |
1134 | /// |
1135 | /// Basic usage: |
1136 | /// |
1137 | /// ``` |
1138 | /// #![feature(strict_overflow_ops)] |
1139 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".strict_rem_euclid(2), 1);" )] |
1140 | /// ``` |
1141 | /// |
1142 | /// The following panics because of division by zero: |
1143 | /// |
1144 | /// ```should_panic |
1145 | /// #![feature(strict_overflow_ops)] |
1146 | #[doc = concat!("let _ = 5" , stringify!($SelfT), ".strict_rem_euclid(0);" )] |
1147 | /// ``` |
1148 | /// |
1149 | /// The following panics because of overflow: |
1150 | /// |
1151 | /// ```should_panic |
1152 | /// #![feature(strict_overflow_ops)] |
1153 | #[doc = concat!("let _ = " , stringify!($SelfT), "::MIN.strict_rem_euclid(-1);" )] |
1154 | /// ``` |
1155 | #[unstable(feature = "strict_overflow_ops" , issue = "118260" )] |
1156 | #[must_use = "this returns the result of the operation, \ |
1157 | without modifying the original" ] |
1158 | #[inline] |
1159 | #[track_caller] |
1160 | pub const fn strict_rem_euclid(self, rhs: Self) -> Self { |
1161 | let (a, b) = self.overflowing_rem_euclid(rhs); |
1162 | if b { overflow_panic::rem() } else { a } |
1163 | } |
1164 | |
1165 | /// Checked negation. Computes `-self`, returning `None` if `self == MIN`. |
1166 | /// |
1167 | /// # Examples |
1168 | /// |
1169 | /// Basic usage: |
1170 | /// |
1171 | /// ``` |
1172 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".checked_neg(), Some(-5));" )] |
1173 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MIN.checked_neg(), None);" )] |
1174 | /// ``` |
1175 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
1176 | #[rustc_const_stable(feature = "const_checked_int_methods" , since = "1.47.0" )] |
1177 | #[must_use = "this returns the result of the operation, \ |
1178 | without modifying the original" ] |
1179 | #[inline] |
1180 | pub const fn checked_neg(self) -> Option<Self> { |
1181 | let (a, b) = self.overflowing_neg(); |
1182 | if intrinsics::unlikely(b) { None } else { Some(a) } |
1183 | } |
1184 | |
1185 | /// Unchecked negation. Computes `-self`, assuming overflow cannot occur. |
1186 | /// |
1187 | /// # Safety |
1188 | /// |
1189 | /// This results in undefined behavior when |
1190 | #[doc = concat!("`self == " , stringify!($SelfT), "::MIN`," )] |
1191 | /// i.e. when [`checked_neg`] would return `None`. |
1192 | /// |
1193 | #[doc = concat!("[`checked_neg`]: " , stringify!($SelfT), "::checked_neg" )] |
1194 | #[unstable( |
1195 | feature = "unchecked_neg" , |
1196 | reason = "niche optimization path" , |
1197 | issue = "85122" , |
1198 | )] |
1199 | #[must_use = "this returns the result of the operation, \ |
1200 | without modifying the original" ] |
1201 | #[inline(always)] |
1202 | #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces |
1203 | pub const unsafe fn unchecked_neg(self) -> Self { |
1204 | assert_unsafe_precondition!( |
1205 | check_language_ub, |
1206 | concat!(stringify!($SelfT), "::unchecked_neg cannot overflow" ), |
1207 | ( |
1208 | lhs: $SelfT = self, |
1209 | ) => !lhs.overflowing_neg().1, |
1210 | ); |
1211 | |
1212 | // SAFETY: this is guaranteed to be safe by the caller. |
1213 | unsafe { |
1214 | intrinsics::unchecked_sub(0, self) |
1215 | } |
1216 | } |
1217 | |
1218 | /// Strict negation. Computes `-self`, panicking if `self == MIN`. |
1219 | /// |
1220 | /// # Panics |
1221 | /// |
1222 | /// ## Overflow behavior |
1223 | /// |
1224 | /// This function will always panic on overflow, regardless of whether overflow checks are enabled. |
1225 | /// |
1226 | /// # Examples |
1227 | /// |
1228 | /// Basic usage: |
1229 | /// |
1230 | /// ``` |
1231 | /// #![feature(strict_overflow_ops)] |
1232 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".strict_neg(), -5);" )] |
1233 | /// ``` |
1234 | /// |
1235 | /// The following panics because of overflow: |
1236 | /// |
1237 | /// ```should_panic |
1238 | /// #![feature(strict_overflow_ops)] |
1239 | #[doc = concat!("let _ = " , stringify!($SelfT), "::MIN.strict_neg();" )] |
1240 | /// |
1241 | #[unstable(feature = "strict_overflow_ops" , issue = "118260" )] |
1242 | #[must_use = "this returns the result of the operation, \ |
1243 | without modifying the original" ] |
1244 | #[inline] |
1245 | #[track_caller] |
1246 | pub const fn strict_neg(self) -> Self { |
1247 | let (a, b) = self.overflowing_neg(); |
1248 | if b { overflow_panic::neg() } else { a } |
1249 | } |
1250 | |
1251 | /// Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger |
1252 | /// than or equal to the number of bits in `self`. |
1253 | /// |
1254 | /// # Examples |
1255 | /// |
1256 | /// Basic usage: |
1257 | /// |
1258 | /// ``` |
1259 | #[doc = concat!("assert_eq!(0x1" , stringify!($SelfT), ".checked_shl(4), Some(0x10));" )] |
1260 | #[doc = concat!("assert_eq!(0x1" , stringify!($SelfT), ".checked_shl(129), None);" )] |
1261 | #[doc = concat!("assert_eq!(0x10" , stringify!($SelfT), ".checked_shl(" , stringify!($BITS_MINUS_ONE), "), Some(0));" )] |
1262 | /// ``` |
1263 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
1264 | #[rustc_const_stable(feature = "const_checked_int_methods" , since = "1.47.0" )] |
1265 | #[must_use = "this returns the result of the operation, \ |
1266 | without modifying the original" ] |
1267 | #[inline] |
1268 | pub const fn checked_shl(self, rhs: u32) -> Option<Self> { |
1269 | // Not using overflowing_shl as that's a wrapping shift |
1270 | if rhs < Self::BITS { |
1271 | // SAFETY: just checked the RHS is in-range |
1272 | Some(unsafe { self.unchecked_shl(rhs) }) |
1273 | } else { |
1274 | None |
1275 | } |
1276 | } |
1277 | |
1278 | /// Strict shift left. Computes `self << rhs`, panicking if `rhs` is larger |
1279 | /// than or equal to the number of bits in `self`. |
1280 | /// |
1281 | /// # Panics |
1282 | /// |
1283 | /// ## Overflow behavior |
1284 | /// |
1285 | /// This function will always panic on overflow, regardless of whether overflow checks are enabled. |
1286 | /// |
1287 | /// # Examples |
1288 | /// |
1289 | /// Basic usage: |
1290 | /// |
1291 | /// ``` |
1292 | /// #![feature(strict_overflow_ops)] |
1293 | #[doc = concat!("assert_eq!(0x1" , stringify!($SelfT), ".strict_shl(4), 0x10);" )] |
1294 | /// ``` |
1295 | /// |
1296 | /// The following panics because of overflow: |
1297 | /// |
1298 | /// ```should_panic |
1299 | /// #![feature(strict_overflow_ops)] |
1300 | #[doc = concat!("let _ = 0x1" , stringify!($SelfT), ".strict_shl(129);" )] |
1301 | /// ``` |
1302 | #[unstable(feature = "strict_overflow_ops" , issue = "118260" )] |
1303 | #[must_use = "this returns the result of the operation, \ |
1304 | without modifying the original" ] |
1305 | #[inline] |
1306 | #[track_caller] |
1307 | pub const fn strict_shl(self, rhs: u32) -> Self { |
1308 | let (a, b) = self.overflowing_shl(rhs); |
1309 | if b { overflow_panic::shl() } else { a } |
1310 | } |
1311 | |
1312 | /// Unchecked shift left. Computes `self << rhs`, assuming that |
1313 | /// `rhs` is less than the number of bits in `self`. |
1314 | /// |
1315 | /// # Safety |
1316 | /// |
1317 | /// This results in undefined behavior if `rhs` is larger than |
1318 | /// or equal to the number of bits in `self`, |
1319 | /// i.e. when [`checked_shl`] would return `None`. |
1320 | /// |
1321 | #[doc = concat!("[`checked_shl`]: " , stringify!($SelfT), "::checked_shl" )] |
1322 | #[unstable( |
1323 | feature = "unchecked_shifts" , |
1324 | reason = "niche optimization path" , |
1325 | issue = "85122" , |
1326 | )] |
1327 | #[must_use = "this returns the result of the operation, \ |
1328 | without modifying the original" ] |
1329 | #[inline(always)] |
1330 | #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces |
1331 | pub const unsafe fn unchecked_shl(self, rhs: u32) -> Self { |
1332 | assert_unsafe_precondition!( |
1333 | check_language_ub, |
1334 | concat!(stringify!($SelfT), "::unchecked_shl cannot overflow" ), |
1335 | ( |
1336 | rhs: u32 = rhs, |
1337 | ) => rhs < <$ActualT>::BITS, |
1338 | ); |
1339 | |
1340 | // SAFETY: this is guaranteed to be safe by the caller. |
1341 | unsafe { |
1342 | intrinsics::unchecked_shl(self, rhs) |
1343 | } |
1344 | } |
1345 | |
1346 | /// Unbounded shift left. Computes `self << rhs`, without bounding the value of `rhs`. |
1347 | /// |
1348 | /// If `rhs` is larger or equal to the number of bits in `self`, |
1349 | /// the entire value is shifted out, and `0` is returned. |
1350 | /// |
1351 | /// # Examples |
1352 | /// |
1353 | /// Basic usage: |
1354 | /// ``` |
1355 | #[doc = concat!("assert_eq!(0x1" , stringify!($SelfT), ".unbounded_shl(4), 0x10);" )] |
1356 | #[doc = concat!("assert_eq!(0x1" , stringify!($SelfT), ".unbounded_shl(129), 0);" )] |
1357 | /// ``` |
1358 | #[stable(feature = "unbounded_shifts" , since = "1.87.0" )] |
1359 | #[rustc_const_stable(feature = "unbounded_shifts" , since = "1.87.0" )] |
1360 | #[must_use = "this returns the result of the operation, \ |
1361 | without modifying the original" ] |
1362 | #[inline] |
1363 | pub const fn unbounded_shl(self, rhs: u32) -> $SelfT{ |
1364 | if rhs < Self::BITS { |
1365 | // SAFETY: |
1366 | // rhs is just checked to be in-range above |
1367 | unsafe { self.unchecked_shl(rhs) } |
1368 | } else { |
1369 | 0 |
1370 | } |
1371 | } |
1372 | |
1373 | /// Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is |
1374 | /// larger than or equal to the number of bits in `self`. |
1375 | /// |
1376 | /// # Examples |
1377 | /// |
1378 | /// Basic usage: |
1379 | /// |
1380 | /// ``` |
1381 | #[doc = concat!("assert_eq!(0x10" , stringify!($SelfT), ".checked_shr(4), Some(0x1));" )] |
1382 | #[doc = concat!("assert_eq!(0x10" , stringify!($SelfT), ".checked_shr(128), None);" )] |
1383 | /// ``` |
1384 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
1385 | #[rustc_const_stable(feature = "const_checked_int_methods" , since = "1.47.0" )] |
1386 | #[must_use = "this returns the result of the operation, \ |
1387 | without modifying the original" ] |
1388 | #[inline] |
1389 | pub const fn checked_shr(self, rhs: u32) -> Option<Self> { |
1390 | // Not using overflowing_shr as that's a wrapping shift |
1391 | if rhs < Self::BITS { |
1392 | // SAFETY: just checked the RHS is in-range |
1393 | Some(unsafe { self.unchecked_shr(rhs) }) |
1394 | } else { |
1395 | None |
1396 | } |
1397 | } |
1398 | |
1399 | /// Strict shift right. Computes `self >> rhs`, panicking `rhs` is |
1400 | /// larger than or equal to the number of bits in `self`. |
1401 | /// |
1402 | /// # Panics |
1403 | /// |
1404 | /// ## Overflow behavior |
1405 | /// |
1406 | /// This function will always panic on overflow, regardless of whether overflow checks are enabled. |
1407 | /// |
1408 | /// # Examples |
1409 | /// |
1410 | /// Basic usage: |
1411 | /// |
1412 | /// ``` |
1413 | /// #![feature(strict_overflow_ops)] |
1414 | #[doc = concat!("assert_eq!(0x10" , stringify!($SelfT), ".strict_shr(4), 0x1);" )] |
1415 | /// ``` |
1416 | /// |
1417 | /// The following panics because of overflow: |
1418 | /// |
1419 | /// ```should_panic |
1420 | /// #![feature(strict_overflow_ops)] |
1421 | #[doc = concat!("let _ = 0x10" , stringify!($SelfT), ".strict_shr(128);" )] |
1422 | /// ``` |
1423 | #[unstable(feature = "strict_overflow_ops" , issue = "118260" )] |
1424 | #[must_use = "this returns the result of the operation, \ |
1425 | without modifying the original" ] |
1426 | #[inline] |
1427 | #[track_caller] |
1428 | pub const fn strict_shr(self, rhs: u32) -> Self { |
1429 | let (a, b) = self.overflowing_shr(rhs); |
1430 | if b { overflow_panic::shr() } else { a } |
1431 | } |
1432 | |
1433 | /// Unchecked shift right. Computes `self >> rhs`, assuming that |
1434 | /// `rhs` is less than the number of bits in `self`. |
1435 | /// |
1436 | /// # Safety |
1437 | /// |
1438 | /// This results in undefined behavior if `rhs` is larger than |
1439 | /// or equal to the number of bits in `self`, |
1440 | /// i.e. when [`checked_shr`] would return `None`. |
1441 | /// |
1442 | #[doc = concat!("[`checked_shr`]: " , stringify!($SelfT), "::checked_shr" )] |
1443 | #[unstable( |
1444 | feature = "unchecked_shifts" , |
1445 | reason = "niche optimization path" , |
1446 | issue = "85122" , |
1447 | )] |
1448 | #[must_use = "this returns the result of the operation, \ |
1449 | without modifying the original" ] |
1450 | #[inline(always)] |
1451 | #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces |
1452 | pub const unsafe fn unchecked_shr(self, rhs: u32) -> Self { |
1453 | assert_unsafe_precondition!( |
1454 | check_language_ub, |
1455 | concat!(stringify!($SelfT), "::unchecked_shr cannot overflow" ), |
1456 | ( |
1457 | rhs: u32 = rhs, |
1458 | ) => rhs < <$ActualT>::BITS, |
1459 | ); |
1460 | |
1461 | // SAFETY: this is guaranteed to be safe by the caller. |
1462 | unsafe { |
1463 | intrinsics::unchecked_shr(self, rhs) |
1464 | } |
1465 | } |
1466 | |
1467 | /// Unbounded shift right. Computes `self >> rhs`, without bounding the value of `rhs`. |
1468 | /// |
1469 | /// If `rhs` is larger or equal to the number of bits in `self`, |
1470 | /// the entire value is shifted out, which yields `0` for a positive number, |
1471 | /// and `-1` for a negative number. |
1472 | /// |
1473 | /// # Examples |
1474 | /// |
1475 | /// Basic usage: |
1476 | /// ``` |
1477 | #[doc = concat!("assert_eq!(0x10" , stringify!($SelfT), ".unbounded_shr(4), 0x1);" )] |
1478 | #[doc = concat!("assert_eq!(0x10" , stringify!($SelfT), ".unbounded_shr(129), 0);" )] |
1479 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MIN.unbounded_shr(129), -1);" )] |
1480 | /// ``` |
1481 | #[stable(feature = "unbounded_shifts" , since = "1.87.0" )] |
1482 | #[rustc_const_stable(feature = "unbounded_shifts" , since = "1.87.0" )] |
1483 | #[must_use = "this returns the result of the operation, \ |
1484 | without modifying the original" ] |
1485 | #[inline] |
1486 | pub const fn unbounded_shr(self, rhs: u32) -> $SelfT{ |
1487 | if rhs < Self::BITS { |
1488 | // SAFETY: |
1489 | // rhs is just checked to be in-range above |
1490 | unsafe { self.unchecked_shr(rhs) } |
1491 | } else { |
1492 | // A shift by `Self::BITS-1` suffices for signed integers, because the sign bit is copied for each of the shifted bits. |
1493 | |
1494 | // SAFETY: |
1495 | // `Self::BITS-1` is guaranteed to be less than `Self::BITS` |
1496 | unsafe { self.unchecked_shr(Self::BITS - 1) } |
1497 | } |
1498 | } |
1499 | |
1500 | /// Checked absolute value. Computes `self.abs()`, returning `None` if |
1501 | /// `self == MIN`. |
1502 | /// |
1503 | /// # Examples |
1504 | /// |
1505 | /// Basic usage: |
1506 | /// |
1507 | /// ``` |
1508 | #[doc = concat!("assert_eq!((-5" , stringify!($SelfT), ").checked_abs(), Some(5));" )] |
1509 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MIN.checked_abs(), None);" )] |
1510 | /// ``` |
1511 | #[stable(feature = "no_panic_abs" , since = "1.13.0" )] |
1512 | #[rustc_const_stable(feature = "const_checked_int_methods" , since = "1.47.0" )] |
1513 | #[must_use = "this returns the result of the operation, \ |
1514 | without modifying the original" ] |
1515 | #[inline] |
1516 | pub const fn checked_abs(self) -> Option<Self> { |
1517 | if self.is_negative() { |
1518 | self.checked_neg() |
1519 | } else { |
1520 | Some(self) |
1521 | } |
1522 | } |
1523 | |
1524 | /// Strict absolute value. Computes `self.abs()`, panicking if |
1525 | /// `self == MIN`. |
1526 | /// |
1527 | /// # Panics |
1528 | /// |
1529 | /// ## Overflow behavior |
1530 | /// |
1531 | /// This function will always panic on overflow, regardless of whether overflow checks are enabled. |
1532 | /// |
1533 | /// # Examples |
1534 | /// |
1535 | /// Basic usage: |
1536 | /// |
1537 | /// ``` |
1538 | /// #![feature(strict_overflow_ops)] |
1539 | #[doc = concat!("assert_eq!((-5" , stringify!($SelfT), ").strict_abs(), 5);" )] |
1540 | /// ``` |
1541 | /// |
1542 | /// The following panics because of overflow: |
1543 | /// |
1544 | /// ```should_panic |
1545 | /// #![feature(strict_overflow_ops)] |
1546 | #[doc = concat!("let _ = " , stringify!($SelfT), "::MIN.strict_abs();" )] |
1547 | /// ``` |
1548 | #[unstable(feature = "strict_overflow_ops" , issue = "118260" )] |
1549 | #[must_use = "this returns the result of the operation, \ |
1550 | without modifying the original" ] |
1551 | #[inline] |
1552 | #[track_caller] |
1553 | pub const fn strict_abs(self) -> Self { |
1554 | if self.is_negative() { |
1555 | self.strict_neg() |
1556 | } else { |
1557 | self |
1558 | } |
1559 | } |
1560 | |
1561 | /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if |
1562 | /// overflow occurred. |
1563 | /// |
1564 | /// # Examples |
1565 | /// |
1566 | /// Basic usage: |
1567 | /// |
1568 | /// ``` |
1569 | #[doc = concat!("assert_eq!(8" , stringify!($SelfT), ".checked_pow(2), Some(64));" )] |
1570 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MAX.checked_pow(2), None);" )] |
1571 | /// ``` |
1572 | |
1573 | #[stable(feature = "no_panic_pow" , since = "1.34.0" )] |
1574 | #[rustc_const_stable(feature = "const_int_pow" , since = "1.50.0" )] |
1575 | #[must_use = "this returns the result of the operation, \ |
1576 | without modifying the original" ] |
1577 | #[inline] |
1578 | pub const fn checked_pow(self, mut exp: u32) -> Option<Self> { |
1579 | if exp == 0 { |
1580 | return Some(1); |
1581 | } |
1582 | let mut base = self; |
1583 | let mut acc: Self = 1; |
1584 | |
1585 | loop { |
1586 | if (exp & 1) == 1 { |
1587 | acc = try_opt!(acc.checked_mul(base)); |
1588 | // since exp!=0, finally the exp must be 1. |
1589 | if exp == 1 { |
1590 | return Some(acc); |
1591 | } |
1592 | } |
1593 | exp /= 2; |
1594 | base = try_opt!(base.checked_mul(base)); |
1595 | } |
1596 | } |
1597 | |
1598 | /// Strict exponentiation. Computes `self.pow(exp)`, panicking if |
1599 | /// overflow occurred. |
1600 | /// |
1601 | /// # Panics |
1602 | /// |
1603 | /// ## Overflow behavior |
1604 | /// |
1605 | /// This function will always panic on overflow, regardless of whether overflow checks are enabled. |
1606 | /// |
1607 | /// # Examples |
1608 | /// |
1609 | /// Basic usage: |
1610 | /// |
1611 | /// ``` |
1612 | /// #![feature(strict_overflow_ops)] |
1613 | #[doc = concat!("assert_eq!(8" , stringify!($SelfT), ".strict_pow(2), 64);" )] |
1614 | /// ``` |
1615 | /// |
1616 | /// The following panics because of overflow: |
1617 | /// |
1618 | /// ```should_panic |
1619 | /// #![feature(strict_overflow_ops)] |
1620 | #[doc = concat!("let _ = " , stringify!($SelfT), "::MAX.strict_pow(2);" )] |
1621 | /// ``` |
1622 | #[unstable(feature = "strict_overflow_ops" , issue = "118260" )] |
1623 | #[must_use = "this returns the result of the operation, \ |
1624 | without modifying the original" ] |
1625 | #[inline] |
1626 | #[track_caller] |
1627 | pub const fn strict_pow(self, mut exp: u32) -> Self { |
1628 | if exp == 0 { |
1629 | return 1; |
1630 | } |
1631 | let mut base = self; |
1632 | let mut acc: Self = 1; |
1633 | |
1634 | loop { |
1635 | if (exp & 1) == 1 { |
1636 | acc = acc.strict_mul(base); |
1637 | // since exp!=0, finally the exp must be 1. |
1638 | if exp == 1 { |
1639 | return acc; |
1640 | } |
1641 | } |
1642 | exp /= 2; |
1643 | base = base.strict_mul(base); |
1644 | } |
1645 | } |
1646 | |
1647 | /// Returns the square root of the number, rounded down. |
1648 | /// |
1649 | /// Returns `None` if `self` is negative. |
1650 | /// |
1651 | /// # Examples |
1652 | /// |
1653 | /// Basic usage: |
1654 | /// ``` |
1655 | #[doc = concat!("assert_eq!(10" , stringify!($SelfT), ".checked_isqrt(), Some(3));" )] |
1656 | /// ``` |
1657 | #[stable(feature = "isqrt" , since = "1.84.0" )] |
1658 | #[rustc_const_stable(feature = "isqrt" , since = "1.84.0" )] |
1659 | #[must_use = "this returns the result of the operation, \ |
1660 | without modifying the original" ] |
1661 | #[inline] |
1662 | pub const fn checked_isqrt(self) -> Option<Self> { |
1663 | if self < 0 { |
1664 | None |
1665 | } else { |
1666 | // SAFETY: Input is nonnegative in this `else` branch. |
1667 | let result = unsafe { |
1668 | crate::num::int_sqrt::$ActualT(self as $ActualT) as $SelfT |
1669 | }; |
1670 | |
1671 | // Inform the optimizer what the range of outputs is. If |
1672 | // testing `core` crashes with no panic message and a |
1673 | // `num::int_sqrt::i*` test failed, it's because your edits |
1674 | // caused these assertions to become false. |
1675 | // |
1676 | // SAFETY: Integer square root is a monotonically nondecreasing |
1677 | // function, which means that increasing the input will never |
1678 | // cause the output to decrease. Thus, since the input for |
1679 | // nonnegative signed integers is bounded by |
1680 | // `[0, <$ActualT>::MAX]`, sqrt(n) will be bounded by |
1681 | // `[sqrt(0), sqrt(<$ActualT>::MAX)]`. |
1682 | unsafe { |
1683 | // SAFETY: `<$ActualT>::MAX` is nonnegative. |
1684 | const MAX_RESULT: $SelfT = unsafe { |
1685 | crate::num::int_sqrt::$ActualT(<$ActualT>::MAX) as $SelfT |
1686 | }; |
1687 | |
1688 | crate::hint::assert_unchecked(result >= 0); |
1689 | crate::hint::assert_unchecked(result <= MAX_RESULT); |
1690 | } |
1691 | |
1692 | Some(result) |
1693 | } |
1694 | } |
1695 | |
1696 | /// Saturating integer addition. Computes `self + rhs`, saturating at the numeric |
1697 | /// bounds instead of overflowing. |
1698 | /// |
1699 | /// # Examples |
1700 | /// |
1701 | /// Basic usage: |
1702 | /// |
1703 | /// ``` |
1704 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".saturating_add(1), 101);" )] |
1705 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MAX.saturating_add(100), " , stringify!($SelfT), "::MAX);" )] |
1706 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MIN.saturating_add(-1), " , stringify!($SelfT), "::MIN);" )] |
1707 | /// ``` |
1708 | |
1709 | #[stable(feature = "rust1" , since = "1.0.0" )] |
1710 | #[rustc_const_stable(feature = "const_saturating_int_methods" , since = "1.47.0" )] |
1711 | #[must_use = "this returns the result of the operation, \ |
1712 | without modifying the original" ] |
1713 | #[inline(always)] |
1714 | pub const fn saturating_add(self, rhs: Self) -> Self { |
1715 | intrinsics::saturating_add(self, rhs) |
1716 | } |
1717 | |
1718 | /// Saturating addition with an unsigned integer. Computes `self + rhs`, |
1719 | /// saturating at the numeric bounds instead of overflowing. |
1720 | /// |
1721 | /// # Examples |
1722 | /// |
1723 | /// Basic usage: |
1724 | /// |
1725 | /// ``` |
1726 | #[doc = concat!("assert_eq!(1" , stringify!($SelfT), ".saturating_add_unsigned(2), 3);" )] |
1727 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MAX.saturating_add_unsigned(100), " , stringify!($SelfT), "::MAX);" )] |
1728 | /// ``` |
1729 | #[stable(feature = "mixed_integer_ops" , since = "1.66.0" )] |
1730 | #[rustc_const_stable(feature = "mixed_integer_ops" , since = "1.66.0" )] |
1731 | #[must_use = "this returns the result of the operation, \ |
1732 | without modifying the original" ] |
1733 | #[inline] |
1734 | pub const fn saturating_add_unsigned(self, rhs: $UnsignedT) -> Self { |
1735 | // Overflow can only happen at the upper bound |
1736 | // We cannot use `unwrap_or` here because it is not `const` |
1737 | match self.checked_add_unsigned(rhs) { |
1738 | Some(x) => x, |
1739 | None => Self::MAX, |
1740 | } |
1741 | } |
1742 | |
1743 | /// Saturating integer subtraction. Computes `self - rhs`, saturating at the |
1744 | /// numeric bounds instead of overflowing. |
1745 | /// |
1746 | /// # Examples |
1747 | /// |
1748 | /// Basic usage: |
1749 | /// |
1750 | /// ``` |
1751 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".saturating_sub(127), -27);" )] |
1752 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MIN.saturating_sub(100), " , stringify!($SelfT), "::MIN);" )] |
1753 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MAX.saturating_sub(-1), " , stringify!($SelfT), "::MAX);" )] |
1754 | /// ``` |
1755 | #[stable(feature = "rust1" , since = "1.0.0" )] |
1756 | #[rustc_const_stable(feature = "const_saturating_int_methods" , since = "1.47.0" )] |
1757 | #[must_use = "this returns the result of the operation, \ |
1758 | without modifying the original" ] |
1759 | #[inline(always)] |
1760 | pub const fn saturating_sub(self, rhs: Self) -> Self { |
1761 | intrinsics::saturating_sub(self, rhs) |
1762 | } |
1763 | |
1764 | /// Saturating subtraction with an unsigned integer. Computes `self - rhs`, |
1765 | /// saturating at the numeric bounds instead of overflowing. |
1766 | /// |
1767 | /// # Examples |
1768 | /// |
1769 | /// Basic usage: |
1770 | /// |
1771 | /// ``` |
1772 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".saturating_sub_unsigned(127), -27);" )] |
1773 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MIN.saturating_sub_unsigned(100), " , stringify!($SelfT), "::MIN);" )] |
1774 | /// ``` |
1775 | #[stable(feature = "mixed_integer_ops" , since = "1.66.0" )] |
1776 | #[rustc_const_stable(feature = "mixed_integer_ops" , since = "1.66.0" )] |
1777 | #[must_use = "this returns the result of the operation, \ |
1778 | without modifying the original" ] |
1779 | #[inline] |
1780 | pub const fn saturating_sub_unsigned(self, rhs: $UnsignedT) -> Self { |
1781 | // Overflow can only happen at the lower bound |
1782 | // We cannot use `unwrap_or` here because it is not `const` |
1783 | match self.checked_sub_unsigned(rhs) { |
1784 | Some(x) => x, |
1785 | None => Self::MIN, |
1786 | } |
1787 | } |
1788 | |
1789 | /// Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN` |
1790 | /// instead of overflowing. |
1791 | /// |
1792 | /// # Examples |
1793 | /// |
1794 | /// Basic usage: |
1795 | /// |
1796 | /// ``` |
1797 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".saturating_neg(), -100);" )] |
1798 | #[doc = concat!("assert_eq!((-100" , stringify!($SelfT), ").saturating_neg(), 100);" )] |
1799 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MIN.saturating_neg(), " , stringify!($SelfT), "::MAX);" )] |
1800 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MAX.saturating_neg(), " , stringify!($SelfT), "::MIN + 1);" )] |
1801 | /// ``` |
1802 | |
1803 | #[stable(feature = "saturating_neg" , since = "1.45.0" )] |
1804 | #[rustc_const_stable(feature = "const_saturating_int_methods" , since = "1.47.0" )] |
1805 | #[must_use = "this returns the result of the operation, \ |
1806 | without modifying the original" ] |
1807 | #[inline(always)] |
1808 | pub const fn saturating_neg(self) -> Self { |
1809 | intrinsics::saturating_sub(0, self) |
1810 | } |
1811 | |
1812 | /// Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self == |
1813 | /// MIN` instead of overflowing. |
1814 | /// |
1815 | /// # Examples |
1816 | /// |
1817 | /// Basic usage: |
1818 | /// |
1819 | /// ``` |
1820 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".saturating_abs(), 100);" )] |
1821 | #[doc = concat!("assert_eq!((-100" , stringify!($SelfT), ").saturating_abs(), 100);" )] |
1822 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MIN.saturating_abs(), " , stringify!($SelfT), "::MAX);" )] |
1823 | #[doc = concat!("assert_eq!((" , stringify!($SelfT), "::MIN + 1).saturating_abs(), " , stringify!($SelfT), "::MAX);" )] |
1824 | /// ``` |
1825 | |
1826 | #[stable(feature = "saturating_neg" , since = "1.45.0" )] |
1827 | #[rustc_const_stable(feature = "const_saturating_int_methods" , since = "1.47.0" )] |
1828 | #[must_use = "this returns the result of the operation, \ |
1829 | without modifying the original" ] |
1830 | #[inline] |
1831 | pub const fn saturating_abs(self) -> Self { |
1832 | if self.is_negative() { |
1833 | self.saturating_neg() |
1834 | } else { |
1835 | self |
1836 | } |
1837 | } |
1838 | |
1839 | /// Saturating integer multiplication. Computes `self * rhs`, saturating at the |
1840 | /// numeric bounds instead of overflowing. |
1841 | /// |
1842 | /// # Examples |
1843 | /// |
1844 | /// Basic usage: |
1845 | /// |
1846 | /// ``` |
1847 | #[doc = concat!("assert_eq!(10" , stringify!($SelfT), ".saturating_mul(12), 120);" )] |
1848 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MAX.saturating_mul(10), " , stringify!($SelfT), "::MAX);" )] |
1849 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MIN.saturating_mul(10), " , stringify!($SelfT), "::MIN);" )] |
1850 | /// ``` |
1851 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
1852 | #[rustc_const_stable(feature = "const_saturating_int_methods" , since = "1.47.0" )] |
1853 | #[must_use = "this returns the result of the operation, \ |
1854 | without modifying the original" ] |
1855 | #[inline] |
1856 | pub const fn saturating_mul(self, rhs: Self) -> Self { |
1857 | match self.checked_mul(rhs) { |
1858 | Some(x) => x, |
1859 | None => if (self < 0) == (rhs < 0) { |
1860 | Self::MAX |
1861 | } else { |
1862 | Self::MIN |
1863 | } |
1864 | } |
1865 | } |
1866 | |
1867 | /// Saturating integer division. Computes `self / rhs`, saturating at the |
1868 | /// numeric bounds instead of overflowing. |
1869 | /// |
1870 | /// # Panics |
1871 | /// |
1872 | /// This function will panic if `rhs` is zero. |
1873 | /// |
1874 | /// # Examples |
1875 | /// |
1876 | /// Basic usage: |
1877 | /// |
1878 | /// ``` |
1879 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".saturating_div(2), 2);" )] |
1880 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MAX.saturating_div(-1), " , stringify!($SelfT), "::MIN + 1);" )] |
1881 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MIN.saturating_div(-1), " , stringify!($SelfT), "::MAX);" )] |
1882 | /// |
1883 | /// ``` |
1884 | #[stable(feature = "saturating_div" , since = "1.58.0" )] |
1885 | #[rustc_const_stable(feature = "saturating_div" , since = "1.58.0" )] |
1886 | #[must_use = "this returns the result of the operation, \ |
1887 | without modifying the original" ] |
1888 | #[inline] |
1889 | pub const fn saturating_div(self, rhs: Self) -> Self { |
1890 | match self.overflowing_div(rhs) { |
1891 | (result, false) => result, |
1892 | (_result, true) => Self::MAX, // MIN / -1 is the only possible saturating overflow |
1893 | } |
1894 | } |
1895 | |
1896 | /// Saturating integer exponentiation. Computes `self.pow(exp)`, |
1897 | /// saturating at the numeric bounds instead of overflowing. |
1898 | /// |
1899 | /// # Examples |
1900 | /// |
1901 | /// Basic usage: |
1902 | /// |
1903 | /// ``` |
1904 | #[doc = concat!("assert_eq!((-4" , stringify!($SelfT), ").saturating_pow(3), -64);" )] |
1905 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MIN.saturating_pow(2), " , stringify!($SelfT), "::MAX);" )] |
1906 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MIN.saturating_pow(3), " , stringify!($SelfT), "::MIN);" )] |
1907 | /// ``` |
1908 | #[stable(feature = "no_panic_pow" , since = "1.34.0" )] |
1909 | #[rustc_const_stable(feature = "const_int_pow" , since = "1.50.0" )] |
1910 | #[must_use = "this returns the result of the operation, \ |
1911 | without modifying the original" ] |
1912 | #[inline] |
1913 | pub const fn saturating_pow(self, exp: u32) -> Self { |
1914 | match self.checked_pow(exp) { |
1915 | Some(x) => x, |
1916 | None if self < 0 && exp % 2 == 1 => Self::MIN, |
1917 | None => Self::MAX, |
1918 | } |
1919 | } |
1920 | |
1921 | /// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the |
1922 | /// boundary of the type. |
1923 | /// |
1924 | /// # Examples |
1925 | /// |
1926 | /// Basic usage: |
1927 | /// |
1928 | /// ``` |
1929 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".wrapping_add(27), 127);" )] |
1930 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MAX.wrapping_add(2), " , stringify!($SelfT), "::MIN + 1);" )] |
1931 | /// ``` |
1932 | #[stable(feature = "rust1" , since = "1.0.0" )] |
1933 | #[rustc_const_stable(feature = "const_int_methods" , since = "1.32.0" )] |
1934 | #[must_use = "this returns the result of the operation, \ |
1935 | without modifying the original" ] |
1936 | #[inline(always)] |
1937 | pub const fn wrapping_add(self, rhs: Self) -> Self { |
1938 | intrinsics::wrapping_add(self, rhs) |
1939 | } |
1940 | |
1941 | /// Wrapping (modular) addition with an unsigned integer. Computes |
1942 | /// `self + rhs`, wrapping around at the boundary of the type. |
1943 | /// |
1944 | /// # Examples |
1945 | /// |
1946 | /// Basic usage: |
1947 | /// |
1948 | /// ``` |
1949 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".wrapping_add_unsigned(27), 127);" )] |
1950 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MAX.wrapping_add_unsigned(2), " , stringify!($SelfT), "::MIN + 1);" )] |
1951 | /// ``` |
1952 | #[stable(feature = "mixed_integer_ops" , since = "1.66.0" )] |
1953 | #[rustc_const_stable(feature = "mixed_integer_ops" , since = "1.66.0" )] |
1954 | #[must_use = "this returns the result of the operation, \ |
1955 | without modifying the original" ] |
1956 | #[inline(always)] |
1957 | pub const fn wrapping_add_unsigned(self, rhs: $UnsignedT) -> Self { |
1958 | self.wrapping_add(rhs as Self) |
1959 | } |
1960 | |
1961 | /// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the |
1962 | /// boundary of the type. |
1963 | /// |
1964 | /// # Examples |
1965 | /// |
1966 | /// Basic usage: |
1967 | /// |
1968 | /// ``` |
1969 | #[doc = concat!("assert_eq!(0" , stringify!($SelfT), ".wrapping_sub(127), -127);" )] |
1970 | #[doc = concat!("assert_eq!((-2" , stringify!($SelfT), ").wrapping_sub(" , stringify!($SelfT), "::MAX), " , stringify!($SelfT), "::MAX);" )] |
1971 | /// ``` |
1972 | #[stable(feature = "rust1" , since = "1.0.0" )] |
1973 | #[rustc_const_stable(feature = "const_int_methods" , since = "1.32.0" )] |
1974 | #[must_use = "this returns the result of the operation, \ |
1975 | without modifying the original" ] |
1976 | #[inline(always)] |
1977 | pub const fn wrapping_sub(self, rhs: Self) -> Self { |
1978 | intrinsics::wrapping_sub(self, rhs) |
1979 | } |
1980 | |
1981 | /// Wrapping (modular) subtraction with an unsigned integer. Computes |
1982 | /// `self - rhs`, wrapping around at the boundary of the type. |
1983 | /// |
1984 | /// # Examples |
1985 | /// |
1986 | /// Basic usage: |
1987 | /// |
1988 | /// ``` |
1989 | #[doc = concat!("assert_eq!(0" , stringify!($SelfT), ".wrapping_sub_unsigned(127), -127);" )] |
1990 | #[doc = concat!("assert_eq!((-2" , stringify!($SelfT), ").wrapping_sub_unsigned(" , stringify!($UnsignedT), "::MAX), -1);" )] |
1991 | /// ``` |
1992 | #[stable(feature = "mixed_integer_ops" , since = "1.66.0" )] |
1993 | #[rustc_const_stable(feature = "mixed_integer_ops" , since = "1.66.0" )] |
1994 | #[must_use = "this returns the result of the operation, \ |
1995 | without modifying the original" ] |
1996 | #[inline(always)] |
1997 | pub const fn wrapping_sub_unsigned(self, rhs: $UnsignedT) -> Self { |
1998 | self.wrapping_sub(rhs as Self) |
1999 | } |
2000 | |
2001 | /// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at |
2002 | /// the boundary of the type. |
2003 | /// |
2004 | /// # Examples |
2005 | /// |
2006 | /// Basic usage: |
2007 | /// |
2008 | /// ``` |
2009 | #[doc = concat!("assert_eq!(10" , stringify!($SelfT), ".wrapping_mul(12), 120);" )] |
2010 | /// assert_eq!(11i8.wrapping_mul(12), -124); |
2011 | /// ``` |
2012 | #[stable(feature = "rust1" , since = "1.0.0" )] |
2013 | #[rustc_const_stable(feature = "const_int_methods" , since = "1.32.0" )] |
2014 | #[must_use = "this returns the result of the operation, \ |
2015 | without modifying the original" ] |
2016 | #[inline(always)] |
2017 | pub const fn wrapping_mul(self, rhs: Self) -> Self { |
2018 | intrinsics::wrapping_mul(self, rhs) |
2019 | } |
2020 | |
2021 | /// Wrapping (modular) division. Computes `self / rhs`, wrapping around at the |
2022 | /// boundary of the type. |
2023 | /// |
2024 | /// The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where |
2025 | /// `MIN` is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value |
2026 | /// that is too large to represent in the type. In such a case, this function returns `MIN` itself. |
2027 | /// |
2028 | /// # Panics |
2029 | /// |
2030 | /// This function will panic if `rhs` is zero. |
2031 | /// |
2032 | /// # Examples |
2033 | /// |
2034 | /// Basic usage: |
2035 | /// |
2036 | /// ``` |
2037 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".wrapping_div(10), 10);" )] |
2038 | /// assert_eq!((-128i8).wrapping_div(-1), -128); |
2039 | /// ``` |
2040 | #[stable(feature = "num_wrapping" , since = "1.2.0" )] |
2041 | #[rustc_const_stable(feature = "const_wrapping_int_methods" , since = "1.52.0" )] |
2042 | #[must_use = "this returns the result of the operation, \ |
2043 | without modifying the original" ] |
2044 | #[inline] |
2045 | pub const fn wrapping_div(self, rhs: Self) -> Self { |
2046 | self.overflowing_div(rhs).0 |
2047 | } |
2048 | |
2049 | /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`, |
2050 | /// wrapping around at the boundary of the type. |
2051 | /// |
2052 | /// Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is the negative minimal value |
2053 | /// for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the |
2054 | /// type. In this case, this method returns `MIN` itself. |
2055 | /// |
2056 | /// # Panics |
2057 | /// |
2058 | /// This function will panic if `rhs` is zero. |
2059 | /// |
2060 | /// # Examples |
2061 | /// |
2062 | /// Basic usage: |
2063 | /// |
2064 | /// ``` |
2065 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".wrapping_div_euclid(10), 10);" )] |
2066 | /// assert_eq!((-128i8).wrapping_div_euclid(-1), -128); |
2067 | /// ``` |
2068 | #[stable(feature = "euclidean_division" , since = "1.38.0" )] |
2069 | #[rustc_const_stable(feature = "const_euclidean_int_methods" , since = "1.52.0" )] |
2070 | #[must_use = "this returns the result of the operation, \ |
2071 | without modifying the original" ] |
2072 | #[inline] |
2073 | pub const fn wrapping_div_euclid(self, rhs: Self) -> Self { |
2074 | self.overflowing_div_euclid(rhs).0 |
2075 | } |
2076 | |
2077 | /// Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the |
2078 | /// boundary of the type. |
2079 | /// |
2080 | /// Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y` |
2081 | /// invalid for `MIN / -1` on a signed type (where `MIN` is the negative minimal value). In such a case, |
2082 | /// this function returns `0`. |
2083 | /// |
2084 | /// # Panics |
2085 | /// |
2086 | /// This function will panic if `rhs` is zero. |
2087 | /// |
2088 | /// # Examples |
2089 | /// |
2090 | /// Basic usage: |
2091 | /// |
2092 | /// ``` |
2093 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".wrapping_rem(10), 0);" )] |
2094 | /// assert_eq!((-128i8).wrapping_rem(-1), 0); |
2095 | /// ``` |
2096 | #[stable(feature = "num_wrapping" , since = "1.2.0" )] |
2097 | #[rustc_const_stable(feature = "const_wrapping_int_methods" , since = "1.52.0" )] |
2098 | #[must_use = "this returns the result of the operation, \ |
2099 | without modifying the original" ] |
2100 | #[inline] |
2101 | pub const fn wrapping_rem(self, rhs: Self) -> Self { |
2102 | self.overflowing_rem(rhs).0 |
2103 | } |
2104 | |
2105 | /// Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around |
2106 | /// at the boundary of the type. |
2107 | /// |
2108 | /// Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is the negative minimal value |
2109 | /// for the type). In this case, this method returns 0. |
2110 | /// |
2111 | /// # Panics |
2112 | /// |
2113 | /// This function will panic if `rhs` is zero. |
2114 | /// |
2115 | /// # Examples |
2116 | /// |
2117 | /// Basic usage: |
2118 | /// |
2119 | /// ``` |
2120 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".wrapping_rem_euclid(10), 0);" )] |
2121 | /// assert_eq!((-128i8).wrapping_rem_euclid(-1), 0); |
2122 | /// ``` |
2123 | #[stable(feature = "euclidean_division" , since = "1.38.0" )] |
2124 | #[rustc_const_stable(feature = "const_euclidean_int_methods" , since = "1.52.0" )] |
2125 | #[must_use = "this returns the result of the operation, \ |
2126 | without modifying the original" ] |
2127 | #[inline] |
2128 | pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self { |
2129 | self.overflowing_rem_euclid(rhs).0 |
2130 | } |
2131 | |
2132 | /// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary |
2133 | /// of the type. |
2134 | /// |
2135 | /// The only case where such wrapping can occur is when one negates `MIN` on a signed type (where `MIN` |
2136 | /// is the negative minimal value for the type); this is a positive value that is too large to represent |
2137 | /// in the type. In such a case, this function returns `MIN` itself. |
2138 | /// |
2139 | /// # Examples |
2140 | /// |
2141 | /// Basic usage: |
2142 | /// |
2143 | /// ``` |
2144 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".wrapping_neg(), -100);" )] |
2145 | #[doc = concat!("assert_eq!((-100" , stringify!($SelfT), ").wrapping_neg(), 100);" )] |
2146 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MIN.wrapping_neg(), " , stringify!($SelfT), "::MIN);" )] |
2147 | /// ``` |
2148 | #[stable(feature = "num_wrapping" , since = "1.2.0" )] |
2149 | #[rustc_const_stable(feature = "const_int_methods" , since = "1.32.0" )] |
2150 | #[must_use = "this returns the result of the operation, \ |
2151 | without modifying the original" ] |
2152 | #[inline(always)] |
2153 | pub const fn wrapping_neg(self) -> Self { |
2154 | (0 as $SelfT).wrapping_sub(self) |
2155 | } |
2156 | |
2157 | /// Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes |
2158 | /// any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type. |
2159 | /// |
2160 | /// Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to |
2161 | /// the range of the type, rather than the bits shifted out of the LHS being returned to the other end. |
2162 | /// The primitive integer types all implement a [`rotate_left`](Self::rotate_left) function, |
2163 | /// which may be what you want instead. |
2164 | /// |
2165 | /// # Examples |
2166 | /// |
2167 | /// Basic usage: |
2168 | /// |
2169 | /// ``` |
2170 | #[doc = concat!("assert_eq!((-1" , stringify!($SelfT), ").wrapping_shl(7), -128);" )] |
2171 | #[doc = concat!("assert_eq!((-1" , stringify!($SelfT), ").wrapping_shl(128), -1);" )] |
2172 | /// ``` |
2173 | #[stable(feature = "num_wrapping" , since = "1.2.0" )] |
2174 | #[rustc_const_stable(feature = "const_int_methods" , since = "1.32.0" )] |
2175 | #[must_use = "this returns the result of the operation, \ |
2176 | without modifying the original" ] |
2177 | #[inline(always)] |
2178 | pub const fn wrapping_shl(self, rhs: u32) -> Self { |
2179 | // SAFETY: the masking by the bitsize of the type ensures that we do not shift |
2180 | // out of bounds |
2181 | unsafe { |
2182 | self.unchecked_shl(rhs & (Self::BITS - 1)) |
2183 | } |
2184 | } |
2185 | |
2186 | /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask` |
2187 | /// removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type. |
2188 | /// |
2189 | /// Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted |
2190 | /// to the range of the type, rather than the bits shifted out of the LHS being returned to the other |
2191 | /// end. The primitive integer types all implement a [`rotate_right`](Self::rotate_right) function, |
2192 | /// which may be what you want instead. |
2193 | /// |
2194 | /// # Examples |
2195 | /// |
2196 | /// Basic usage: |
2197 | /// |
2198 | /// ``` |
2199 | #[doc = concat!("assert_eq!((-128" , stringify!($SelfT), ").wrapping_shr(7), -1);" )] |
2200 | /// assert_eq!((-128i16).wrapping_shr(64), -128); |
2201 | /// ``` |
2202 | #[stable(feature = "num_wrapping" , since = "1.2.0" )] |
2203 | #[rustc_const_stable(feature = "const_int_methods" , since = "1.32.0" )] |
2204 | #[must_use = "this returns the result of the operation, \ |
2205 | without modifying the original" ] |
2206 | #[inline(always)] |
2207 | pub const fn wrapping_shr(self, rhs: u32) -> Self { |
2208 | // SAFETY: the masking by the bitsize of the type ensures that we do not shift |
2209 | // out of bounds |
2210 | unsafe { |
2211 | self.unchecked_shr(rhs & (Self::BITS - 1)) |
2212 | } |
2213 | } |
2214 | |
2215 | /// Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at |
2216 | /// the boundary of the type. |
2217 | /// |
2218 | /// The only case where such wrapping can occur is when one takes the absolute value of the negative |
2219 | /// minimal value for the type; this is a positive value that is too large to represent in the type. In |
2220 | /// such a case, this function returns `MIN` itself. |
2221 | /// |
2222 | /// # Examples |
2223 | /// |
2224 | /// Basic usage: |
2225 | /// |
2226 | /// ``` |
2227 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".wrapping_abs(), 100);" )] |
2228 | #[doc = concat!("assert_eq!((-100" , stringify!($SelfT), ").wrapping_abs(), 100);" )] |
2229 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MIN.wrapping_abs(), " , stringify!($SelfT), "::MIN);" )] |
2230 | /// assert_eq!((-128i8).wrapping_abs() as u8, 128); |
2231 | /// ``` |
2232 | #[stable(feature = "no_panic_abs" , since = "1.13.0" )] |
2233 | #[rustc_const_stable(feature = "const_int_methods" , since = "1.32.0" )] |
2234 | #[must_use = "this returns the result of the operation, \ |
2235 | without modifying the original" ] |
2236 | #[allow(unused_attributes)] |
2237 | #[inline] |
2238 | pub const fn wrapping_abs(self) -> Self { |
2239 | if self.is_negative() { |
2240 | self.wrapping_neg() |
2241 | } else { |
2242 | self |
2243 | } |
2244 | } |
2245 | |
2246 | /// Computes the absolute value of `self` without any wrapping |
2247 | /// or panicking. |
2248 | /// |
2249 | /// |
2250 | /// # Examples |
2251 | /// |
2252 | /// Basic usage: |
2253 | /// |
2254 | /// ``` |
2255 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".unsigned_abs(), 100" , stringify!($UnsignedT), ");" )] |
2256 | #[doc = concat!("assert_eq!((-100" , stringify!($SelfT), ").unsigned_abs(), 100" , stringify!($UnsignedT), ");" )] |
2257 | /// assert_eq!((-128i8).unsigned_abs(), 128u8); |
2258 | /// ``` |
2259 | #[stable(feature = "unsigned_abs" , since = "1.51.0" )] |
2260 | #[rustc_const_stable(feature = "unsigned_abs" , since = "1.51.0" )] |
2261 | #[must_use = "this returns the result of the operation, \ |
2262 | without modifying the original" ] |
2263 | #[inline] |
2264 | pub const fn unsigned_abs(self) -> $UnsignedT { |
2265 | self.wrapping_abs() as $UnsignedT |
2266 | } |
2267 | |
2268 | /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`, |
2269 | /// wrapping around at the boundary of the type. |
2270 | /// |
2271 | /// # Examples |
2272 | /// |
2273 | /// Basic usage: |
2274 | /// |
2275 | /// ``` |
2276 | #[doc = concat!("assert_eq!(3" , stringify!($SelfT), ".wrapping_pow(4), 81);" )] |
2277 | /// assert_eq!(3i8.wrapping_pow(5), -13); |
2278 | /// assert_eq!(3i8.wrapping_pow(6), -39); |
2279 | /// ``` |
2280 | #[stable(feature = "no_panic_pow" , since = "1.34.0" )] |
2281 | #[rustc_const_stable(feature = "const_int_pow" , since = "1.50.0" )] |
2282 | #[must_use = "this returns the result of the operation, \ |
2283 | without modifying the original" ] |
2284 | #[inline] |
2285 | pub const fn wrapping_pow(self, mut exp: u32) -> Self { |
2286 | if exp == 0 { |
2287 | return 1; |
2288 | } |
2289 | let mut base = self; |
2290 | let mut acc: Self = 1; |
2291 | |
2292 | if intrinsics::is_val_statically_known(exp) { |
2293 | while exp > 1 { |
2294 | if (exp & 1) == 1 { |
2295 | acc = acc.wrapping_mul(base); |
2296 | } |
2297 | exp /= 2; |
2298 | base = base.wrapping_mul(base); |
2299 | } |
2300 | |
2301 | // since exp!=0, finally the exp must be 1. |
2302 | // Deal with the final bit of the exponent separately, since |
2303 | // squaring the base afterwards is not necessary. |
2304 | acc.wrapping_mul(base) |
2305 | } else { |
2306 | // This is faster than the above when the exponent is not known |
2307 | // at compile time. We can't use the same code for the constant |
2308 | // exponent case because LLVM is currently unable to unroll |
2309 | // this loop. |
2310 | loop { |
2311 | if (exp & 1) == 1 { |
2312 | acc = acc.wrapping_mul(base); |
2313 | // since exp!=0, finally the exp must be 1. |
2314 | if exp == 1 { |
2315 | return acc; |
2316 | } |
2317 | } |
2318 | exp /= 2; |
2319 | base = base.wrapping_mul(base); |
2320 | } |
2321 | } |
2322 | } |
2323 | |
2324 | /// Calculates `self` + `rhs`. |
2325 | /// |
2326 | /// Returns a tuple of the addition along with a boolean indicating |
2327 | /// whether an arithmetic overflow would occur. If an overflow would have |
2328 | /// occurred then the wrapped value is returned. |
2329 | /// |
2330 | /// # Examples |
2331 | /// |
2332 | /// Basic usage: |
2333 | /// |
2334 | /// ``` |
2335 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".overflowing_add(2), (7, false));" )] |
2336 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MAX.overflowing_add(1), (" , stringify!($SelfT), "::MIN, true));" )] |
2337 | /// ``` |
2338 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
2339 | #[rustc_const_stable(feature = "const_int_methods" , since = "1.32.0" )] |
2340 | #[must_use = "this returns the result of the operation, \ |
2341 | without modifying the original" ] |
2342 | #[inline(always)] |
2343 | pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) { |
2344 | let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT); |
2345 | (a as Self, b) |
2346 | } |
2347 | |
2348 | /// Calculates `self` + `rhs` + `carry` and checks for overflow. |
2349 | /// |
2350 | /// Performs "ternary addition" of two integer operands and a carry-in |
2351 | /// bit, and returns a tuple of the sum along with a boolean indicating |
2352 | /// whether an arithmetic overflow would occur. On overflow, the wrapped |
2353 | /// value is returned. |
2354 | /// |
2355 | /// This allows chaining together multiple additions to create a wider |
2356 | /// addition, and can be useful for bignum addition. This method should |
2357 | /// only be used for the most significant word; for the less significant |
2358 | /// words the unsigned method |
2359 | #[doc = concat!("[`" , stringify!($UnsignedT), "::carrying_add`]" )] |
2360 | /// should be used. |
2361 | /// |
2362 | /// The output boolean returned by this method is *not* a carry flag, |
2363 | /// and should *not* be added to a more significant word. |
2364 | /// |
2365 | /// If the input carry is false, this method is equivalent to |
2366 | /// [`overflowing_add`](Self::overflowing_add). |
2367 | /// |
2368 | /// # Examples |
2369 | /// |
2370 | /// ``` |
2371 | /// #![feature(bigint_helper_methods)] |
2372 | /// // Only the most significant word is signed. |
2373 | /// // |
2374 | #[doc = concat!("// 10 MAX (a = 10 × 2^" , stringify!($BITS), " + 2^" , stringify!($BITS), " - 1)" )] |
2375 | #[doc = concat!("// + -5 9 (b = -5 × 2^" , stringify!($BITS), " + 9)" )] |
2376 | /// // --------- |
2377 | #[doc = concat!("// 6 8 (sum = 6 × 2^" , stringify!($BITS), " + 8)" )] |
2378 | /// |
2379 | #[doc = concat!("let (a1, a0): (" , stringify!($SelfT), ", " , stringify!($UnsignedT), ") = (10, " , stringify!($UnsignedT), "::MAX);" )] |
2380 | #[doc = concat!("let (b1, b0): (" , stringify!($SelfT), ", " , stringify!($UnsignedT), ") = (-5, 9);" )] |
2381 | /// let carry0 = false; |
2382 | /// |
2383 | #[doc = concat!("// " , stringify!($UnsignedT), "::carrying_add for the less significant words" )] |
2384 | /// let (sum0, carry1) = a0.carrying_add(b0, carry0); |
2385 | /// assert_eq!(carry1, true); |
2386 | /// |
2387 | #[doc = concat!("// " , stringify!($SelfT), "::carrying_add for the most significant word" )] |
2388 | /// let (sum1, overflow) = a1.carrying_add(b1, carry1); |
2389 | /// assert_eq!(overflow, false); |
2390 | /// |
2391 | /// assert_eq!((sum1, sum0), (6, 8)); |
2392 | /// ``` |
2393 | #[unstable(feature = "bigint_helper_methods" , issue = "85532" )] |
2394 | #[must_use = "this returns the result of the operation, \ |
2395 | without modifying the original" ] |
2396 | #[inline] |
2397 | pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) { |
2398 | // note: longer-term this should be done via an intrinsic. |
2399 | // note: no intermediate overflow is required (https://github.com/rust-lang/rust/issues/85532#issuecomment-1032214946). |
2400 | let (a, b) = self.overflowing_add(rhs); |
2401 | let (c, d) = a.overflowing_add(carry as $SelfT); |
2402 | (c, b != d) |
2403 | } |
2404 | |
2405 | /// Calculates `self` + `rhs` with an unsigned `rhs`. |
2406 | /// |
2407 | /// Returns a tuple of the addition along with a boolean indicating |
2408 | /// whether an arithmetic overflow would occur. If an overflow would |
2409 | /// have occurred then the wrapped value is returned. |
2410 | /// |
2411 | /// # Examples |
2412 | /// |
2413 | /// Basic usage: |
2414 | /// |
2415 | /// ``` |
2416 | #[doc = concat!("assert_eq!(1" , stringify!($SelfT), ".overflowing_add_unsigned(2), (3, false));" )] |
2417 | #[doc = concat!("assert_eq!((" , stringify!($SelfT), "::MIN).overflowing_add_unsigned(" , stringify!($UnsignedT), "::MAX), (" , stringify!($SelfT), "::MAX, false));" )] |
2418 | #[doc = concat!("assert_eq!((" , stringify!($SelfT), "::MAX - 2).overflowing_add_unsigned(3), (" , stringify!($SelfT), "::MIN, true));" )] |
2419 | /// ``` |
2420 | #[stable(feature = "mixed_integer_ops" , since = "1.66.0" )] |
2421 | #[rustc_const_stable(feature = "mixed_integer_ops" , since = "1.66.0" )] |
2422 | #[must_use = "this returns the result of the operation, \ |
2423 | without modifying the original" ] |
2424 | #[inline] |
2425 | pub const fn overflowing_add_unsigned(self, rhs: $UnsignedT) -> (Self, bool) { |
2426 | let rhs = rhs as Self; |
2427 | let (res, overflowed) = self.overflowing_add(rhs); |
2428 | (res, overflowed ^ (rhs < 0)) |
2429 | } |
2430 | |
2431 | /// Calculates `self` - `rhs`. |
2432 | /// |
2433 | /// Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow |
2434 | /// would occur. If an overflow would have occurred then the wrapped value is returned. |
2435 | /// |
2436 | /// # Examples |
2437 | /// |
2438 | /// Basic usage: |
2439 | /// |
2440 | /// ``` |
2441 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".overflowing_sub(2), (3, false));" )] |
2442 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MIN.overflowing_sub(1), (" , stringify!($SelfT), "::MAX, true));" )] |
2443 | /// ``` |
2444 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
2445 | #[rustc_const_stable(feature = "const_int_methods" , since = "1.32.0" )] |
2446 | #[must_use = "this returns the result of the operation, \ |
2447 | without modifying the original" ] |
2448 | #[inline(always)] |
2449 | pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) { |
2450 | let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT); |
2451 | (a as Self, b) |
2452 | } |
2453 | |
2454 | /// Calculates `self` − `rhs` − `borrow` and checks for |
2455 | /// overflow. |
2456 | /// |
2457 | /// Performs "ternary subtraction" by subtracting both an integer |
2458 | /// operand and a borrow-in bit from `self`, and returns a tuple of the |
2459 | /// difference along with a boolean indicating whether an arithmetic |
2460 | /// overflow would occur. On overflow, the wrapped value is returned. |
2461 | /// |
2462 | /// This allows chaining together multiple subtractions to create a |
2463 | /// wider subtraction, and can be useful for bignum subtraction. This |
2464 | /// method should only be used for the most significant word; for the |
2465 | /// less significant words the unsigned method |
2466 | #[doc = concat!("[`" , stringify!($UnsignedT), "::borrowing_sub`]" )] |
2467 | /// should be used. |
2468 | /// |
2469 | /// The output boolean returned by this method is *not* a borrow flag, |
2470 | /// and should *not* be subtracted from a more significant word. |
2471 | /// |
2472 | /// If the input borrow is false, this method is equivalent to |
2473 | /// [`overflowing_sub`](Self::overflowing_sub). |
2474 | /// |
2475 | /// # Examples |
2476 | /// |
2477 | /// ``` |
2478 | /// #![feature(bigint_helper_methods)] |
2479 | /// // Only the most significant word is signed. |
2480 | /// // |
2481 | #[doc = concat!("// 6 8 (a = 6 × 2^" , stringify!($BITS), " + 8)" )] |
2482 | #[doc = concat!("// - -5 9 (b = -5 × 2^" , stringify!($BITS), " + 9)" )] |
2483 | /// // --------- |
2484 | #[doc = concat!("// 10 MAX (diff = 10 × 2^" , stringify!($BITS), " + 2^" , stringify!($BITS), " - 1)" )] |
2485 | /// |
2486 | #[doc = concat!("let (a1, a0): (" , stringify!($SelfT), ", " , stringify!($UnsignedT), ") = (6, 8);" )] |
2487 | #[doc = concat!("let (b1, b0): (" , stringify!($SelfT), ", " , stringify!($UnsignedT), ") = (-5, 9);" )] |
2488 | /// let borrow0 = false; |
2489 | /// |
2490 | #[doc = concat!("// " , stringify!($UnsignedT), "::borrowing_sub for the less significant words" )] |
2491 | /// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0); |
2492 | /// assert_eq!(borrow1, true); |
2493 | /// |
2494 | #[doc = concat!("// " , stringify!($SelfT), "::borrowing_sub for the most significant word" )] |
2495 | /// let (diff1, overflow) = a1.borrowing_sub(b1, borrow1); |
2496 | /// assert_eq!(overflow, false); |
2497 | /// |
2498 | #[doc = concat!("assert_eq!((diff1, diff0), (10, " , stringify!($UnsignedT), "::MAX));" )] |
2499 | /// ``` |
2500 | #[unstable(feature = "bigint_helper_methods" , issue = "85532" )] |
2501 | #[must_use = "this returns the result of the operation, \ |
2502 | without modifying the original" ] |
2503 | #[inline] |
2504 | pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) { |
2505 | // note: longer-term this should be done via an intrinsic. |
2506 | // note: no intermediate overflow is required (https://github.com/rust-lang/rust/issues/85532#issuecomment-1032214946). |
2507 | let (a, b) = self.overflowing_sub(rhs); |
2508 | let (c, d) = a.overflowing_sub(borrow as $SelfT); |
2509 | (c, b != d) |
2510 | } |
2511 | |
2512 | /// Calculates `self` - `rhs` with an unsigned `rhs`. |
2513 | /// |
2514 | /// Returns a tuple of the subtraction along with a boolean indicating |
2515 | /// whether an arithmetic overflow would occur. If an overflow would |
2516 | /// have occurred then the wrapped value is returned. |
2517 | /// |
2518 | /// # Examples |
2519 | /// |
2520 | /// Basic usage: |
2521 | /// |
2522 | /// ``` |
2523 | #[doc = concat!("assert_eq!(1" , stringify!($SelfT), ".overflowing_sub_unsigned(2), (-1, false));" )] |
2524 | #[doc = concat!("assert_eq!((" , stringify!($SelfT), "::MAX).overflowing_sub_unsigned(" , stringify!($UnsignedT), "::MAX), (" , stringify!($SelfT), "::MIN, false));" )] |
2525 | #[doc = concat!("assert_eq!((" , stringify!($SelfT), "::MIN + 2).overflowing_sub_unsigned(3), (" , stringify!($SelfT), "::MAX, true));" )] |
2526 | /// ``` |
2527 | #[stable(feature = "mixed_integer_ops" , since = "1.66.0" )] |
2528 | #[rustc_const_stable(feature = "mixed_integer_ops" , since = "1.66.0" )] |
2529 | #[must_use = "this returns the result of the operation, \ |
2530 | without modifying the original" ] |
2531 | #[inline] |
2532 | pub const fn overflowing_sub_unsigned(self, rhs: $UnsignedT) -> (Self, bool) { |
2533 | let rhs = rhs as Self; |
2534 | let (res, overflowed) = self.overflowing_sub(rhs); |
2535 | (res, overflowed ^ (rhs < 0)) |
2536 | } |
2537 | |
2538 | /// Calculates the multiplication of `self` and `rhs`. |
2539 | /// |
2540 | /// Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow |
2541 | /// would occur. If an overflow would have occurred then the wrapped value is returned. |
2542 | /// |
2543 | /// # Examples |
2544 | /// |
2545 | /// Basic usage: |
2546 | /// |
2547 | /// ``` |
2548 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".overflowing_mul(2), (10, false));" )] |
2549 | /// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true)); |
2550 | /// ``` |
2551 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
2552 | #[rustc_const_stable(feature = "const_int_methods" , since = "1.32.0" )] |
2553 | #[must_use = "this returns the result of the operation, \ |
2554 | without modifying the original" ] |
2555 | #[inline(always)] |
2556 | pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) { |
2557 | let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT); |
2558 | (a as Self, b) |
2559 | } |
2560 | |
2561 | /// Calculates the complete product `self * rhs` without the possibility to overflow. |
2562 | /// |
2563 | /// This returns the low-order (wrapping) bits and the high-order (overflow) bits |
2564 | /// of the result as two separate values, in that order. |
2565 | /// |
2566 | /// If you also need to add a carry to the wide result, then you want |
2567 | /// [`Self::carrying_mul`] instead. |
2568 | /// |
2569 | /// # Examples |
2570 | /// |
2571 | /// Basic usage: |
2572 | /// |
2573 | /// Please note that this example is shared between integer types. |
2574 | /// Which explains why `i32` is used here. |
2575 | /// |
2576 | /// ``` |
2577 | /// #![feature(bigint_helper_methods)] |
2578 | /// assert_eq!(5i32.widening_mul(-2), (4294967286, -1)); |
2579 | /// assert_eq!(1_000_000_000i32.widening_mul(-10), (2884901888, -3)); |
2580 | /// ``` |
2581 | #[unstable(feature = "bigint_helper_methods" , issue = "85532" )] |
2582 | #[rustc_const_unstable(feature = "bigint_helper_methods" , issue = "85532" )] |
2583 | #[must_use = "this returns the result of the operation, \ |
2584 | without modifying the original" ] |
2585 | #[inline] |
2586 | pub const fn widening_mul(self, rhs: Self) -> ($UnsignedT, Self) { |
2587 | Self::carrying_mul_add(self, rhs, 0, 0) |
2588 | } |
2589 | |
2590 | /// Calculates the "full multiplication" `self * rhs + carry` |
2591 | /// without the possibility to overflow. |
2592 | /// |
2593 | /// This returns the low-order (wrapping) bits and the high-order (overflow) bits |
2594 | /// of the result as two separate values, in that order. |
2595 | /// |
2596 | /// Performs "long multiplication" which takes in an extra amount to add, and may return an |
2597 | /// additional amount of overflow. This allows for chaining together multiple |
2598 | /// multiplications to create "big integers" which represent larger values. |
2599 | /// |
2600 | /// If you don't need the `carry`, then you can use [`Self::widening_mul`] instead. |
2601 | /// |
2602 | /// # Examples |
2603 | /// |
2604 | /// Basic usage: |
2605 | /// |
2606 | /// Please note that this example is shared between integer types. |
2607 | /// Which explains why `i32` is used here. |
2608 | /// |
2609 | /// ``` |
2610 | /// #![feature(bigint_helper_methods)] |
2611 | /// assert_eq!(5i32.carrying_mul(-2, 0), (4294967286, -1)); |
2612 | /// assert_eq!(5i32.carrying_mul(-2, 10), (0, 0)); |
2613 | /// assert_eq!(1_000_000_000i32.carrying_mul(-10, 0), (2884901888, -3)); |
2614 | /// assert_eq!(1_000_000_000i32.carrying_mul(-10, 10), (2884901898, -3)); |
2615 | #[doc = concat!("assert_eq!(" , |
2616 | stringify!($SelfT), "::MAX.carrying_mul(" , stringify!($SelfT), "::MAX, " , stringify!($SelfT), "::MAX), " , |
2617 | "(" , stringify!($SelfT), "::MAX.unsigned_abs() + 1, " , stringify!($SelfT), "::MAX / 2));" |
2618 | )] |
2619 | /// ``` |
2620 | #[unstable(feature = "bigint_helper_methods" , issue = "85532" )] |
2621 | #[rustc_const_unstable(feature = "bigint_helper_methods" , issue = "85532" )] |
2622 | #[must_use = "this returns the result of the operation, \ |
2623 | without modifying the original" ] |
2624 | #[inline] |
2625 | pub const fn carrying_mul(self, rhs: Self, carry: Self) -> ($UnsignedT, Self) { |
2626 | Self::carrying_mul_add(self, rhs, carry, 0) |
2627 | } |
2628 | |
2629 | /// Calculates the "full multiplication" `self * rhs + carry1 + carry2` |
2630 | /// without the possibility to overflow. |
2631 | /// |
2632 | /// This returns the low-order (wrapping) bits and the high-order (overflow) bits |
2633 | /// of the result as two separate values, in that order. |
2634 | /// |
2635 | /// Performs "long multiplication" which takes in an extra amount to add, and may return an |
2636 | /// additional amount of overflow. This allows for chaining together multiple |
2637 | /// multiplications to create "big integers" which represent larger values. |
2638 | /// |
2639 | /// If you don't need either `carry`, then you can use [`Self::widening_mul`] instead, |
2640 | /// and if you only need one `carry`, then you can use [`Self::carrying_mul`] instead. |
2641 | /// |
2642 | /// # Examples |
2643 | /// |
2644 | /// Basic usage: |
2645 | /// |
2646 | /// Please note that this example is shared between integer types. |
2647 | /// Which explains why `i32` is used here. |
2648 | /// |
2649 | /// ``` |
2650 | /// #![feature(bigint_helper_methods)] |
2651 | /// assert_eq!(5i32.carrying_mul_add(-2, 0, 0), (4294967286, -1)); |
2652 | /// assert_eq!(5i32.carrying_mul_add(-2, 10, 10), (10, 0)); |
2653 | /// assert_eq!(1_000_000_000i32.carrying_mul_add(-10, 0, 0), (2884901888, -3)); |
2654 | /// assert_eq!(1_000_000_000i32.carrying_mul_add(-10, 10, 10), (2884901908, -3)); |
2655 | #[doc = concat!("assert_eq!(" , |
2656 | stringify!($SelfT), "::MAX.carrying_mul_add(" , stringify!($SelfT), "::MAX, " , stringify!($SelfT), "::MAX, " , stringify!($SelfT), "::MAX), " , |
2657 | "(" , stringify!($UnsignedT), "::MAX, " , stringify!($SelfT), "::MAX / 2));" |
2658 | )] |
2659 | /// ``` |
2660 | #[unstable(feature = "bigint_helper_methods" , issue = "85532" )] |
2661 | #[rustc_const_unstable(feature = "bigint_helper_methods" , issue = "85532" )] |
2662 | #[must_use = "this returns the result of the operation, \ |
2663 | without modifying the original" ] |
2664 | #[inline] |
2665 | pub const fn carrying_mul_add(self, rhs: Self, carry: Self, add: Self) -> ($UnsignedT, Self) { |
2666 | intrinsics::carrying_mul_add(self, rhs, carry, add) |
2667 | } |
2668 | |
2669 | /// Calculates the divisor when `self` is divided by `rhs`. |
2670 | /// |
2671 | /// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would |
2672 | /// occur. If an overflow would occur then self is returned. |
2673 | /// |
2674 | /// # Panics |
2675 | /// |
2676 | /// This function will panic if `rhs` is zero. |
2677 | /// |
2678 | /// # Examples |
2679 | /// |
2680 | /// Basic usage: |
2681 | /// |
2682 | /// ``` |
2683 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".overflowing_div(2), (2, false));" )] |
2684 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MIN.overflowing_div(-1), (" , stringify!($SelfT), "::MIN, true));" )] |
2685 | /// ``` |
2686 | #[inline] |
2687 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
2688 | #[rustc_const_stable(feature = "const_overflowing_int_methods" , since = "1.52.0" )] |
2689 | #[must_use = "this returns the result of the operation, \ |
2690 | without modifying the original" ] |
2691 | pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) { |
2692 | // Using `&` helps LLVM see that it is the same check made in division. |
2693 | if intrinsics::unlikely((self == Self::MIN) & (rhs == -1)) { |
2694 | (self, true) |
2695 | } else { |
2696 | (self / rhs, false) |
2697 | } |
2698 | } |
2699 | |
2700 | /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`. |
2701 | /// |
2702 | /// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would |
2703 | /// occur. If an overflow would occur then `self` is returned. |
2704 | /// |
2705 | /// # Panics |
2706 | /// |
2707 | /// This function will panic if `rhs` is zero. |
2708 | /// |
2709 | /// # Examples |
2710 | /// |
2711 | /// Basic usage: |
2712 | /// |
2713 | /// ``` |
2714 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));" )] |
2715 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MIN.overflowing_div_euclid(-1), (" , stringify!($SelfT), "::MIN, true));" )] |
2716 | /// ``` |
2717 | #[inline] |
2718 | #[stable(feature = "euclidean_division" , since = "1.38.0" )] |
2719 | #[rustc_const_stable(feature = "const_euclidean_int_methods" , since = "1.52.0" )] |
2720 | #[must_use = "this returns the result of the operation, \ |
2721 | without modifying the original" ] |
2722 | pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) { |
2723 | // Using `&` helps LLVM see that it is the same check made in division. |
2724 | if intrinsics::unlikely((self == Self::MIN) & (rhs == -1)) { |
2725 | (self, true) |
2726 | } else { |
2727 | (self.div_euclid(rhs), false) |
2728 | } |
2729 | } |
2730 | |
2731 | /// Calculates the remainder when `self` is divided by `rhs`. |
2732 | /// |
2733 | /// Returns a tuple of the remainder after dividing along with a boolean indicating whether an |
2734 | /// arithmetic overflow would occur. If an overflow would occur then 0 is returned. |
2735 | /// |
2736 | /// # Panics |
2737 | /// |
2738 | /// This function will panic if `rhs` is zero. |
2739 | /// |
2740 | /// # Examples |
2741 | /// |
2742 | /// Basic usage: |
2743 | /// |
2744 | /// ``` |
2745 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".overflowing_rem(2), (1, false));" )] |
2746 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MIN.overflowing_rem(-1), (0, true));" )] |
2747 | /// ``` |
2748 | #[inline] |
2749 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
2750 | #[rustc_const_stable(feature = "const_overflowing_int_methods" , since = "1.52.0" )] |
2751 | #[must_use = "this returns the result of the operation, \ |
2752 | without modifying the original" ] |
2753 | pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) { |
2754 | if intrinsics::unlikely(rhs == -1) { |
2755 | (0, self == Self::MIN) |
2756 | } else { |
2757 | (self % rhs, false) |
2758 | } |
2759 | } |
2760 | |
2761 | |
2762 | /// Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`. |
2763 | /// |
2764 | /// Returns a tuple of the remainder after dividing along with a boolean indicating whether an |
2765 | /// arithmetic overflow would occur. If an overflow would occur then 0 is returned. |
2766 | /// |
2767 | /// # Panics |
2768 | /// |
2769 | /// This function will panic if `rhs` is zero. |
2770 | /// |
2771 | /// # Examples |
2772 | /// |
2773 | /// Basic usage: |
2774 | /// |
2775 | /// ``` |
2776 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));" )] |
2777 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MIN.overflowing_rem_euclid(-1), (0, true));" )] |
2778 | /// ``` |
2779 | #[stable(feature = "euclidean_division" , since = "1.38.0" )] |
2780 | #[rustc_const_stable(feature = "const_euclidean_int_methods" , since = "1.52.0" )] |
2781 | #[must_use = "this returns the result of the operation, \ |
2782 | without modifying the original" ] |
2783 | #[inline] |
2784 | #[track_caller] |
2785 | pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) { |
2786 | if intrinsics::unlikely(rhs == -1) { |
2787 | (0, self == Self::MIN) |
2788 | } else { |
2789 | (self.rem_euclid(rhs), false) |
2790 | } |
2791 | } |
2792 | |
2793 | |
2794 | /// Negates self, overflowing if this is equal to the minimum value. |
2795 | /// |
2796 | /// Returns a tuple of the negated version of self along with a boolean indicating whether an overflow |
2797 | /// happened. If `self` is the minimum value (e.g., `i32::MIN` for values of type `i32`), then the |
2798 | /// minimum value will be returned again and `true` will be returned for an overflow happening. |
2799 | /// |
2800 | /// # Examples |
2801 | /// |
2802 | /// Basic usage: |
2803 | /// |
2804 | /// ``` |
2805 | #[doc = concat!("assert_eq!(2" , stringify!($SelfT), ".overflowing_neg(), (-2, false));" )] |
2806 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MIN.overflowing_neg(), (" , stringify!($SelfT), "::MIN, true));" )] |
2807 | /// ``` |
2808 | #[inline] |
2809 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
2810 | #[rustc_const_stable(feature = "const_int_methods" , since = "1.32.0" )] |
2811 | #[must_use = "this returns the result of the operation, \ |
2812 | without modifying the original" ] |
2813 | #[allow(unused_attributes)] |
2814 | pub const fn overflowing_neg(self) -> (Self, bool) { |
2815 | if intrinsics::unlikely(self == Self::MIN) { |
2816 | (Self::MIN, true) |
2817 | } else { |
2818 | (-self, false) |
2819 | } |
2820 | } |
2821 | |
2822 | /// Shifts self left by `rhs` bits. |
2823 | /// |
2824 | /// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift |
2825 | /// value was larger than or equal to the number of bits. If the shift value is too large, then value is |
2826 | /// masked (N-1) where N is the number of bits, and this value is then used to perform the shift. |
2827 | /// |
2828 | /// # Examples |
2829 | /// |
2830 | /// Basic usage: |
2831 | /// |
2832 | /// ``` |
2833 | #[doc = concat!("assert_eq!(0x1" , stringify!($SelfT),".overflowing_shl(4), (0x10, false));" )] |
2834 | /// assert_eq!(0x1i32.overflowing_shl(36), (0x10, true)); |
2835 | #[doc = concat!("assert_eq!(0x10" , stringify!($SelfT), ".overflowing_shl(" , stringify!($BITS_MINUS_ONE), "), (0, false));" )] |
2836 | /// ``` |
2837 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
2838 | #[rustc_const_stable(feature = "const_int_methods" , since = "1.32.0" )] |
2839 | #[must_use = "this returns the result of the operation, \ |
2840 | without modifying the original" ] |
2841 | #[inline] |
2842 | pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) { |
2843 | (self.wrapping_shl(rhs), rhs >= Self::BITS) |
2844 | } |
2845 | |
2846 | /// Shifts self right by `rhs` bits. |
2847 | /// |
2848 | /// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift |
2849 | /// value was larger than or equal to the number of bits. If the shift value is too large, then value is |
2850 | /// masked (N-1) where N is the number of bits, and this value is then used to perform the shift. |
2851 | /// |
2852 | /// # Examples |
2853 | /// |
2854 | /// Basic usage: |
2855 | /// |
2856 | /// ``` |
2857 | #[doc = concat!("assert_eq!(0x10" , stringify!($SelfT), ".overflowing_shr(4), (0x1, false));" )] |
2858 | /// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true)); |
2859 | /// ``` |
2860 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
2861 | #[rustc_const_stable(feature = "const_int_methods" , since = "1.32.0" )] |
2862 | #[must_use = "this returns the result of the operation, \ |
2863 | without modifying the original" ] |
2864 | #[inline] |
2865 | pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) { |
2866 | (self.wrapping_shr(rhs), rhs >= Self::BITS) |
2867 | } |
2868 | |
2869 | /// Computes the absolute value of `self`. |
2870 | /// |
2871 | /// Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow |
2872 | /// happened. If self is the minimum value |
2873 | #[doc = concat!("(e.g., " , stringify!($SelfT), "::MIN for values of type " , stringify!($SelfT), ")," )] |
2874 | /// then the minimum value will be returned again and true will be returned |
2875 | /// for an overflow happening. |
2876 | /// |
2877 | /// # Examples |
2878 | /// |
2879 | /// Basic usage: |
2880 | /// |
2881 | /// ``` |
2882 | #[doc = concat!("assert_eq!(10" , stringify!($SelfT), ".overflowing_abs(), (10, false));" )] |
2883 | #[doc = concat!("assert_eq!((-10" , stringify!($SelfT), ").overflowing_abs(), (10, false));" )] |
2884 | #[doc = concat!("assert_eq!((" , stringify!($SelfT), "::MIN).overflowing_abs(), (" , stringify!($SelfT), "::MIN, true));" )] |
2885 | /// ``` |
2886 | #[stable(feature = "no_panic_abs" , since = "1.13.0" )] |
2887 | #[rustc_const_stable(feature = "const_int_methods" , since = "1.32.0" )] |
2888 | #[must_use = "this returns the result of the operation, \ |
2889 | without modifying the original" ] |
2890 | #[inline] |
2891 | pub const fn overflowing_abs(self) -> (Self, bool) { |
2892 | (self.wrapping_abs(), self == Self::MIN) |
2893 | } |
2894 | |
2895 | /// Raises self to the power of `exp`, using exponentiation by squaring. |
2896 | /// |
2897 | /// Returns a tuple of the exponentiation along with a bool indicating |
2898 | /// whether an overflow happened. |
2899 | /// |
2900 | /// # Examples |
2901 | /// |
2902 | /// Basic usage: |
2903 | /// |
2904 | /// ``` |
2905 | #[doc = concat!("assert_eq!(3" , stringify!($SelfT), ".overflowing_pow(4), (81, false));" )] |
2906 | /// assert_eq!(3i8.overflowing_pow(5), (-13, true)); |
2907 | /// ``` |
2908 | #[stable(feature = "no_panic_pow" , since = "1.34.0" )] |
2909 | #[rustc_const_stable(feature = "const_int_pow" , since = "1.50.0" )] |
2910 | #[must_use = "this returns the result of the operation, \ |
2911 | without modifying the original" ] |
2912 | #[inline] |
2913 | pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) { |
2914 | if exp == 0 { |
2915 | return (1,false); |
2916 | } |
2917 | let mut base = self; |
2918 | let mut acc: Self = 1; |
2919 | let mut overflown = false; |
2920 | // Scratch space for storing results of overflowing_mul. |
2921 | let mut r; |
2922 | |
2923 | loop { |
2924 | if (exp & 1) == 1 { |
2925 | r = acc.overflowing_mul(base); |
2926 | // since exp!=0, finally the exp must be 1. |
2927 | if exp == 1 { |
2928 | r.1 |= overflown; |
2929 | return r; |
2930 | } |
2931 | acc = r.0; |
2932 | overflown |= r.1; |
2933 | } |
2934 | exp /= 2; |
2935 | r = base.overflowing_mul(base); |
2936 | base = r.0; |
2937 | overflown |= r.1; |
2938 | } |
2939 | } |
2940 | |
2941 | /// Raises self to the power of `exp`, using exponentiation by squaring. |
2942 | /// |
2943 | /// # Examples |
2944 | /// |
2945 | /// Basic usage: |
2946 | /// |
2947 | /// ``` |
2948 | #[doc = concat!("let x: " , stringify!($SelfT), " = 2; // or any other integer type" )] |
2949 | /// |
2950 | /// assert_eq!(x.pow(5), 32); |
2951 | /// ``` |
2952 | #[stable(feature = "rust1" , since = "1.0.0" )] |
2953 | #[rustc_const_stable(feature = "const_int_pow" , since = "1.50.0" )] |
2954 | #[must_use = "this returns the result of the operation, \ |
2955 | without modifying the original" ] |
2956 | #[inline] |
2957 | #[rustc_inherit_overflow_checks] |
2958 | pub const fn pow(self, mut exp: u32) -> Self { |
2959 | if exp == 0 { |
2960 | return 1; |
2961 | } |
2962 | let mut base = self; |
2963 | let mut acc = 1; |
2964 | |
2965 | if intrinsics::is_val_statically_known(exp) { |
2966 | while exp > 1 { |
2967 | if (exp & 1) == 1 { |
2968 | acc = acc * base; |
2969 | } |
2970 | exp /= 2; |
2971 | base = base * base; |
2972 | } |
2973 | |
2974 | // since exp!=0, finally the exp must be 1. |
2975 | // Deal with the final bit of the exponent separately, since |
2976 | // squaring the base afterwards is not necessary and may cause a |
2977 | // needless overflow. |
2978 | acc * base |
2979 | } else { |
2980 | // This is faster than the above when the exponent is not known |
2981 | // at compile time. We can't use the same code for the constant |
2982 | // exponent case because LLVM is currently unable to unroll |
2983 | // this loop. |
2984 | loop { |
2985 | if (exp & 1) == 1 { |
2986 | acc = acc * base; |
2987 | // since exp!=0, finally the exp must be 1. |
2988 | if exp == 1 { |
2989 | return acc; |
2990 | } |
2991 | } |
2992 | exp /= 2; |
2993 | base = base * base; |
2994 | } |
2995 | } |
2996 | } |
2997 | |
2998 | /// Returns the square root of the number, rounded down. |
2999 | /// |
3000 | /// # Panics |
3001 | /// |
3002 | /// This function will panic if `self` is negative. |
3003 | /// |
3004 | /// # Examples |
3005 | /// |
3006 | /// Basic usage: |
3007 | /// ``` |
3008 | #[doc = concat!("assert_eq!(10" , stringify!($SelfT), ".isqrt(), 3);" )] |
3009 | /// ``` |
3010 | #[stable(feature = "isqrt" , since = "1.84.0" )] |
3011 | #[rustc_const_stable(feature = "isqrt" , since = "1.84.0" )] |
3012 | #[must_use = "this returns the result of the operation, \ |
3013 | without modifying the original" ] |
3014 | #[inline] |
3015 | #[track_caller] |
3016 | pub const fn isqrt(self) -> Self { |
3017 | match self.checked_isqrt() { |
3018 | Some(sqrt) => sqrt, |
3019 | None => crate::num::int_sqrt::panic_for_negative_argument(), |
3020 | } |
3021 | } |
3022 | |
3023 | /// Calculates the quotient of Euclidean division of `self` by `rhs`. |
3024 | /// |
3025 | /// This computes the integer `q` such that `self = q * rhs + r`, with |
3026 | /// `r = self.rem_euclid(rhs)` and `0 <= r < abs(rhs)`. |
3027 | /// |
3028 | /// In other words, the result is `self / rhs` rounded to the integer `q` |
3029 | /// such that `self >= q * rhs`. |
3030 | /// If `self > 0`, this is equal to rounding towards zero (the default in Rust); |
3031 | /// if `self < 0`, this is equal to rounding away from zero (towards +/- infinity). |
3032 | /// If `rhs > 0`, this is equal to rounding towards -infinity; |
3033 | /// if `rhs < 0`, this is equal to rounding towards +infinity. |
3034 | /// |
3035 | /// # Panics |
3036 | /// |
3037 | /// This function will panic if `rhs` is zero or if `self` is `Self::MIN` |
3038 | /// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag. |
3039 | /// |
3040 | /// # Examples |
3041 | /// |
3042 | /// Basic usage: |
3043 | /// |
3044 | /// ``` |
3045 | #[doc = concat!("let a: " , stringify!($SelfT), " = 7; // or any other integer type" )] |
3046 | /// let b = 4; |
3047 | /// |
3048 | /// assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1 |
3049 | /// assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1 |
3050 | /// assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2 |
3051 | /// assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2 |
3052 | /// ``` |
3053 | #[stable(feature = "euclidean_division" , since = "1.38.0" )] |
3054 | #[rustc_const_stable(feature = "const_euclidean_int_methods" , since = "1.52.0" )] |
3055 | #[must_use = "this returns the result of the operation, \ |
3056 | without modifying the original" ] |
3057 | #[inline] |
3058 | #[track_caller] |
3059 | pub const fn div_euclid(self, rhs: Self) -> Self { |
3060 | let q = self / rhs; |
3061 | if self % rhs < 0 { |
3062 | return if rhs > 0 { q - 1 } else { q + 1 } |
3063 | } |
3064 | q |
3065 | } |
3066 | |
3067 | |
3068 | /// Calculates the least nonnegative remainder of `self (mod rhs)`. |
3069 | /// |
3070 | /// This is done as if by the Euclidean division algorithm -- given |
3071 | /// `r = self.rem_euclid(rhs)`, the result satisfies |
3072 | /// `self = rhs * self.div_euclid(rhs) + r` and `0 <= r < abs(rhs)`. |
3073 | /// |
3074 | /// # Panics |
3075 | /// |
3076 | /// This function will panic if `rhs` is zero or if `self` is `Self::MIN` and |
3077 | /// `rhs` is -1. This behavior is not affected by the `overflow-checks` flag. |
3078 | /// |
3079 | /// # Examples |
3080 | /// |
3081 | /// Basic usage: |
3082 | /// |
3083 | /// ``` |
3084 | #[doc = concat!("let a: " , stringify!($SelfT), " = 7; // or any other integer type" )] |
3085 | /// let b = 4; |
3086 | /// |
3087 | /// assert_eq!(a.rem_euclid(b), 3); |
3088 | /// assert_eq!((-a).rem_euclid(b), 1); |
3089 | /// assert_eq!(a.rem_euclid(-b), 3); |
3090 | /// assert_eq!((-a).rem_euclid(-b), 1); |
3091 | /// ``` |
3092 | /// |
3093 | /// This will panic: |
3094 | /// ```should_panic |
3095 | #[doc = concat!("let _ = " , stringify!($SelfT), "::MIN.rem_euclid(-1);" )] |
3096 | /// ``` |
3097 | #[doc(alias = "modulo" , alias = "mod" )] |
3098 | #[stable(feature = "euclidean_division" , since = "1.38.0" )] |
3099 | #[rustc_const_stable(feature = "const_euclidean_int_methods" , since = "1.52.0" )] |
3100 | #[must_use = "this returns the result of the operation, \ |
3101 | without modifying the original" ] |
3102 | #[inline] |
3103 | #[track_caller] |
3104 | pub const fn rem_euclid(self, rhs: Self) -> Self { |
3105 | let r = self % rhs; |
3106 | if r < 0 { |
3107 | // Semantically equivalent to `if rhs < 0 { r - rhs } else { r + rhs }`. |
3108 | // If `rhs` is not `Self::MIN`, then `r + abs(rhs)` will not overflow |
3109 | // and is clearly equivalent, because `r` is negative. |
3110 | // Otherwise, `rhs` is `Self::MIN`, then we have |
3111 | // `r.wrapping_add(Self::MIN.wrapping_abs())`, which evaluates |
3112 | // to `r.wrapping_add(Self::MIN)`, which is equivalent to |
3113 | // `r - Self::MIN`, which is what we wanted (and will not overflow |
3114 | // for negative `r`). |
3115 | r.wrapping_add(rhs.wrapping_abs()) |
3116 | } else { |
3117 | r |
3118 | } |
3119 | } |
3120 | |
3121 | /// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity. |
3122 | /// |
3123 | /// # Panics |
3124 | /// |
3125 | /// This function will panic if `rhs` is zero or if `self` is `Self::MIN` |
3126 | /// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag. |
3127 | /// |
3128 | /// # Examples |
3129 | /// |
3130 | /// Basic usage: |
3131 | /// |
3132 | /// ``` |
3133 | /// #![feature(int_roundings)] |
3134 | #[doc = concat!("let a: " , stringify!($SelfT)," = 8;" )] |
3135 | /// let b = 3; |
3136 | /// |
3137 | /// assert_eq!(a.div_floor(b), 2); |
3138 | /// assert_eq!(a.div_floor(-b), -3); |
3139 | /// assert_eq!((-a).div_floor(b), -3); |
3140 | /// assert_eq!((-a).div_floor(-b), 2); |
3141 | /// ``` |
3142 | #[unstable(feature = "int_roundings" , issue = "88581" )] |
3143 | #[must_use = "this returns the result of the operation, \ |
3144 | without modifying the original" ] |
3145 | #[inline] |
3146 | #[track_caller] |
3147 | pub const fn div_floor(self, rhs: Self) -> Self { |
3148 | let d = self / rhs; |
3149 | let r = self % rhs; |
3150 | |
3151 | // If the remainder is non-zero, we need to subtract one if the |
3152 | // signs of self and rhs differ, as this means we rounded upwards |
3153 | // instead of downwards. We do this branchlessly by creating a mask |
3154 | // which is all-ones iff the signs differ, and 0 otherwise. Then by |
3155 | // adding this mask (which corresponds to the signed value -1), we |
3156 | // get our correction. |
3157 | let correction = (self ^ rhs) >> (Self::BITS - 1); |
3158 | if r != 0 { |
3159 | d + correction |
3160 | } else { |
3161 | d |
3162 | } |
3163 | } |
3164 | |
3165 | /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity. |
3166 | /// |
3167 | /// # Panics |
3168 | /// |
3169 | /// This function will panic if `rhs` is zero or if `self` is `Self::MIN` |
3170 | /// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag. |
3171 | /// |
3172 | /// # Examples |
3173 | /// |
3174 | /// Basic usage: |
3175 | /// |
3176 | /// ``` |
3177 | /// #![feature(int_roundings)] |
3178 | #[doc = concat!("let a: " , stringify!($SelfT)," = 8;" )] |
3179 | /// let b = 3; |
3180 | /// |
3181 | /// assert_eq!(a.div_ceil(b), 3); |
3182 | /// assert_eq!(a.div_ceil(-b), -2); |
3183 | /// assert_eq!((-a).div_ceil(b), -2); |
3184 | /// assert_eq!((-a).div_ceil(-b), 3); |
3185 | /// ``` |
3186 | #[unstable(feature = "int_roundings" , issue = "88581" )] |
3187 | #[must_use = "this returns the result of the operation, \ |
3188 | without modifying the original" ] |
3189 | #[inline] |
3190 | #[track_caller] |
3191 | pub const fn div_ceil(self, rhs: Self) -> Self { |
3192 | let d = self / rhs; |
3193 | let r = self % rhs; |
3194 | |
3195 | // When remainder is non-zero we have a.div_ceil(b) == 1 + a.div_floor(b), |
3196 | // so we can re-use the algorithm from div_floor, just adding 1. |
3197 | let correction = 1 + ((self ^ rhs) >> (Self::BITS - 1)); |
3198 | if r != 0 { |
3199 | d + correction |
3200 | } else { |
3201 | d |
3202 | } |
3203 | } |
3204 | |
3205 | /// If `rhs` is positive, calculates the smallest value greater than or |
3206 | /// equal to `self` that is a multiple of `rhs`. If `rhs` is negative, |
3207 | /// calculates the largest value less than or equal to `self` that is a |
3208 | /// multiple of `rhs`. |
3209 | /// |
3210 | /// # Panics |
3211 | /// |
3212 | /// This function will panic if `rhs` is zero. |
3213 | /// |
3214 | /// ## Overflow behavior |
3215 | /// |
3216 | /// On overflow, this function will panic if overflow checks are enabled (default in debug |
3217 | /// mode) and wrap if overflow checks are disabled (default in release mode). |
3218 | /// |
3219 | /// # Examples |
3220 | /// |
3221 | /// Basic usage: |
3222 | /// |
3223 | /// ``` |
3224 | /// #![feature(int_roundings)] |
3225 | #[doc = concat!("assert_eq!(16_" , stringify!($SelfT), ".next_multiple_of(8), 16);" )] |
3226 | #[doc = concat!("assert_eq!(23_" , stringify!($SelfT), ".next_multiple_of(8), 24);" )] |
3227 | #[doc = concat!("assert_eq!(16_" , stringify!($SelfT), ".next_multiple_of(-8), 16);" )] |
3228 | #[doc = concat!("assert_eq!(23_" , stringify!($SelfT), ".next_multiple_of(-8), 16);" )] |
3229 | #[doc = concat!("assert_eq!((-16_" , stringify!($SelfT), ").next_multiple_of(8), -16);" )] |
3230 | #[doc = concat!("assert_eq!((-23_" , stringify!($SelfT), ").next_multiple_of(8), -16);" )] |
3231 | #[doc = concat!("assert_eq!((-16_" , stringify!($SelfT), ").next_multiple_of(-8), -16);" )] |
3232 | #[doc = concat!("assert_eq!((-23_" , stringify!($SelfT), ").next_multiple_of(-8), -24);" )] |
3233 | /// ``` |
3234 | #[unstable(feature = "int_roundings" , issue = "88581" )] |
3235 | #[must_use = "this returns the result of the operation, \ |
3236 | without modifying the original" ] |
3237 | #[inline] |
3238 | #[rustc_inherit_overflow_checks] |
3239 | pub const fn next_multiple_of(self, rhs: Self) -> Self { |
3240 | // This would otherwise fail when calculating `r` when self == T::MIN. |
3241 | if rhs == -1 { |
3242 | return self; |
3243 | } |
3244 | |
3245 | let r = self % rhs; |
3246 | let m = if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) { |
3247 | r + rhs |
3248 | } else { |
3249 | r |
3250 | }; |
3251 | |
3252 | if m == 0 { |
3253 | self |
3254 | } else { |
3255 | self + (rhs - m) |
3256 | } |
3257 | } |
3258 | |
3259 | /// If `rhs` is positive, calculates the smallest value greater than or |
3260 | /// equal to `self` that is a multiple of `rhs`. If `rhs` is negative, |
3261 | /// calculates the largest value less than or equal to `self` that is a |
3262 | /// multiple of `rhs`. Returns `None` if `rhs` is zero or the operation |
3263 | /// would result in overflow. |
3264 | /// |
3265 | /// # Examples |
3266 | /// |
3267 | /// Basic usage: |
3268 | /// |
3269 | /// ``` |
3270 | /// #![feature(int_roundings)] |
3271 | #[doc = concat!("assert_eq!(16_" , stringify!($SelfT), ".checked_next_multiple_of(8), Some(16));" )] |
3272 | #[doc = concat!("assert_eq!(23_" , stringify!($SelfT), ".checked_next_multiple_of(8), Some(24));" )] |
3273 | #[doc = concat!("assert_eq!(16_" , stringify!($SelfT), ".checked_next_multiple_of(-8), Some(16));" )] |
3274 | #[doc = concat!("assert_eq!(23_" , stringify!($SelfT), ".checked_next_multiple_of(-8), Some(16));" )] |
3275 | #[doc = concat!("assert_eq!((-16_" , stringify!($SelfT), ").checked_next_multiple_of(8), Some(-16));" )] |
3276 | #[doc = concat!("assert_eq!((-23_" , stringify!($SelfT), ").checked_next_multiple_of(8), Some(-16));" )] |
3277 | #[doc = concat!("assert_eq!((-16_" , stringify!($SelfT), ").checked_next_multiple_of(-8), Some(-16));" )] |
3278 | #[doc = concat!("assert_eq!((-23_" , stringify!($SelfT), ").checked_next_multiple_of(-8), Some(-24));" )] |
3279 | #[doc = concat!("assert_eq!(1_" , stringify!($SelfT), ".checked_next_multiple_of(0), None);" )] |
3280 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MAX.checked_next_multiple_of(2), None);" )] |
3281 | /// ``` |
3282 | #[unstable(feature = "int_roundings" , issue = "88581" )] |
3283 | #[must_use = "this returns the result of the operation, \ |
3284 | without modifying the original" ] |
3285 | #[inline] |
3286 | pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> { |
3287 | // This would otherwise fail when calculating `r` when self == T::MIN. |
3288 | if rhs == -1 { |
3289 | return Some(self); |
3290 | } |
3291 | |
3292 | let r = try_opt!(self.checked_rem(rhs)); |
3293 | let m = if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) { |
3294 | // r + rhs cannot overflow because they have opposite signs |
3295 | r + rhs |
3296 | } else { |
3297 | r |
3298 | }; |
3299 | |
3300 | if m == 0 { |
3301 | Some(self) |
3302 | } else { |
3303 | // rhs - m cannot overflow because m has the same sign as rhs |
3304 | self.checked_add(rhs - m) |
3305 | } |
3306 | } |
3307 | |
3308 | /// Returns the logarithm of the number with respect to an arbitrary base, |
3309 | /// rounded down. |
3310 | /// |
3311 | /// This method might not be optimized owing to implementation details; |
3312 | /// `ilog2` can produce results more efficiently for base 2, and `ilog10` |
3313 | /// can produce results more efficiently for base 10. |
3314 | /// |
3315 | /// # Panics |
3316 | /// |
3317 | /// This function will panic if `self` is less than or equal to zero, |
3318 | /// or if `base` is less than 2. |
3319 | /// |
3320 | /// # Examples |
3321 | /// |
3322 | /// ``` |
3323 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".ilog(5), 1);" )] |
3324 | /// ``` |
3325 | #[stable(feature = "int_log" , since = "1.67.0" )] |
3326 | #[rustc_const_stable(feature = "int_log" , since = "1.67.0" )] |
3327 | #[must_use = "this returns the result of the operation, \ |
3328 | without modifying the original" ] |
3329 | #[inline] |
3330 | #[track_caller] |
3331 | pub const fn ilog(self, base: Self) -> u32 { |
3332 | assert!(base >= 2, "base of integer logarithm must be at least 2" ); |
3333 | if let Some(log) = self.checked_ilog(base) { |
3334 | log |
3335 | } else { |
3336 | int_log10::panic_for_nonpositive_argument() |
3337 | } |
3338 | } |
3339 | |
3340 | /// Returns the base 2 logarithm of the number, rounded down. |
3341 | /// |
3342 | /// # Panics |
3343 | /// |
3344 | /// This function will panic if `self` is less than or equal to zero. |
3345 | /// |
3346 | /// # Examples |
3347 | /// |
3348 | /// ``` |
3349 | #[doc = concat!("assert_eq!(2" , stringify!($SelfT), ".ilog2(), 1);" )] |
3350 | /// ``` |
3351 | #[stable(feature = "int_log" , since = "1.67.0" )] |
3352 | #[rustc_const_stable(feature = "int_log" , since = "1.67.0" )] |
3353 | #[must_use = "this returns the result of the operation, \ |
3354 | without modifying the original" ] |
3355 | #[inline] |
3356 | #[track_caller] |
3357 | pub const fn ilog2(self) -> u32 { |
3358 | if let Some(log) = self.checked_ilog2() { |
3359 | log |
3360 | } else { |
3361 | int_log10::panic_for_nonpositive_argument() |
3362 | } |
3363 | } |
3364 | |
3365 | /// Returns the base 10 logarithm of the number, rounded down. |
3366 | /// |
3367 | /// # Panics |
3368 | /// |
3369 | /// This function will panic if `self` is less than or equal to zero. |
3370 | /// |
3371 | /// # Example |
3372 | /// |
3373 | /// ``` |
3374 | #[doc = concat!("assert_eq!(10" , stringify!($SelfT), ".ilog10(), 1);" )] |
3375 | /// ``` |
3376 | #[stable(feature = "int_log" , since = "1.67.0" )] |
3377 | #[rustc_const_stable(feature = "int_log" , since = "1.67.0" )] |
3378 | #[must_use = "this returns the result of the operation, \ |
3379 | without modifying the original" ] |
3380 | #[inline] |
3381 | #[track_caller] |
3382 | pub const fn ilog10(self) -> u32 { |
3383 | if let Some(log) = self.checked_ilog10() { |
3384 | log |
3385 | } else { |
3386 | int_log10::panic_for_nonpositive_argument() |
3387 | } |
3388 | } |
3389 | |
3390 | /// Returns the logarithm of the number with respect to an arbitrary base, |
3391 | /// rounded down. |
3392 | /// |
3393 | /// Returns `None` if the number is negative or zero, or if the base is not at least 2. |
3394 | /// |
3395 | /// This method might not be optimized owing to implementation details; |
3396 | /// `checked_ilog2` can produce results more efficiently for base 2, and |
3397 | /// `checked_ilog10` can produce results more efficiently for base 10. |
3398 | /// |
3399 | /// # Examples |
3400 | /// |
3401 | /// ``` |
3402 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".checked_ilog(5), Some(1));" )] |
3403 | /// ``` |
3404 | #[stable(feature = "int_log" , since = "1.67.0" )] |
3405 | #[rustc_const_stable(feature = "int_log" , since = "1.67.0" )] |
3406 | #[must_use = "this returns the result of the operation, \ |
3407 | without modifying the original" ] |
3408 | #[inline] |
3409 | pub const fn checked_ilog(self, base: Self) -> Option<u32> { |
3410 | if self <= 0 || base <= 1 { |
3411 | None |
3412 | } else { |
3413 | // Delegate to the unsigned implementation. |
3414 | // The condition makes sure that both casts are exact. |
3415 | (self as $UnsignedT).checked_ilog(base as $UnsignedT) |
3416 | } |
3417 | } |
3418 | |
3419 | /// Returns the base 2 logarithm of the number, rounded down. |
3420 | /// |
3421 | /// Returns `None` if the number is negative or zero. |
3422 | /// |
3423 | /// # Examples |
3424 | /// |
3425 | /// ``` |
3426 | #[doc = concat!("assert_eq!(2" , stringify!($SelfT), ".checked_ilog2(), Some(1));" )] |
3427 | /// ``` |
3428 | #[stable(feature = "int_log" , since = "1.67.0" )] |
3429 | #[rustc_const_stable(feature = "int_log" , since = "1.67.0" )] |
3430 | #[must_use = "this returns the result of the operation, \ |
3431 | without modifying the original" ] |
3432 | #[inline] |
3433 | pub const fn checked_ilog2(self) -> Option<u32> { |
3434 | if self <= 0 { |
3435 | None |
3436 | } else { |
3437 | // SAFETY: We just checked that this number is positive |
3438 | let log = (Self::BITS - 1) - unsafe { intrinsics::ctlz_nonzero(self) as u32 }; |
3439 | Some(log) |
3440 | } |
3441 | } |
3442 | |
3443 | /// Returns the base 10 logarithm of the number, rounded down. |
3444 | /// |
3445 | /// Returns `None` if the number is negative or zero. |
3446 | /// |
3447 | /// # Example |
3448 | /// |
3449 | /// ``` |
3450 | #[doc = concat!("assert_eq!(10" , stringify!($SelfT), ".checked_ilog10(), Some(1));" )] |
3451 | /// ``` |
3452 | #[stable(feature = "int_log" , since = "1.67.0" )] |
3453 | #[rustc_const_stable(feature = "int_log" , since = "1.67.0" )] |
3454 | #[must_use = "this returns the result of the operation, \ |
3455 | without modifying the original" ] |
3456 | #[inline] |
3457 | pub const fn checked_ilog10(self) -> Option<u32> { |
3458 | if self > 0 { |
3459 | Some(int_log10::$ActualT(self as $ActualT)) |
3460 | } else { |
3461 | None |
3462 | } |
3463 | } |
3464 | |
3465 | /// Computes the absolute value of `self`. |
3466 | /// |
3467 | /// # Overflow behavior |
3468 | /// |
3469 | /// The absolute value of |
3470 | #[doc = concat!("`" , stringify!($SelfT), "::MIN`" )] |
3471 | /// cannot be represented as an |
3472 | #[doc = concat!("`" , stringify!($SelfT), "`," )] |
3473 | /// and attempting to calculate it will cause an overflow. This means |
3474 | /// that code in debug mode will trigger a panic on this case and |
3475 | /// optimized code will return |
3476 | #[doc = concat!("`" , stringify!($SelfT), "::MIN`" )] |
3477 | /// without a panic. If you do not want this behavior, consider |
3478 | /// using [`unsigned_abs`](Self::unsigned_abs) instead. |
3479 | /// |
3480 | /// # Examples |
3481 | /// |
3482 | /// Basic usage: |
3483 | /// |
3484 | /// ``` |
3485 | #[doc = concat!("assert_eq!(10" , stringify!($SelfT), ".abs(), 10);" )] |
3486 | #[doc = concat!("assert_eq!((-10" , stringify!($SelfT), ").abs(), 10);" )] |
3487 | /// ``` |
3488 | #[stable(feature = "rust1" , since = "1.0.0" )] |
3489 | #[rustc_const_stable(feature = "const_int_methods" , since = "1.32.0" )] |
3490 | #[allow(unused_attributes)] |
3491 | #[must_use = "this returns the result of the operation, \ |
3492 | without modifying the original" ] |
3493 | #[inline] |
3494 | #[rustc_inherit_overflow_checks] |
3495 | pub const fn abs(self) -> Self { |
3496 | // Note that the #[rustc_inherit_overflow_checks] and #[inline] |
3497 | // above mean that the overflow semantics of the subtraction |
3498 | // depend on the crate we're being called from. |
3499 | if self.is_negative() { |
3500 | -self |
3501 | } else { |
3502 | self |
3503 | } |
3504 | } |
3505 | |
3506 | /// Computes the absolute difference between `self` and `other`. |
3507 | /// |
3508 | /// This function always returns the correct answer without overflow or |
3509 | /// panics by returning an unsigned integer. |
3510 | /// |
3511 | /// # Examples |
3512 | /// |
3513 | /// Basic usage: |
3514 | /// |
3515 | /// ``` |
3516 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".abs_diff(80), 20" , stringify!($UnsignedT), ");" )] |
3517 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".abs_diff(110), 10" , stringify!($UnsignedT), ");" )] |
3518 | #[doc = concat!("assert_eq!((-100" , stringify!($SelfT), ").abs_diff(80), 180" , stringify!($UnsignedT), ");" )] |
3519 | #[doc = concat!("assert_eq!((-100" , stringify!($SelfT), ").abs_diff(-120), 20" , stringify!($UnsignedT), ");" )] |
3520 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MIN.abs_diff(" , stringify!($SelfT), "::MAX), " , stringify!($UnsignedT), "::MAX);" )] |
3521 | /// ``` |
3522 | #[stable(feature = "int_abs_diff" , since = "1.60.0" )] |
3523 | #[rustc_const_stable(feature = "int_abs_diff" , since = "1.60.0" )] |
3524 | #[must_use = "this returns the result of the operation, \ |
3525 | without modifying the original" ] |
3526 | #[inline] |
3527 | pub const fn abs_diff(self, other: Self) -> $UnsignedT { |
3528 | if self < other { |
3529 | // Converting a non-negative x from signed to unsigned by using |
3530 | // `x as U` is left unchanged, but a negative x is converted |
3531 | // to value x + 2^N. Thus if `s` and `o` are binary variables |
3532 | // respectively indicating whether `self` and `other` are |
3533 | // negative, we are computing the mathematical value: |
3534 | // |
3535 | // (other + o*2^N) - (self + s*2^N) mod 2^N |
3536 | // other - self + (o-s)*2^N mod 2^N |
3537 | // other - self mod 2^N |
3538 | // |
3539 | // Finally, taking the mod 2^N of the mathematical value of |
3540 | // `other - self` does not change it as it already is |
3541 | // in the range [0, 2^N). |
3542 | (other as $UnsignedT).wrapping_sub(self as $UnsignedT) |
3543 | } else { |
3544 | (self as $UnsignedT).wrapping_sub(other as $UnsignedT) |
3545 | } |
3546 | } |
3547 | |
3548 | /// Returns a number representing sign of `self`. |
3549 | /// |
3550 | /// - `0` if the number is zero |
3551 | /// - `1` if the number is positive |
3552 | /// - `-1` if the number is negative |
3553 | /// |
3554 | /// # Examples |
3555 | /// |
3556 | /// Basic usage: |
3557 | /// |
3558 | /// ``` |
3559 | #[doc = concat!("assert_eq!(10" , stringify!($SelfT), ".signum(), 1);" )] |
3560 | #[doc = concat!("assert_eq!(0" , stringify!($SelfT), ".signum(), 0);" )] |
3561 | #[doc = concat!("assert_eq!((-10" , stringify!($SelfT), ").signum(), -1);" )] |
3562 | /// ``` |
3563 | #[stable(feature = "rust1" , since = "1.0.0" )] |
3564 | #[rustc_const_stable(feature = "const_int_sign" , since = "1.47.0" )] |
3565 | #[must_use = "this returns the result of the operation, \ |
3566 | without modifying the original" ] |
3567 | #[inline(always)] |
3568 | pub const fn signum(self) -> Self { |
3569 | // Picking the right way to phrase this is complicated |
3570 | // (<https://graphics.stanford.edu/~seander/bithacks.html#CopyIntegerSign>) |
3571 | // so delegate it to `Ord` which is already producing -1/0/+1 |
3572 | // exactly like we need and can be the place to deal with the complexity. |
3573 | |
3574 | // FIXME(const-hack): replace with cmp |
3575 | if self < 0 { -1 } |
3576 | else if self == 0 { 0 } |
3577 | else { 1 } |
3578 | } |
3579 | |
3580 | /// Returns `true` if `self` is positive and `false` if the number is zero or |
3581 | /// negative. |
3582 | /// |
3583 | /// # Examples |
3584 | /// |
3585 | /// Basic usage: |
3586 | /// |
3587 | /// ``` |
3588 | #[doc = concat!("assert!(10" , stringify!($SelfT), ".is_positive());" )] |
3589 | #[doc = concat!("assert!(!(-10" , stringify!($SelfT), ").is_positive());" )] |
3590 | /// ``` |
3591 | #[must_use] |
3592 | #[stable(feature = "rust1" , since = "1.0.0" )] |
3593 | #[rustc_const_stable(feature = "const_int_methods" , since = "1.32.0" )] |
3594 | #[inline(always)] |
3595 | pub const fn is_positive(self) -> bool { self > 0 } |
3596 | |
3597 | /// Returns `true` if `self` is negative and `false` if the number is zero or |
3598 | /// positive. |
3599 | /// |
3600 | /// # Examples |
3601 | /// |
3602 | /// Basic usage: |
3603 | /// |
3604 | /// ``` |
3605 | #[doc = concat!("assert!((-10" , stringify!($SelfT), ").is_negative());" )] |
3606 | #[doc = concat!("assert!(!10" , stringify!($SelfT), ".is_negative());" )] |
3607 | /// ``` |
3608 | #[must_use] |
3609 | #[stable(feature = "rust1" , since = "1.0.0" )] |
3610 | #[rustc_const_stable(feature = "const_int_methods" , since = "1.32.0" )] |
3611 | #[inline(always)] |
3612 | pub const fn is_negative(self) -> bool { self < 0 } |
3613 | |
3614 | /// Returns the memory representation of this integer as a byte array in |
3615 | /// big-endian (network) byte order. |
3616 | /// |
3617 | #[doc = $to_xe_bytes_doc] |
3618 | /// |
3619 | /// # Examples |
3620 | /// |
3621 | /// ``` |
3622 | #[doc = concat!("let bytes = " , $swap_op, stringify!($SelfT), ".to_be_bytes();" )] |
3623 | #[doc = concat!("assert_eq!(bytes, " , $be_bytes, ");" )] |
3624 | /// ``` |
3625 | #[stable(feature = "int_to_from_bytes" , since = "1.32.0" )] |
3626 | #[rustc_const_stable(feature = "const_int_conversion" , since = "1.44.0" )] |
3627 | #[must_use = "this returns the result of the operation, \ |
3628 | without modifying the original" ] |
3629 | #[inline] |
3630 | pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] { |
3631 | self.to_be().to_ne_bytes() |
3632 | } |
3633 | |
3634 | /// Returns the memory representation of this integer as a byte array in |
3635 | /// little-endian byte order. |
3636 | /// |
3637 | #[doc = $to_xe_bytes_doc] |
3638 | /// |
3639 | /// # Examples |
3640 | /// |
3641 | /// ``` |
3642 | #[doc = concat!("let bytes = " , $swap_op, stringify!($SelfT), ".to_le_bytes();" )] |
3643 | #[doc = concat!("assert_eq!(bytes, " , $le_bytes, ");" )] |
3644 | /// ``` |
3645 | #[stable(feature = "int_to_from_bytes" , since = "1.32.0" )] |
3646 | #[rustc_const_stable(feature = "const_int_conversion" , since = "1.44.0" )] |
3647 | #[must_use = "this returns the result of the operation, \ |
3648 | without modifying the original" ] |
3649 | #[inline] |
3650 | pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] { |
3651 | self.to_le().to_ne_bytes() |
3652 | } |
3653 | |
3654 | /// Returns the memory representation of this integer as a byte array in |
3655 | /// native byte order. |
3656 | /// |
3657 | /// As the target platform's native endianness is used, portable code |
3658 | /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, |
3659 | /// instead. |
3660 | /// |
3661 | #[doc = $to_xe_bytes_doc] |
3662 | /// |
3663 | /// [`to_be_bytes`]: Self::to_be_bytes |
3664 | /// [`to_le_bytes`]: Self::to_le_bytes |
3665 | /// |
3666 | /// # Examples |
3667 | /// |
3668 | /// ``` |
3669 | #[doc = concat!("let bytes = " , $swap_op, stringify!($SelfT), ".to_ne_bytes();" )] |
3670 | /// assert_eq!( |
3671 | /// bytes, |
3672 | /// if cfg!(target_endian = "big") { |
3673 | #[doc = concat!(" " , $be_bytes)] |
3674 | /// } else { |
3675 | #[doc = concat!(" " , $le_bytes)] |
3676 | /// } |
3677 | /// ); |
3678 | /// ``` |
3679 | #[stable(feature = "int_to_from_bytes" , since = "1.32.0" )] |
3680 | #[rustc_const_stable(feature = "const_int_conversion" , since = "1.44.0" )] |
3681 | // SAFETY: const sound because integers are plain old datatypes so we can always |
3682 | // transmute them to arrays of bytes |
3683 | #[must_use = "this returns the result of the operation, \ |
3684 | without modifying the original" ] |
3685 | #[inline] |
3686 | pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] { |
3687 | // SAFETY: integers are plain old datatypes so we can always transmute them to |
3688 | // arrays of bytes |
3689 | unsafe { mem::transmute(self) } |
3690 | } |
3691 | |
3692 | /// Creates an integer value from its representation as a byte array in |
3693 | /// big endian. |
3694 | /// |
3695 | #[doc = $from_xe_bytes_doc] |
3696 | /// |
3697 | /// # Examples |
3698 | /// |
3699 | /// ``` |
3700 | #[doc = concat!("let value = " , stringify!($SelfT), "::from_be_bytes(" , $be_bytes, ");" )] |
3701 | #[doc = concat!("assert_eq!(value, " , $swap_op, ");" )] |
3702 | /// ``` |
3703 | /// |
3704 | /// When starting from a slice rather than an array, fallible conversion APIs can be used: |
3705 | /// |
3706 | /// ``` |
3707 | #[doc = concat!("fn read_be_" , stringify!($SelfT), "(input: &mut &[u8]) -> " , stringify!($SelfT), " {" )] |
3708 | #[doc = concat!(" let (int_bytes, rest) = input.split_at(size_of::<" , stringify!($SelfT), ">());" )] |
3709 | /// *input = rest; |
3710 | #[doc = concat!(" " , stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())" )] |
3711 | /// } |
3712 | /// ``` |
3713 | #[stable(feature = "int_to_from_bytes" , since = "1.32.0" )] |
3714 | #[rustc_const_stable(feature = "const_int_conversion" , since = "1.44.0" )] |
3715 | #[must_use] |
3716 | #[inline] |
3717 | pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self { |
3718 | Self::from_be(Self::from_ne_bytes(bytes)) |
3719 | } |
3720 | |
3721 | /// Creates an integer value from its representation as a byte array in |
3722 | /// little endian. |
3723 | /// |
3724 | #[doc = $from_xe_bytes_doc] |
3725 | /// |
3726 | /// # Examples |
3727 | /// |
3728 | /// ``` |
3729 | #[doc = concat!("let value = " , stringify!($SelfT), "::from_le_bytes(" , $le_bytes, ");" )] |
3730 | #[doc = concat!("assert_eq!(value, " , $swap_op, ");" )] |
3731 | /// ``` |
3732 | /// |
3733 | /// When starting from a slice rather than an array, fallible conversion APIs can be used: |
3734 | /// |
3735 | /// ``` |
3736 | #[doc = concat!("fn read_le_" , stringify!($SelfT), "(input: &mut &[u8]) -> " , stringify!($SelfT), " {" )] |
3737 | #[doc = concat!(" let (int_bytes, rest) = input.split_at(size_of::<" , stringify!($SelfT), ">());" )] |
3738 | /// *input = rest; |
3739 | #[doc = concat!(" " , stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())" )] |
3740 | /// } |
3741 | /// ``` |
3742 | #[stable(feature = "int_to_from_bytes" , since = "1.32.0" )] |
3743 | #[rustc_const_stable(feature = "const_int_conversion" , since = "1.44.0" )] |
3744 | #[must_use] |
3745 | #[inline] |
3746 | pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self { |
3747 | Self::from_le(Self::from_ne_bytes(bytes)) |
3748 | } |
3749 | |
3750 | /// Creates an integer value from its memory representation as a byte |
3751 | /// array in native endianness. |
3752 | /// |
3753 | /// As the target platform's native endianness is used, portable code |
3754 | /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as |
3755 | /// appropriate instead. |
3756 | /// |
3757 | /// [`from_be_bytes`]: Self::from_be_bytes |
3758 | /// [`from_le_bytes`]: Self::from_le_bytes |
3759 | /// |
3760 | #[doc = $from_xe_bytes_doc] |
3761 | /// |
3762 | /// # Examples |
3763 | /// |
3764 | /// ``` |
3765 | #[doc = concat!("let value = " , stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big \") {" )] |
3766 | #[doc = concat!(" " , $be_bytes)] |
3767 | /// } else { |
3768 | #[doc = concat!(" " , $le_bytes)] |
3769 | /// }); |
3770 | #[doc = concat!("assert_eq!(value, " , $swap_op, ");" )] |
3771 | /// ``` |
3772 | /// |
3773 | /// When starting from a slice rather than an array, fallible conversion APIs can be used: |
3774 | /// |
3775 | /// ``` |
3776 | #[doc = concat!("fn read_ne_" , stringify!($SelfT), "(input: &mut &[u8]) -> " , stringify!($SelfT), " {" )] |
3777 | #[doc = concat!(" let (int_bytes, rest) = input.split_at(size_of::<" , stringify!($SelfT), ">());" )] |
3778 | /// *input = rest; |
3779 | #[doc = concat!(" " , stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())" )] |
3780 | /// } |
3781 | /// ``` |
3782 | #[stable(feature = "int_to_from_bytes" , since = "1.32.0" )] |
3783 | #[rustc_const_stable(feature = "const_int_conversion" , since = "1.44.0" )] |
3784 | #[must_use] |
3785 | // SAFETY: const sound because integers are plain old datatypes so we can always |
3786 | // transmute to them |
3787 | #[inline] |
3788 | pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self { |
3789 | // SAFETY: integers are plain old datatypes so we can always transmute to them |
3790 | unsafe { mem::transmute(bytes) } |
3791 | } |
3792 | |
3793 | /// New code should prefer to use |
3794 | #[doc = concat!("[`" , stringify!($SelfT), "::MIN" , "`] instead." )] |
3795 | /// |
3796 | /// Returns the smallest value that can be represented by this integer type. |
3797 | #[stable(feature = "rust1" , since = "1.0.0" )] |
3798 | #[inline(always)] |
3799 | #[rustc_promotable] |
3800 | #[rustc_const_stable(feature = "const_min_value" , since = "1.32.0" )] |
3801 | #[deprecated(since = "TBD" , note = "replaced by the `MIN` associated constant on this type" )] |
3802 | #[rustc_diagnostic_item = concat!(stringify!($SelfT), "_legacy_fn_min_value" )] |
3803 | pub const fn min_value() -> Self { |
3804 | Self::MIN |
3805 | } |
3806 | |
3807 | /// New code should prefer to use |
3808 | #[doc = concat!("[`" , stringify!($SelfT), "::MAX" , "`] instead." )] |
3809 | /// |
3810 | /// Returns the largest value that can be represented by this integer type. |
3811 | #[stable(feature = "rust1" , since = "1.0.0" )] |
3812 | #[inline(always)] |
3813 | #[rustc_promotable] |
3814 | #[rustc_const_stable(feature = "const_max_value" , since = "1.32.0" )] |
3815 | #[deprecated(since = "TBD" , note = "replaced by the `MAX` associated constant on this type" )] |
3816 | #[rustc_diagnostic_item = concat!(stringify!($SelfT), "_legacy_fn_max_value" )] |
3817 | pub const fn max_value() -> Self { |
3818 | Self::MAX |
3819 | } |
3820 | } |
3821 | } |
3822 | |