1 | macro_rules! uint_impl { |
2 | ( |
3 | Self = $SelfT:ty, |
4 | ActualT = $ActualT:ident, |
5 | SignedT = $SignedT:ident, |
6 | NonZeroT = $NonZeroT:ty, |
7 | |
8 | // There are all for use *only* in doc comments. |
9 | // As such, they're all passed as literals -- passing them as a string |
10 | // literal is fine if they need to be multiple code tokens. |
11 | // In non-comments, use the associated constants rather than these. |
12 | BITS = $BITS:literal, |
13 | MAX = $MaxV:literal, |
14 | rot = $rot:literal, |
15 | rot_op = $rot_op:literal, |
16 | rot_result = $rot_result:literal, |
17 | swap_op = $swap_op:literal, |
18 | swapped = $swapped:literal, |
19 | reversed = $reversed:literal, |
20 | le_bytes = $le_bytes:literal, |
21 | be_bytes = $be_bytes:literal, |
22 | to_xe_bytes_doc = $to_xe_bytes_doc:expr, |
23 | from_xe_bytes_doc = $from_xe_bytes_doc:expr, |
24 | bound_condition = $bound_condition:literal, |
25 | ) => { |
26 | /// The smallest value that can be represented by this integer type. |
27 | /// |
28 | /// # Examples |
29 | /// |
30 | /// Basic usage: |
31 | /// |
32 | /// ``` |
33 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MIN, 0);" )] |
34 | /// ``` |
35 | #[stable(feature = "assoc_int_consts" , since = "1.43.0" )] |
36 | pub const MIN: Self = 0; |
37 | |
38 | /// The largest value that can be represented by this integer type |
39 | #[doc = concat!("(2<sup>" , $BITS, "</sup> − 1" , $bound_condition, ")." )] |
40 | /// |
41 | /// # Examples |
42 | /// |
43 | /// Basic usage: |
44 | /// |
45 | /// ``` |
46 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MAX, " , stringify!($MaxV), ");" )] |
47 | /// ``` |
48 | #[stable(feature = "assoc_int_consts" , since = "1.43.0" )] |
49 | pub const MAX: Self = !0; |
50 | |
51 | /// The size of this integer type in bits. |
52 | /// |
53 | /// # Examples |
54 | /// |
55 | /// ``` |
56 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::BITS, " , stringify!($BITS), ");" )] |
57 | /// ``` |
58 | #[stable(feature = "int_bits_const" , since = "1.53.0" )] |
59 | pub const BITS: u32 = Self::MAX.count_ones(); |
60 | |
61 | /// Returns the number of ones in the binary representation of `self`. |
62 | /// |
63 | /// # Examples |
64 | /// |
65 | /// Basic usage: |
66 | /// |
67 | /// ``` |
68 | #[doc = concat!("let n = 0b01001100" , stringify!($SelfT), ";" )] |
69 | /// |
70 | /// assert_eq!(n.count_ones(), 3); |
71 | /// ``` |
72 | #[stable(feature = "rust1" , since = "1.0.0" )] |
73 | #[rustc_const_stable(feature = "const_math" , since = "1.32.0" )] |
74 | #[doc(alias = "popcount" )] |
75 | #[doc(alias = "popcnt" )] |
76 | #[must_use = "this returns the result of the operation, \ |
77 | without modifying the original" ] |
78 | #[inline(always)] |
79 | pub const fn count_ones(self) -> u32 { |
80 | #[cfg(not(bootstrap))] |
81 | return intrinsics::ctpop(self as $ActualT); |
82 | #[cfg(bootstrap)] |
83 | return intrinsics::ctpop(self as $ActualT) as u32; |
84 | } |
85 | |
86 | /// Returns the number of zeros in the binary representation of `self`. |
87 | /// |
88 | /// # Examples |
89 | /// |
90 | /// Basic usage: |
91 | /// |
92 | /// ``` |
93 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MAX.count_zeros(), 0);" )] |
94 | /// ``` |
95 | #[stable(feature = "rust1" , since = "1.0.0" )] |
96 | #[rustc_const_stable(feature = "const_math" , since = "1.32.0" )] |
97 | #[must_use = "this returns the result of the operation, \ |
98 | without modifying the original" ] |
99 | #[inline(always)] |
100 | pub const fn count_zeros(self) -> u32 { |
101 | (!self).count_ones() |
102 | } |
103 | |
104 | /// Returns the number of leading zeros in the binary representation of `self`. |
105 | /// |
106 | /// Depending on what you're doing with the value, you might also be interested in the |
107 | /// [`ilog2`] function which returns a consistent number, even if the type widens. |
108 | /// |
109 | /// # Examples |
110 | /// |
111 | /// Basic usage: |
112 | /// |
113 | /// ``` |
114 | #[doc = concat!("let n = " , stringify!($SelfT), "::MAX >> 2;" )] |
115 | /// |
116 | /// assert_eq!(n.leading_zeros(), 2); |
117 | /// ``` |
118 | #[doc = concat!("[`ilog2`]: " , stringify!($SelfT), "::ilog2" )] |
119 | #[stable(feature = "rust1" , since = "1.0.0" )] |
120 | #[rustc_const_stable(feature = "const_math" , since = "1.32.0" )] |
121 | #[must_use = "this returns the result of the operation, \ |
122 | without modifying the original" ] |
123 | #[inline(always)] |
124 | pub const fn leading_zeros(self) -> u32 { |
125 | #[cfg(not(bootstrap))] |
126 | return intrinsics::ctlz(self as $ActualT); |
127 | #[cfg(bootstrap)] |
128 | return intrinsics::ctlz(self as $ActualT) as u32; |
129 | } |
130 | |
131 | /// Returns the number of trailing zeros in the binary representation |
132 | /// of `self`. |
133 | /// |
134 | /// # Examples |
135 | /// |
136 | /// Basic usage: |
137 | /// |
138 | /// ``` |
139 | #[doc = concat!("let n = 0b0101000" , stringify!($SelfT), ";" )] |
140 | /// |
141 | /// assert_eq!(n.trailing_zeros(), 3); |
142 | /// ``` |
143 | #[stable(feature = "rust1" , since = "1.0.0" )] |
144 | #[rustc_const_stable(feature = "const_math" , since = "1.32.0" )] |
145 | #[must_use = "this returns the result of the operation, \ |
146 | without modifying the original" ] |
147 | #[inline(always)] |
148 | pub const fn trailing_zeros(self) -> u32 { |
149 | #[cfg(not(bootstrap))] |
150 | return intrinsics::cttz(self); |
151 | #[cfg(bootstrap)] |
152 | return intrinsics::cttz(self) as u32; |
153 | } |
154 | |
155 | /// Returns the number of leading ones in the binary representation of `self`. |
156 | /// |
157 | /// # Examples |
158 | /// |
159 | /// Basic usage: |
160 | /// |
161 | /// ``` |
162 | #[doc = concat!("let n = !(" , stringify!($SelfT), "::MAX >> 2);" )] |
163 | /// |
164 | /// assert_eq!(n.leading_ones(), 2); |
165 | /// ``` |
166 | #[stable(feature = "leading_trailing_ones" , since = "1.46.0" )] |
167 | #[rustc_const_stable(feature = "leading_trailing_ones" , since = "1.46.0" )] |
168 | #[must_use = "this returns the result of the operation, \ |
169 | without modifying the original" ] |
170 | #[inline(always)] |
171 | pub const fn leading_ones(self) -> u32 { |
172 | (!self).leading_zeros() |
173 | } |
174 | |
175 | /// Returns the number of trailing ones in the binary representation |
176 | /// of `self`. |
177 | /// |
178 | /// # Examples |
179 | /// |
180 | /// Basic usage: |
181 | /// |
182 | /// ``` |
183 | #[doc = concat!("let n = 0b1010111" , stringify!($SelfT), ";" )] |
184 | /// |
185 | /// assert_eq!(n.trailing_ones(), 3); |
186 | /// ``` |
187 | #[stable(feature = "leading_trailing_ones" , since = "1.46.0" )] |
188 | #[rustc_const_stable(feature = "leading_trailing_ones" , since = "1.46.0" )] |
189 | #[must_use = "this returns the result of the operation, \ |
190 | without modifying the original" ] |
191 | #[inline(always)] |
192 | pub const fn trailing_ones(self) -> u32 { |
193 | (!self).trailing_zeros() |
194 | } |
195 | |
196 | /// Shifts the bits to the left by a specified amount, `n`, |
197 | /// wrapping the truncated bits to the end of the resulting integer. |
198 | /// |
199 | /// Please note this isn't the same operation as the `<<` shifting operator! |
200 | /// |
201 | /// # Examples |
202 | /// |
203 | /// Basic usage: |
204 | /// |
205 | /// ``` |
206 | #[doc = concat!("let n = " , $rot_op, stringify!($SelfT), ";" )] |
207 | #[doc = concat!("let m = " , $rot_result, ";" )] |
208 | /// |
209 | #[doc = concat!("assert_eq!(n.rotate_left(" , $rot, "), m);" )] |
210 | /// ``` |
211 | #[stable(feature = "rust1" , since = "1.0.0" )] |
212 | #[rustc_const_stable(feature = "const_math" , since = "1.32.0" )] |
213 | #[must_use = "this returns the result of the operation, \ |
214 | without modifying the original" ] |
215 | #[inline(always)] |
216 | pub const fn rotate_left(self, n: u32) -> Self { |
217 | #[cfg(not(bootstrap))] |
218 | return intrinsics::rotate_left(self, n); |
219 | #[cfg(bootstrap)] |
220 | return intrinsics::rotate_left(self, n as $SelfT); |
221 | } |
222 | |
223 | /// Shifts the bits to the right by a specified amount, `n`, |
224 | /// wrapping the truncated bits to the beginning of the resulting |
225 | /// integer. |
226 | /// |
227 | /// Please note this isn't the same operation as the `>>` shifting operator! |
228 | /// |
229 | /// # Examples |
230 | /// |
231 | /// Basic usage: |
232 | /// |
233 | /// ``` |
234 | #[doc = concat!("let n = " , $rot_result, stringify!($SelfT), ";" )] |
235 | #[doc = concat!("let m = " , $rot_op, ";" )] |
236 | /// |
237 | #[doc = concat!("assert_eq!(n.rotate_right(" , $rot, "), m);" )] |
238 | /// ``` |
239 | #[stable(feature = "rust1" , since = "1.0.0" )] |
240 | #[rustc_const_stable(feature = "const_math" , since = "1.32.0" )] |
241 | #[must_use = "this returns the result of the operation, \ |
242 | without modifying the original" ] |
243 | #[inline(always)] |
244 | pub const fn rotate_right(self, n: u32) -> Self { |
245 | #[cfg(not(bootstrap))] |
246 | return intrinsics::rotate_right(self, n); |
247 | #[cfg(bootstrap)] |
248 | return intrinsics::rotate_right(self, n as $SelfT); |
249 | } |
250 | |
251 | /// Reverses the byte order of the integer. |
252 | /// |
253 | /// # Examples |
254 | /// |
255 | /// Basic usage: |
256 | /// |
257 | /// ``` |
258 | #[doc = concat!("let n = " , $swap_op, stringify!($SelfT), ";" )] |
259 | /// let m = n.swap_bytes(); |
260 | /// |
261 | #[doc = concat!("assert_eq!(m, " , $swapped, ");" )] |
262 | /// ``` |
263 | #[stable(feature = "rust1" , since = "1.0.0" )] |
264 | #[rustc_const_stable(feature = "const_math" , since = "1.32.0" )] |
265 | #[must_use = "this returns the result of the operation, \ |
266 | without modifying the original" ] |
267 | #[inline(always)] |
268 | pub const fn swap_bytes(self) -> Self { |
269 | intrinsics::bswap(self as $ActualT) as Self |
270 | } |
271 | |
272 | /// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit, |
273 | /// second least-significant bit becomes second most-significant bit, etc. |
274 | /// |
275 | /// # Examples |
276 | /// |
277 | /// Basic usage: |
278 | /// |
279 | /// ``` |
280 | #[doc = concat!("let n = " , $swap_op, stringify!($SelfT), ";" )] |
281 | /// let m = n.reverse_bits(); |
282 | /// |
283 | #[doc = concat!("assert_eq!(m, " , $reversed, ");" )] |
284 | #[doc = concat!("assert_eq!(0, 0" , stringify!($SelfT), ".reverse_bits());" )] |
285 | /// ``` |
286 | #[stable(feature = "reverse_bits" , since = "1.37.0" )] |
287 | #[rustc_const_stable(feature = "reverse_bits" , since = "1.37.0" )] |
288 | #[must_use = "this returns the result of the operation, \ |
289 | without modifying the original" ] |
290 | #[inline(always)] |
291 | pub const fn reverse_bits(self) -> Self { |
292 | intrinsics::bitreverse(self as $ActualT) as Self |
293 | } |
294 | |
295 | /// Converts an integer from big endian to the target's endianness. |
296 | /// |
297 | /// On big endian this is a no-op. On little endian the bytes are |
298 | /// swapped. |
299 | /// |
300 | /// # Examples |
301 | /// |
302 | /// Basic usage: |
303 | /// |
304 | /// ``` |
305 | #[doc = concat!("let n = 0x1A" , stringify!($SelfT), ";" )] |
306 | /// |
307 | /// if cfg!(target_endian = "big") { |
308 | #[doc = concat!(" assert_eq!(" , stringify!($SelfT), "::from_be(n), n)" )] |
309 | /// } else { |
310 | #[doc = concat!(" assert_eq!(" , stringify!($SelfT), "::from_be(n), n.swap_bytes())" )] |
311 | /// } |
312 | /// ``` |
313 | #[stable(feature = "rust1" , since = "1.0.0" )] |
314 | #[rustc_const_stable(feature = "const_math" , since = "1.32.0" )] |
315 | #[must_use] |
316 | #[inline(always)] |
317 | pub const fn from_be(x: Self) -> Self { |
318 | #[cfg(target_endian = "big" )] |
319 | { |
320 | x |
321 | } |
322 | #[cfg(not(target_endian = "big" ))] |
323 | { |
324 | x.swap_bytes() |
325 | } |
326 | } |
327 | |
328 | /// Converts an integer from little endian to the target's endianness. |
329 | /// |
330 | /// On little endian this is a no-op. On big endian the bytes are |
331 | /// swapped. |
332 | /// |
333 | /// # Examples |
334 | /// |
335 | /// Basic usage: |
336 | /// |
337 | /// ``` |
338 | #[doc = concat!("let n = 0x1A" , stringify!($SelfT), ";" )] |
339 | /// |
340 | /// if cfg!(target_endian = "little") { |
341 | #[doc = concat!(" assert_eq!(" , stringify!($SelfT), "::from_le(n), n)" )] |
342 | /// } else { |
343 | #[doc = concat!(" assert_eq!(" , stringify!($SelfT), "::from_le(n), n.swap_bytes())" )] |
344 | /// } |
345 | /// ``` |
346 | #[stable(feature = "rust1" , since = "1.0.0" )] |
347 | #[rustc_const_stable(feature = "const_math" , since = "1.32.0" )] |
348 | #[must_use] |
349 | #[inline(always)] |
350 | pub const fn from_le(x: Self) -> Self { |
351 | #[cfg(target_endian = "little" )] |
352 | { |
353 | x |
354 | } |
355 | #[cfg(not(target_endian = "little" ))] |
356 | { |
357 | x.swap_bytes() |
358 | } |
359 | } |
360 | |
361 | /// Converts `self` to big endian from the target's endianness. |
362 | /// |
363 | /// On big endian this is a no-op. On little endian the bytes are |
364 | /// swapped. |
365 | /// |
366 | /// # Examples |
367 | /// |
368 | /// Basic usage: |
369 | /// |
370 | /// ``` |
371 | #[doc = concat!("let n = 0x1A" , stringify!($SelfT), ";" )] |
372 | /// |
373 | /// if cfg!(target_endian = "big") { |
374 | /// assert_eq!(n.to_be(), n) |
375 | /// } else { |
376 | /// assert_eq!(n.to_be(), n.swap_bytes()) |
377 | /// } |
378 | /// ``` |
379 | #[stable(feature = "rust1" , since = "1.0.0" )] |
380 | #[rustc_const_stable(feature = "const_math" , since = "1.32.0" )] |
381 | #[must_use = "this returns the result of the operation, \ |
382 | without modifying the original" ] |
383 | #[inline(always)] |
384 | pub const fn to_be(self) -> Self { // or not to be? |
385 | #[cfg(target_endian = "big" )] |
386 | { |
387 | self |
388 | } |
389 | #[cfg(not(target_endian = "big" ))] |
390 | { |
391 | self.swap_bytes() |
392 | } |
393 | } |
394 | |
395 | /// Converts `self` to little endian from the target's endianness. |
396 | /// |
397 | /// On little endian this is a no-op. On big endian the bytes are |
398 | /// swapped. |
399 | /// |
400 | /// # Examples |
401 | /// |
402 | /// Basic usage: |
403 | /// |
404 | /// ``` |
405 | #[doc = concat!("let n = 0x1A" , stringify!($SelfT), ";" )] |
406 | /// |
407 | /// if cfg!(target_endian = "little") { |
408 | /// assert_eq!(n.to_le(), n) |
409 | /// } else { |
410 | /// assert_eq!(n.to_le(), n.swap_bytes()) |
411 | /// } |
412 | /// ``` |
413 | #[stable(feature = "rust1" , since = "1.0.0" )] |
414 | #[rustc_const_stable(feature = "const_math" , since = "1.32.0" )] |
415 | #[must_use = "this returns the result of the operation, \ |
416 | without modifying the original" ] |
417 | #[inline(always)] |
418 | pub const fn to_le(self) -> Self { |
419 | #[cfg(target_endian = "little" )] |
420 | { |
421 | self |
422 | } |
423 | #[cfg(not(target_endian = "little" ))] |
424 | { |
425 | self.swap_bytes() |
426 | } |
427 | } |
428 | |
429 | /// Checked integer addition. Computes `self + rhs`, returning `None` |
430 | /// if overflow occurred. |
431 | /// |
432 | /// # Examples |
433 | /// |
434 | /// Basic usage: |
435 | /// |
436 | /// ``` |
437 | #[doc = concat!( |
438 | "assert_eq!((" , stringify!($SelfT), "::MAX - 2).checked_add(1), " , |
439 | "Some(" , stringify!($SelfT), "::MAX - 1));" |
440 | )] |
441 | #[doc = concat!("assert_eq!((" , stringify!($SelfT), "::MAX - 2).checked_add(3), None);" )] |
442 | /// ``` |
443 | #[stable(feature = "rust1" , since = "1.0.0" )] |
444 | #[rustc_const_stable(feature = "const_checked_int_methods" , since = "1.47.0" )] |
445 | #[must_use = "this returns the result of the operation, \ |
446 | without modifying the original" ] |
447 | #[inline] |
448 | pub const fn checked_add(self, rhs: Self) -> Option<Self> { |
449 | let (a, b) = self.overflowing_add(rhs); |
450 | if unlikely!(b) { None } else { Some(a) } |
451 | } |
452 | |
453 | /// Strict integer addition. Computes `self + rhs`, panicking |
454 | /// if overflow occurred. |
455 | /// |
456 | /// # Panics |
457 | /// |
458 | /// ## Overflow behavior |
459 | /// |
460 | /// This function will always panic on overflow, regardless of whether overflow checks are enabled. |
461 | /// |
462 | /// # Examples |
463 | /// |
464 | /// Basic usage: |
465 | /// |
466 | /// ``` |
467 | /// #![feature(strict_overflow_ops)] |
468 | #[doc = concat!("assert_eq!((" , stringify!($SelfT), "::MAX - 2).strict_add(1), " , stringify!($SelfT), "::MAX - 1);" )] |
469 | /// ``` |
470 | /// |
471 | /// The following panics because of overflow: |
472 | /// |
473 | /// ```should_panic |
474 | /// #![feature(strict_overflow_ops)] |
475 | #[doc = concat!("let _ = (" , stringify!($SelfT), "::MAX - 2).strict_add(3);" )] |
476 | /// ``` |
477 | #[unstable(feature = "strict_overflow_ops" , issue = "118260" )] |
478 | #[rustc_const_unstable(feature = "const_strict_overflow_ops" , issue = "118260" )] |
479 | #[must_use = "this returns the result of the operation, \ |
480 | without modifying the original" ] |
481 | #[inline] |
482 | #[track_caller] |
483 | pub const fn strict_add(self, rhs: Self) -> Self { |
484 | let (a, b) = self.overflowing_add(rhs); |
485 | if unlikely!(b) { overflow_panic ::add()} else {a} |
486 | } |
487 | |
488 | /// Unchecked integer addition. Computes `self + rhs`, assuming overflow |
489 | /// cannot occur. |
490 | /// |
491 | /// Calling `x.unchecked_add(y)` is semantically equivalent to calling |
492 | /// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`. |
493 | /// |
494 | /// If you're just trying to avoid the panic in debug mode, then **do not** |
495 | /// use this. Instead, you're looking for [`wrapping_add`]. |
496 | /// |
497 | /// # Safety |
498 | /// |
499 | /// This results in undefined behavior when |
500 | #[doc = concat!("`self + rhs > " , stringify!($SelfT), "::MAX` or `self + rhs < " , stringify!($SelfT), "::MIN`," )] |
501 | /// i.e. when [`checked_add`] would return `None`. |
502 | /// |
503 | /// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked |
504 | #[doc = concat!("[`checked_add`]: " , stringify!($SelfT), "::checked_add" )] |
505 | #[doc = concat!("[`wrapping_add`]: " , stringify!($SelfT), "::wrapping_add" )] |
506 | #[stable(feature = "unchecked_math" , since = "CURRENT_RUSTC_VERSION" )] |
507 | #[rustc_const_stable(feature = "unchecked_math" , since = "CURRENT_RUSTC_VERSION" )] |
508 | #[must_use = "this returns the result of the operation, \ |
509 | without modifying the original" ] |
510 | #[inline(always)] |
511 | #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces |
512 | pub const unsafe fn unchecked_add(self, rhs: Self) -> Self { |
513 | // SAFETY: the caller must uphold the safety contract for |
514 | // `unchecked_add`. |
515 | unsafe { intrinsics::unchecked_add(self, rhs) } |
516 | } |
517 | |
518 | /// Checked addition with a signed integer. Computes `self + rhs`, |
519 | /// returning `None` if overflow occurred. |
520 | /// |
521 | /// # Examples |
522 | /// |
523 | /// Basic usage: |
524 | /// |
525 | /// ``` |
526 | #[doc = concat!("assert_eq!(1" , stringify!($SelfT), ".checked_add_signed(2), Some(3));" )] |
527 | #[doc = concat!("assert_eq!(1" , stringify!($SelfT), ".checked_add_signed(-2), None);" )] |
528 | #[doc = concat!("assert_eq!((" , stringify!($SelfT), "::MAX - 2).checked_add_signed(3), None);" )] |
529 | /// ``` |
530 | #[stable(feature = "mixed_integer_ops" , since = "1.66.0" )] |
531 | #[rustc_const_stable(feature = "mixed_integer_ops" , since = "1.66.0" )] |
532 | #[must_use = "this returns the result of the operation, \ |
533 | without modifying the original" ] |
534 | #[inline] |
535 | pub const fn checked_add_signed(self, rhs: $SignedT) -> Option<Self> { |
536 | let (a, b) = self.overflowing_add_signed(rhs); |
537 | if unlikely!(b) { None } else { Some(a) } |
538 | } |
539 | |
540 | /// Strict addition with a signed integer. Computes `self + rhs`, |
541 | /// panicking if overflow occurred. |
542 | /// |
543 | /// # Panics |
544 | /// |
545 | /// ## Overflow behavior |
546 | /// |
547 | /// This function will always panic on overflow, regardless of whether overflow checks are enabled. |
548 | /// |
549 | /// # Examples |
550 | /// |
551 | /// Basic usage: |
552 | /// |
553 | /// ``` |
554 | /// #![feature(strict_overflow_ops)] |
555 | #[doc = concat!("assert_eq!(1" , stringify!($SelfT), ".strict_add_signed(2), 3);" )] |
556 | /// ``` |
557 | /// |
558 | /// The following panic because of overflow: |
559 | /// |
560 | /// ```should_panic |
561 | /// #![feature(strict_overflow_ops)] |
562 | #[doc = concat!("let _ = 1" , stringify!($SelfT), ".strict_add_signed(-2);" )] |
563 | /// ``` |
564 | /// |
565 | /// ```should_panic |
566 | /// #![feature(strict_overflow_ops)] |
567 | #[doc = concat!("let _ = (" , stringify!($SelfT), "::MAX - 2).strict_add_signed(3);" )] |
568 | /// ``` |
569 | #[unstable(feature = "strict_overflow_ops" , issue = "118260" )] |
570 | #[rustc_const_unstable(feature = "const_strict_overflow_ops" , issue = "118260" )] |
571 | #[must_use = "this returns the result of the operation, \ |
572 | without modifying the original" ] |
573 | #[inline] |
574 | #[track_caller] |
575 | pub const fn strict_add_signed(self, rhs: $SignedT) -> Self { |
576 | let (a, b) = self.overflowing_add_signed(rhs); |
577 | if unlikely!(b) { overflow_panic ::add()} else {a} |
578 | } |
579 | |
580 | /// Checked integer subtraction. Computes `self - rhs`, returning |
581 | /// `None` if overflow occurred. |
582 | /// |
583 | /// # Examples |
584 | /// |
585 | /// Basic usage: |
586 | /// |
587 | /// ``` |
588 | #[doc = concat!("assert_eq!(1" , stringify!($SelfT), ".checked_sub(1), Some(0));" )] |
589 | #[doc = concat!("assert_eq!(0" , stringify!($SelfT), ".checked_sub(1), None);" )] |
590 | /// ``` |
591 | #[stable(feature = "rust1" , since = "1.0.0" )] |
592 | #[rustc_const_stable(feature = "const_checked_int_methods" , since = "1.47.0" )] |
593 | #[must_use = "this returns the result of the operation, \ |
594 | without modifying the original" ] |
595 | #[inline] |
596 | pub const fn checked_sub(self, rhs: Self) -> Option<Self> { |
597 | // Per PR#103299, there's no advantage to the `overflowing` intrinsic |
598 | // for *unsigned* subtraction and we just emit the manual check anyway. |
599 | // Thus, rather than using `overflowing_sub` that produces a wrapping |
600 | // subtraction, check it ourself so we can use an unchecked one. |
601 | |
602 | if self >= rhs { |
603 | // SAFETY: just checked this can't overflow |
604 | Some(unsafe { intrinsics::unchecked_sub(self, rhs) }) |
605 | } else { |
606 | None |
607 | } |
608 | } |
609 | |
610 | /// Strict integer subtraction. Computes `self - rhs`, panicking if |
611 | /// overflow occurred. |
612 | /// |
613 | /// # Panics |
614 | /// |
615 | /// ## Overflow behavior |
616 | /// |
617 | /// This function will always panic on overflow, regardless of whether overflow checks are enabled. |
618 | /// |
619 | /// # Examples |
620 | /// |
621 | /// Basic usage: |
622 | /// |
623 | /// ``` |
624 | /// #![feature(strict_overflow_ops)] |
625 | #[doc = concat!("assert_eq!(1" , stringify!($SelfT), ".strict_sub(1), 0);" )] |
626 | /// ``` |
627 | /// |
628 | /// The following panics because of overflow: |
629 | /// |
630 | /// ```should_panic |
631 | /// #![feature(strict_overflow_ops)] |
632 | #[doc = concat!("let _ = 0" , stringify!($SelfT), ".strict_sub(1);" )] |
633 | /// ``` |
634 | #[unstable(feature = "strict_overflow_ops" , issue = "118260" )] |
635 | #[rustc_const_unstable(feature = "const_strict_overflow_ops" , issue = "118260" )] |
636 | #[must_use = "this returns the result of the operation, \ |
637 | without modifying the original" ] |
638 | #[inline] |
639 | #[track_caller] |
640 | pub const fn strict_sub(self, rhs: Self) -> Self { |
641 | let (a, b) = self.overflowing_sub(rhs); |
642 | if unlikely!(b) { overflow_panic ::sub()} else {a} |
643 | } |
644 | |
645 | /// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow |
646 | /// cannot occur. |
647 | /// |
648 | /// Calling `x.unchecked_sub(y)` is semantically equivalent to calling |
649 | /// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`. |
650 | /// |
651 | /// If you're just trying to avoid the panic in debug mode, then **do not** |
652 | /// use this. Instead, you're looking for [`wrapping_sub`]. |
653 | /// |
654 | /// # Safety |
655 | /// |
656 | /// This results in undefined behavior when |
657 | #[doc = concat!("`self - rhs > " , stringify!($SelfT), "::MAX` or `self - rhs < " , stringify!($SelfT), "::MIN`," )] |
658 | /// i.e. when [`checked_sub`] would return `None`. |
659 | /// |
660 | /// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked |
661 | #[doc = concat!("[`checked_sub`]: " , stringify!($SelfT), "::checked_sub" )] |
662 | #[doc = concat!("[`wrapping_sub`]: " , stringify!($SelfT), "::wrapping_sub" )] |
663 | #[stable(feature = "unchecked_math" , since = "CURRENT_RUSTC_VERSION" )] |
664 | #[rustc_const_stable(feature = "unchecked_math" , since = "CURRENT_RUSTC_VERSION" )] |
665 | #[must_use = "this returns the result of the operation, \ |
666 | without modifying the original" ] |
667 | #[inline(always)] |
668 | #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces |
669 | pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self { |
670 | // SAFETY: the caller must uphold the safety contract for |
671 | // `unchecked_sub`. |
672 | unsafe { intrinsics::unchecked_sub(self, rhs) } |
673 | } |
674 | |
675 | /// Checked integer multiplication. Computes `self * rhs`, returning |
676 | /// `None` if overflow occurred. |
677 | /// |
678 | /// # Examples |
679 | /// |
680 | /// Basic usage: |
681 | /// |
682 | /// ``` |
683 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".checked_mul(1), Some(5));" )] |
684 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MAX.checked_mul(2), None);" )] |
685 | /// ``` |
686 | #[stable(feature = "rust1" , since = "1.0.0" )] |
687 | #[rustc_const_stable(feature = "const_checked_int_methods" , since = "1.47.0" )] |
688 | #[must_use = "this returns the result of the operation, \ |
689 | without modifying the original" ] |
690 | #[inline] |
691 | pub const fn checked_mul(self, rhs: Self) -> Option<Self> { |
692 | let (a, b) = self.overflowing_mul(rhs); |
693 | if unlikely!(b) { None } else { Some(a) } |
694 | } |
695 | |
696 | /// Strict integer multiplication. Computes `self * rhs`, panicking if |
697 | /// overflow occurred. |
698 | /// |
699 | /// # Panics |
700 | /// |
701 | /// ## Overflow behavior |
702 | /// |
703 | /// This function will always panic on overflow, regardless of whether overflow checks are enabled. |
704 | /// |
705 | /// # Examples |
706 | /// |
707 | /// Basic usage: |
708 | /// |
709 | /// ``` |
710 | /// #![feature(strict_overflow_ops)] |
711 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".strict_mul(1), 5);" )] |
712 | /// ``` |
713 | /// |
714 | /// The following panics because of overflow: |
715 | /// |
716 | /// ``` should_panic |
717 | /// #![feature(strict_overflow_ops)] |
718 | #[doc = concat!("let _ = " , stringify!($SelfT), "::MAX.strict_mul(2);" )] |
719 | /// ``` |
720 | #[unstable(feature = "strict_overflow_ops" , issue = "118260" )] |
721 | #[rustc_const_unstable(feature = "const_strict_overflow_ops" , issue = "118260" )] |
722 | #[must_use = "this returns the result of the operation, \ |
723 | without modifying the original" ] |
724 | #[inline] |
725 | #[track_caller] |
726 | pub const fn strict_mul(self, rhs: Self) -> Self { |
727 | let (a, b) = self.overflowing_mul(rhs); |
728 | if unlikely!(b) { overflow_panic ::mul()} else {a} |
729 | } |
730 | |
731 | /// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow |
732 | /// cannot occur. |
733 | /// |
734 | /// Calling `x.unchecked_mul(y)` is semantically equivalent to calling |
735 | /// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`. |
736 | /// |
737 | /// If you're just trying to avoid the panic in debug mode, then **do not** |
738 | /// use this. Instead, you're looking for [`wrapping_mul`]. |
739 | /// |
740 | /// # Safety |
741 | /// |
742 | /// This results in undefined behavior when |
743 | #[doc = concat!("`self * rhs > " , stringify!($SelfT), "::MAX` or `self * rhs < " , stringify!($SelfT), "::MIN`," )] |
744 | /// i.e. when [`checked_mul`] would return `None`. |
745 | /// |
746 | /// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked |
747 | #[doc = concat!("[`checked_mul`]: " , stringify!($SelfT), "::checked_mul" )] |
748 | #[doc = concat!("[`wrapping_mul`]: " , stringify!($SelfT), "::wrapping_mul" )] |
749 | #[stable(feature = "unchecked_math" , since = "CURRENT_RUSTC_VERSION" )] |
750 | #[rustc_const_stable(feature = "unchecked_math" , since = "CURRENT_RUSTC_VERSION" )] |
751 | #[must_use = "this returns the result of the operation, \ |
752 | without modifying the original" ] |
753 | #[inline(always)] |
754 | #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces |
755 | pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self { |
756 | // SAFETY: the caller must uphold the safety contract for |
757 | // `unchecked_mul`. |
758 | unsafe { intrinsics::unchecked_mul(self, rhs) } |
759 | } |
760 | |
761 | /// Checked integer division. Computes `self / rhs`, returning `None` |
762 | /// if `rhs == 0`. |
763 | /// |
764 | /// # Examples |
765 | /// |
766 | /// Basic usage: |
767 | /// |
768 | /// ``` |
769 | #[doc = concat!("assert_eq!(128" , stringify!($SelfT), ".checked_div(2), Some(64));" )] |
770 | #[doc = concat!("assert_eq!(1" , stringify!($SelfT), ".checked_div(0), None);" )] |
771 | /// ``` |
772 | #[stable(feature = "rust1" , since = "1.0.0" )] |
773 | #[rustc_const_stable(feature = "const_checked_int_div" , since = "1.52.0" )] |
774 | #[must_use = "this returns the result of the operation, \ |
775 | without modifying the original" ] |
776 | #[inline] |
777 | pub const fn checked_div(self, rhs: Self) -> Option<Self> { |
778 | if unlikely!(rhs == 0) { |
779 | None |
780 | } else { |
781 | // SAFETY: div by zero has been checked above and unsigned types have no other |
782 | // failure modes for division |
783 | Some(unsafe { intrinsics::unchecked_div(self, rhs) }) |
784 | } |
785 | } |
786 | |
787 | /// Strict integer division. Computes `self / rhs`. |
788 | /// Strict division on unsigned types is just normal division. |
789 | /// There's no way overflow could ever happen. |
790 | /// This function exists, so that all operations |
791 | /// are accounted for in the strict operations. |
792 | /// |
793 | /// # Panics |
794 | /// |
795 | /// This function will panic if `rhs` is zero. |
796 | /// |
797 | /// # Examples |
798 | /// |
799 | /// Basic usage: |
800 | /// |
801 | /// ``` |
802 | /// #![feature(strict_overflow_ops)] |
803 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".strict_div(10), 10);" )] |
804 | /// ``` |
805 | /// |
806 | /// The following panics because of division by zero: |
807 | /// |
808 | /// ```should_panic |
809 | /// #![feature(strict_overflow_ops)] |
810 | #[doc = concat!("let _ = (1" , stringify!($SelfT), ").strict_div(0);" )] |
811 | /// ``` |
812 | #[unstable(feature = "strict_overflow_ops" , issue = "118260" )] |
813 | #[rustc_const_unstable(feature = "const_strict_overflow_ops" , issue = "118260" )] |
814 | #[must_use = "this returns the result of the operation, \ |
815 | without modifying the original" ] |
816 | #[inline(always)] |
817 | #[track_caller] |
818 | pub const fn strict_div(self, rhs: Self) -> Self { |
819 | self / rhs |
820 | } |
821 | |
822 | /// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None` |
823 | /// if `rhs == 0`. |
824 | /// |
825 | /// # Examples |
826 | /// |
827 | /// Basic usage: |
828 | /// |
829 | /// ``` |
830 | #[doc = concat!("assert_eq!(128" , stringify!($SelfT), ".checked_div_euclid(2), Some(64));" )] |
831 | #[doc = concat!("assert_eq!(1" , stringify!($SelfT), ".checked_div_euclid(0), None);" )] |
832 | /// ``` |
833 | #[stable(feature = "euclidean_division" , since = "1.38.0" )] |
834 | #[rustc_const_stable(feature = "const_euclidean_int_methods" , since = "1.52.0" )] |
835 | #[must_use = "this returns the result of the operation, \ |
836 | without modifying the original" ] |
837 | #[inline] |
838 | pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> { |
839 | if unlikely!(rhs == 0) { |
840 | None |
841 | } else { |
842 | Some(self.div_euclid(rhs)) |
843 | } |
844 | } |
845 | |
846 | /// Strict Euclidean division. Computes `self.div_euclid(rhs)`. |
847 | /// Strict division on unsigned types is just normal division. |
848 | /// There's no way overflow could ever happen. |
849 | /// This function exists, so that all operations |
850 | /// are accounted for in the strict operations. |
851 | /// Since, for the positive integers, all common |
852 | /// definitions of division are equal, this |
853 | /// is exactly equal to `self.strict_div(rhs)`. |
854 | /// |
855 | /// # Panics |
856 | /// |
857 | /// This function will panic if `rhs` is zero. |
858 | /// |
859 | /// # Examples |
860 | /// |
861 | /// Basic usage: |
862 | /// |
863 | /// ``` |
864 | /// #![feature(strict_overflow_ops)] |
865 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".strict_div_euclid(10), 10);" )] |
866 | /// ``` |
867 | /// The following panics because of division by zero: |
868 | /// |
869 | /// ```should_panic |
870 | /// #![feature(strict_overflow_ops)] |
871 | #[doc = concat!("let _ = (1" , stringify!($SelfT), ").strict_div_euclid(0);" )] |
872 | /// ``` |
873 | #[unstable(feature = "strict_overflow_ops" , issue = "118260" )] |
874 | #[rustc_const_unstable(feature = "const_strict_overflow_ops" , issue = "118260" )] |
875 | #[must_use = "this returns the result of the operation, \ |
876 | without modifying the original" ] |
877 | #[inline(always)] |
878 | #[track_caller] |
879 | pub const fn strict_div_euclid(self, rhs: Self) -> Self { |
880 | self / rhs |
881 | } |
882 | |
883 | /// Checked integer remainder. Computes `self % rhs`, returning `None` |
884 | /// if `rhs == 0`. |
885 | /// |
886 | /// # Examples |
887 | /// |
888 | /// Basic usage: |
889 | /// |
890 | /// ``` |
891 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".checked_rem(2), Some(1));" )] |
892 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".checked_rem(0), None);" )] |
893 | /// ``` |
894 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
895 | #[rustc_const_stable(feature = "const_checked_int_div" , since = "1.52.0" )] |
896 | #[must_use = "this returns the result of the operation, \ |
897 | without modifying the original" ] |
898 | #[inline] |
899 | pub const fn checked_rem(self, rhs: Self) -> Option<Self> { |
900 | if unlikely!(rhs == 0) { |
901 | None |
902 | } else { |
903 | // SAFETY: div by zero has been checked above and unsigned types have no other |
904 | // failure modes for division |
905 | Some(unsafe { intrinsics::unchecked_rem(self, rhs) }) |
906 | } |
907 | } |
908 | |
909 | /// Strict integer remainder. Computes `self % rhs`. |
910 | /// Strict remainder calculation on unsigned types is |
911 | /// just the regular remainder calculation. |
912 | /// There's no way overflow could ever happen. |
913 | /// This function exists, so that all operations |
914 | /// are accounted for in the strict operations. |
915 | /// |
916 | /// # Panics |
917 | /// |
918 | /// This function will panic if `rhs` is zero. |
919 | /// |
920 | /// # Examples |
921 | /// |
922 | /// Basic usage: |
923 | /// |
924 | /// ``` |
925 | /// #![feature(strict_overflow_ops)] |
926 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".strict_rem(10), 0);" )] |
927 | /// ``` |
928 | /// |
929 | /// The following panics because of division by zero: |
930 | /// |
931 | /// ```should_panic |
932 | /// #![feature(strict_overflow_ops)] |
933 | #[doc = concat!("let _ = 5" , stringify!($SelfT), ".strict_rem(0);" )] |
934 | /// ``` |
935 | #[unstable(feature = "strict_overflow_ops" , issue = "118260" )] |
936 | #[rustc_const_unstable(feature = "const_strict_overflow_ops" , issue = "118260" )] |
937 | #[must_use = "this returns the result of the operation, \ |
938 | without modifying the original" ] |
939 | #[inline(always)] |
940 | #[track_caller] |
941 | pub const fn strict_rem(self, rhs: Self) -> Self { |
942 | self % rhs |
943 | } |
944 | |
945 | /// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None` |
946 | /// if `rhs == 0`. |
947 | /// |
948 | /// # Examples |
949 | /// |
950 | /// Basic usage: |
951 | /// |
952 | /// ``` |
953 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".checked_rem_euclid(2), Some(1));" )] |
954 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".checked_rem_euclid(0), None);" )] |
955 | /// ``` |
956 | #[stable(feature = "euclidean_division" , since = "1.38.0" )] |
957 | #[rustc_const_stable(feature = "const_euclidean_int_methods" , since = "1.52.0" )] |
958 | #[must_use = "this returns the result of the operation, \ |
959 | without modifying the original" ] |
960 | #[inline] |
961 | pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> { |
962 | if unlikely!(rhs == 0) { |
963 | None |
964 | } else { |
965 | Some(self.rem_euclid(rhs)) |
966 | } |
967 | } |
968 | |
969 | /// Strict Euclidean modulo. Computes `self.rem_euclid(rhs)`. |
970 | /// Strict modulo calculation on unsigned types is |
971 | /// just the regular remainder calculation. |
972 | /// There's no way overflow could ever happen. |
973 | /// This function exists, so that all operations |
974 | /// are accounted for in the strict operations. |
975 | /// Since, for the positive integers, all common |
976 | /// definitions of division are equal, this |
977 | /// is exactly equal to `self.strict_rem(rhs)`. |
978 | /// |
979 | /// # Panics |
980 | /// |
981 | /// This function will panic if `rhs` is zero. |
982 | /// |
983 | /// # Examples |
984 | /// |
985 | /// Basic usage: |
986 | /// |
987 | /// ``` |
988 | /// #![feature(strict_overflow_ops)] |
989 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".strict_rem_euclid(10), 0);" )] |
990 | /// ``` |
991 | /// |
992 | /// The following panics because of division by zero: |
993 | /// |
994 | /// ```should_panic |
995 | /// #![feature(strict_overflow_ops)] |
996 | #[doc = concat!("let _ = 5" , stringify!($SelfT), ".strict_rem_euclid(0);" )] |
997 | /// ``` |
998 | #[unstable(feature = "strict_overflow_ops" , issue = "118260" )] |
999 | #[rustc_const_unstable(feature = "const_strict_overflow_ops" , issue = "118260" )] |
1000 | #[must_use = "this returns the result of the operation, \ |
1001 | without modifying the original" ] |
1002 | #[inline(always)] |
1003 | #[track_caller] |
1004 | pub const fn strict_rem_euclid(self, rhs: Self) -> Self { |
1005 | self % rhs |
1006 | } |
1007 | |
1008 | /// Returns the logarithm of the number with respect to an arbitrary base, |
1009 | /// rounded down. |
1010 | /// |
1011 | /// This method might not be optimized owing to implementation details; |
1012 | /// `ilog2` can produce results more efficiently for base 2, and `ilog10` |
1013 | /// can produce results more efficiently for base 10. |
1014 | /// |
1015 | /// # Panics |
1016 | /// |
1017 | /// This function will panic if `self` is zero, or if `base` is less than 2. |
1018 | /// |
1019 | /// # Examples |
1020 | /// |
1021 | /// ``` |
1022 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".ilog(5), 1);" )] |
1023 | /// ``` |
1024 | #[stable(feature = "int_log" , since = "1.67.0" )] |
1025 | #[rustc_const_stable(feature = "int_log" , since = "1.67.0" )] |
1026 | #[must_use = "this returns the result of the operation, \ |
1027 | without modifying the original" ] |
1028 | #[inline] |
1029 | #[track_caller] |
1030 | pub const fn ilog(self, base: Self) -> u32 { |
1031 | assert!(base >= 2, "base of integer logarithm must be at least 2" ); |
1032 | if let Some(log) = self.checked_ilog(base) { |
1033 | log |
1034 | } else { |
1035 | int_log10::panic_for_nonpositive_argument() |
1036 | } |
1037 | } |
1038 | |
1039 | /// Returns the base 2 logarithm of the number, rounded down. |
1040 | /// |
1041 | /// # Panics |
1042 | /// |
1043 | /// This function will panic if `self` is zero. |
1044 | /// |
1045 | /// # Examples |
1046 | /// |
1047 | /// ``` |
1048 | #[doc = concat!("assert_eq!(2" , stringify!($SelfT), ".ilog2(), 1);" )] |
1049 | /// ``` |
1050 | #[stable(feature = "int_log" , since = "1.67.0" )] |
1051 | #[rustc_const_stable(feature = "int_log" , since = "1.67.0" )] |
1052 | #[must_use = "this returns the result of the operation, \ |
1053 | without modifying the original" ] |
1054 | #[inline] |
1055 | #[track_caller] |
1056 | pub const fn ilog2(self) -> u32 { |
1057 | if let Some(log) = self.checked_ilog2() { |
1058 | log |
1059 | } else { |
1060 | int_log10::panic_for_nonpositive_argument() |
1061 | } |
1062 | } |
1063 | |
1064 | /// Returns the base 10 logarithm of the number, rounded down. |
1065 | /// |
1066 | /// # Panics |
1067 | /// |
1068 | /// This function will panic if `self` is zero. |
1069 | /// |
1070 | /// # Example |
1071 | /// |
1072 | /// ``` |
1073 | #[doc = concat!("assert_eq!(10" , stringify!($SelfT), ".ilog10(), 1);" )] |
1074 | /// ``` |
1075 | #[stable(feature = "int_log" , since = "1.67.0" )] |
1076 | #[rustc_const_stable(feature = "int_log" , since = "1.67.0" )] |
1077 | #[must_use = "this returns the result of the operation, \ |
1078 | without modifying the original" ] |
1079 | #[inline] |
1080 | #[track_caller] |
1081 | pub const fn ilog10(self) -> u32 { |
1082 | if let Some(log) = self.checked_ilog10() { |
1083 | log |
1084 | } else { |
1085 | int_log10::panic_for_nonpositive_argument() |
1086 | } |
1087 | } |
1088 | |
1089 | /// Returns the logarithm of the number with respect to an arbitrary base, |
1090 | /// rounded down. |
1091 | /// |
1092 | /// Returns `None` if the number is zero, or if the base is not at least 2. |
1093 | /// |
1094 | /// This method might not be optimized owing to implementation details; |
1095 | /// `checked_ilog2` can produce results more efficiently for base 2, and |
1096 | /// `checked_ilog10` can produce results more efficiently for base 10. |
1097 | /// |
1098 | /// # Examples |
1099 | /// |
1100 | /// ``` |
1101 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".checked_ilog(5), Some(1));" )] |
1102 | /// ``` |
1103 | #[stable(feature = "int_log" , since = "1.67.0" )] |
1104 | #[rustc_const_stable(feature = "int_log" , since = "1.67.0" )] |
1105 | #[must_use = "this returns the result of the operation, \ |
1106 | without modifying the original" ] |
1107 | #[inline] |
1108 | pub const fn checked_ilog(self, base: Self) -> Option<u32> { |
1109 | if self <= 0 || base <= 1 { |
1110 | None |
1111 | } else { |
1112 | let mut n = 0; |
1113 | let mut r = 1; |
1114 | |
1115 | // Optimization for 128 bit wide integers. |
1116 | if Self::BITS == 128 { |
1117 | // The following is a correct lower bound for ⌊log(base,self)⌋ because |
1118 | // |
1119 | // log(base,self) = log(2,self) / log(2,base) |
1120 | // ≥ ⌊log(2,self)⌋ / (⌊log(2,base)⌋ + 1) |
1121 | // |
1122 | // hence |
1123 | // |
1124 | // ⌊log(base,self)⌋ ≥ ⌊ ⌊log(2,self)⌋ / (⌊log(2,base)⌋ + 1) ⌋ . |
1125 | n = self.ilog2() / (base.ilog2() + 1); |
1126 | r = base.pow(n); |
1127 | } |
1128 | |
1129 | while r <= self / base { |
1130 | n += 1; |
1131 | r *= base; |
1132 | } |
1133 | Some(n) |
1134 | } |
1135 | } |
1136 | |
1137 | /// Returns the base 2 logarithm of the number, rounded down. |
1138 | /// |
1139 | /// Returns `None` if the number is zero. |
1140 | /// |
1141 | /// # Examples |
1142 | /// |
1143 | /// ``` |
1144 | #[doc = concat!("assert_eq!(2" , stringify!($SelfT), ".checked_ilog2(), Some(1));" )] |
1145 | /// ``` |
1146 | #[stable(feature = "int_log" , since = "1.67.0" )] |
1147 | #[rustc_const_stable(feature = "int_log" , since = "1.67.0" )] |
1148 | #[must_use = "this returns the result of the operation, \ |
1149 | without modifying the original" ] |
1150 | #[inline] |
1151 | pub const fn checked_ilog2(self) -> Option<u32> { |
1152 | // FIXME: Simply use `NonZero::new` once it is actually generic. |
1153 | if let Some(x) = <$NonZeroT>::new(self) { |
1154 | Some(x.ilog2()) |
1155 | } else { |
1156 | None |
1157 | } |
1158 | } |
1159 | |
1160 | /// Returns the base 10 logarithm of the number, rounded down. |
1161 | /// |
1162 | /// Returns `None` if the number is zero. |
1163 | /// |
1164 | /// # Examples |
1165 | /// |
1166 | /// ``` |
1167 | #[doc = concat!("assert_eq!(10" , stringify!($SelfT), ".checked_ilog10(), Some(1));" )] |
1168 | /// ``` |
1169 | #[stable(feature = "int_log" , since = "1.67.0" )] |
1170 | #[rustc_const_stable(feature = "int_log" , since = "1.67.0" )] |
1171 | #[must_use = "this returns the result of the operation, \ |
1172 | without modifying the original" ] |
1173 | #[inline] |
1174 | pub const fn checked_ilog10(self) -> Option<u32> { |
1175 | // FIXME: Simply use `NonZero::new` once it is actually generic. |
1176 | if let Some(x) = <$NonZeroT>::new(self) { |
1177 | Some(x.ilog10()) |
1178 | } else { |
1179 | None |
1180 | } |
1181 | } |
1182 | |
1183 | /// Checked negation. Computes `-self`, returning `None` unless `self == |
1184 | /// 0`. |
1185 | /// |
1186 | /// Note that negating any positive integer will overflow. |
1187 | /// |
1188 | /// # Examples |
1189 | /// |
1190 | /// Basic usage: |
1191 | /// |
1192 | /// ``` |
1193 | #[doc = concat!("assert_eq!(0" , stringify!($SelfT), ".checked_neg(), Some(0));" )] |
1194 | #[doc = concat!("assert_eq!(1" , stringify!($SelfT), ".checked_neg(), None);" )] |
1195 | /// ``` |
1196 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
1197 | #[rustc_const_stable(feature = "const_checked_int_methods" , since = "1.47.0" )] |
1198 | #[must_use = "this returns the result of the operation, \ |
1199 | without modifying the original" ] |
1200 | #[inline] |
1201 | pub const fn checked_neg(self) -> Option<Self> { |
1202 | let (a, b) = self.overflowing_neg(); |
1203 | if unlikely!(b) { None } else { Some(a) } |
1204 | } |
1205 | |
1206 | /// Strict negation. Computes `-self`, panicking unless `self == |
1207 | /// 0`. |
1208 | /// |
1209 | /// Note that negating any positive integer will overflow. |
1210 | /// |
1211 | /// # Panics |
1212 | /// |
1213 | /// ## Overflow behavior |
1214 | /// |
1215 | /// This function will always panic on overflow, regardless of whether overflow checks are enabled. |
1216 | /// |
1217 | /// # Examples |
1218 | /// |
1219 | /// Basic usage: |
1220 | /// |
1221 | /// ``` |
1222 | /// #![feature(strict_overflow_ops)] |
1223 | #[doc = concat!("assert_eq!(0" , stringify!($SelfT), ".strict_neg(), 0);" )] |
1224 | /// ``` |
1225 | /// |
1226 | /// The following panics because of overflow: |
1227 | /// |
1228 | /// ```should_panic |
1229 | /// #![feature(strict_overflow_ops)] |
1230 | #[doc = concat!("let _ = 1" , stringify!($SelfT), ".strict_neg();" )] |
1231 | /// |
1232 | #[unstable(feature = "strict_overflow_ops" , issue = "118260" )] |
1233 | #[rustc_const_unstable(feature = "const_strict_overflow_ops" , issue = "118260" )] |
1234 | #[must_use = "this returns the result of the operation, \ |
1235 | without modifying the original" ] |
1236 | #[inline] |
1237 | #[track_caller] |
1238 | pub const fn strict_neg(self) -> Self { |
1239 | let (a, b) = self.overflowing_neg(); |
1240 | if unlikely!(b) { overflow_panic::neg() } else { a } |
1241 | } |
1242 | |
1243 | /// Checked shift left. Computes `self << rhs`, returning `None` |
1244 | /// if `rhs` is larger than or equal to the number of bits in `self`. |
1245 | /// |
1246 | /// # Examples |
1247 | /// |
1248 | /// Basic usage: |
1249 | /// |
1250 | /// ``` |
1251 | #[doc = concat!("assert_eq!(0x1" , stringify!($SelfT), ".checked_shl(4), Some(0x10));" )] |
1252 | #[doc = concat!("assert_eq!(0x10" , stringify!($SelfT), ".checked_shl(129), None);" )] |
1253 | /// ``` |
1254 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
1255 | #[rustc_const_stable(feature = "const_checked_int_methods" , since = "1.47.0" )] |
1256 | // We could always go back to wrapping |
1257 | #[rustc_allow_const_fn_unstable(unchecked_shifts)] |
1258 | #[must_use = "this returns the result of the operation, \ |
1259 | without modifying the original" ] |
1260 | #[inline] |
1261 | pub const fn checked_shl(self, rhs: u32) -> Option<Self> { |
1262 | // Not using overflowing_shl as that's a wrapping shift |
1263 | if rhs < Self::BITS { |
1264 | // SAFETY: just checked the RHS is in-range |
1265 | Some(unsafe { self.unchecked_shl(rhs) }) |
1266 | } else { |
1267 | None |
1268 | } |
1269 | } |
1270 | |
1271 | /// Strict shift left. Computes `self << rhs`, panicking if `rhs` is larger |
1272 | /// than or equal to the number of bits in `self`. |
1273 | /// |
1274 | /// # Panics |
1275 | /// |
1276 | /// ## Overflow behavior |
1277 | /// |
1278 | /// This function will always panic on overflow, regardless of whether overflow checks are enabled. |
1279 | /// |
1280 | /// # Examples |
1281 | /// |
1282 | /// Basic usage: |
1283 | /// |
1284 | /// ``` |
1285 | /// #![feature(strict_overflow_ops)] |
1286 | #[doc = concat!("assert_eq!(0x1" , stringify!($SelfT), ".strict_shl(4), 0x10);" )] |
1287 | /// ``` |
1288 | /// |
1289 | /// The following panics because of overflow: |
1290 | /// |
1291 | /// ```should_panic |
1292 | /// #![feature(strict_overflow_ops)] |
1293 | #[doc = concat!("let _ = 0x10" , stringify!($SelfT), ".strict_shl(129);" )] |
1294 | /// ``` |
1295 | #[unstable(feature = "strict_overflow_ops" , issue = "118260" )] |
1296 | #[rustc_const_unstable(feature = "const_strict_overflow_ops" , issue = "118260" )] |
1297 | #[must_use = "this returns the result of the operation, \ |
1298 | without modifying the original" ] |
1299 | #[inline] |
1300 | #[track_caller] |
1301 | pub const fn strict_shl(self, rhs: u32) -> Self { |
1302 | let (a, b) = self.overflowing_shl(rhs); |
1303 | if unlikely!(b) { overflow_panic::shl() } else { a } |
1304 | } |
1305 | |
1306 | /// Unchecked shift left. Computes `self << rhs`, assuming that |
1307 | /// `rhs` is less than the number of bits in `self`. |
1308 | /// |
1309 | /// # Safety |
1310 | /// |
1311 | /// This results in undefined behavior if `rhs` is larger than |
1312 | /// or equal to the number of bits in `self`, |
1313 | /// i.e. when [`checked_shl`] would return `None`. |
1314 | /// |
1315 | #[doc = concat!("[`checked_shl`]: " , stringify!($SelfT), "::checked_shl" )] |
1316 | #[unstable( |
1317 | feature = "unchecked_shifts" , |
1318 | reason = "niche optimization path" , |
1319 | issue = "85122" , |
1320 | )] |
1321 | #[must_use = "this returns the result of the operation, \ |
1322 | without modifying the original" ] |
1323 | #[rustc_const_unstable(feature = "unchecked_shifts" , issue = "85122" )] |
1324 | #[inline(always)] |
1325 | #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces |
1326 | pub const unsafe fn unchecked_shl(self, rhs: u32) -> Self { |
1327 | #[cfg(bootstrap)] |
1328 | { |
1329 | // For bootstrapping, just use built-in primitive shift. |
1330 | // panicking is a legal manifestation of UB |
1331 | self << rhs |
1332 | } |
1333 | #[cfg(not(bootstrap))] |
1334 | { |
1335 | // SAFETY: the caller must uphold the safety contract for |
1336 | // `unchecked_shl`. |
1337 | unsafe { intrinsics::unchecked_shl(self, rhs) } |
1338 | } |
1339 | } |
1340 | |
1341 | /// Checked shift right. Computes `self >> rhs`, returning `None` |
1342 | /// if `rhs` is larger than or equal to the number of bits in `self`. |
1343 | /// |
1344 | /// # Examples |
1345 | /// |
1346 | /// Basic usage: |
1347 | /// |
1348 | /// ``` |
1349 | #[doc = concat!("assert_eq!(0x10" , stringify!($SelfT), ".checked_shr(4), Some(0x1));" )] |
1350 | #[doc = concat!("assert_eq!(0x10" , stringify!($SelfT), ".checked_shr(129), None);" )] |
1351 | /// ``` |
1352 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
1353 | #[rustc_const_stable(feature = "const_checked_int_methods" , since = "1.47.0" )] |
1354 | // We could always go back to wrapping |
1355 | #[rustc_allow_const_fn_unstable(unchecked_shifts)] |
1356 | #[must_use = "this returns the result of the operation, \ |
1357 | without modifying the original" ] |
1358 | #[inline] |
1359 | pub const fn checked_shr(self, rhs: u32) -> Option<Self> { |
1360 | // Not using overflowing_shr as that's a wrapping shift |
1361 | if rhs < Self::BITS { |
1362 | // SAFETY: just checked the RHS is in-range |
1363 | Some(unsafe { self.unchecked_shr(rhs) }) |
1364 | } else { |
1365 | None |
1366 | } |
1367 | } |
1368 | |
1369 | /// Strict shift right. Computes `self >> rhs`, panicking `rhs` is |
1370 | /// larger than or equal to the number of bits in `self`. |
1371 | /// |
1372 | /// # Panics |
1373 | /// |
1374 | /// ## Overflow behavior |
1375 | /// |
1376 | /// This function will always panic on overflow, regardless of whether overflow checks are enabled. |
1377 | /// |
1378 | /// # Examples |
1379 | /// |
1380 | /// Basic usage: |
1381 | /// |
1382 | /// ``` |
1383 | /// #![feature(strict_overflow_ops)] |
1384 | #[doc = concat!("assert_eq!(0x10" , stringify!($SelfT), ".strict_shr(4), 0x1);" )] |
1385 | /// ``` |
1386 | /// |
1387 | /// The following panics because of overflow: |
1388 | /// |
1389 | /// ```should_panic |
1390 | /// #![feature(strict_overflow_ops)] |
1391 | #[doc = concat!("let _ = 0x10" , stringify!($SelfT), ".strict_shr(129);" )] |
1392 | /// ``` |
1393 | #[unstable(feature = "strict_overflow_ops" , issue = "118260" )] |
1394 | #[rustc_const_unstable(feature = "const_strict_overflow_ops" , issue = "118260" )] |
1395 | #[must_use = "this returns the result of the operation, \ |
1396 | without modifying the original" ] |
1397 | #[inline] |
1398 | #[track_caller] |
1399 | pub const fn strict_shr(self, rhs: u32) -> Self { |
1400 | let (a, b) = self.overflowing_shr(rhs); |
1401 | if unlikely!(b) { overflow_panic::shr() } else { a } |
1402 | } |
1403 | |
1404 | /// Unchecked shift right. Computes `self >> rhs`, assuming that |
1405 | /// `rhs` is less than the number of bits in `self`. |
1406 | /// |
1407 | /// # Safety |
1408 | /// |
1409 | /// This results in undefined behavior if `rhs` is larger than |
1410 | /// or equal to the number of bits in `self`, |
1411 | /// i.e. when [`checked_shr`] would return `None`. |
1412 | /// |
1413 | #[doc = concat!("[`checked_shr`]: " , stringify!($SelfT), "::checked_shr" )] |
1414 | #[unstable( |
1415 | feature = "unchecked_shifts" , |
1416 | reason = "niche optimization path" , |
1417 | issue = "85122" , |
1418 | )] |
1419 | #[must_use = "this returns the result of the operation, \ |
1420 | without modifying the original" ] |
1421 | #[rustc_const_unstable(feature = "unchecked_shifts" , issue = "85122" )] |
1422 | #[inline(always)] |
1423 | #[cfg_attr(miri, track_caller)] // even without panics, this helps for Miri backtraces |
1424 | pub const unsafe fn unchecked_shr(self, rhs: u32) -> Self { |
1425 | #[cfg(bootstrap)] |
1426 | { |
1427 | // For bootstrapping, just use built-in primitive shift. |
1428 | // panicking is a legal manifestation of UB |
1429 | self >> rhs |
1430 | } |
1431 | #[cfg(not(bootstrap))] |
1432 | { |
1433 | // SAFETY: the caller must uphold the safety contract for |
1434 | // `unchecked_shr`. |
1435 | unsafe { intrinsics::unchecked_shr(self, rhs) } |
1436 | } |
1437 | } |
1438 | |
1439 | /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if |
1440 | /// overflow occurred. |
1441 | /// |
1442 | /// # Examples |
1443 | /// |
1444 | /// Basic usage: |
1445 | /// |
1446 | /// ``` |
1447 | #[doc = concat!("assert_eq!(2" , stringify!($SelfT), ".checked_pow(5), Some(32));" )] |
1448 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MAX.checked_pow(2), None);" )] |
1449 | /// ``` |
1450 | #[stable(feature = "no_panic_pow" , since = "1.34.0" )] |
1451 | #[rustc_const_stable(feature = "const_int_pow" , since = "1.50.0" )] |
1452 | #[must_use = "this returns the result of the operation, \ |
1453 | without modifying the original" ] |
1454 | #[inline] |
1455 | pub const fn checked_pow(self, mut exp: u32) -> Option<Self> { |
1456 | if exp == 0 { |
1457 | return Some(1); |
1458 | } |
1459 | let mut base = self; |
1460 | let mut acc: Self = 1; |
1461 | |
1462 | while exp > 1 { |
1463 | if (exp & 1) == 1 { |
1464 | acc = try_opt!(acc.checked_mul(base)); |
1465 | } |
1466 | exp /= 2; |
1467 | base = try_opt!(base.checked_mul(base)); |
1468 | } |
1469 | |
1470 | // since exp!=0, finally the exp must be 1. |
1471 | // Deal with the final bit of the exponent separately, since |
1472 | // squaring the base afterwards is not necessary and may cause a |
1473 | // needless overflow. |
1474 | |
1475 | acc.checked_mul(base) |
1476 | } |
1477 | |
1478 | /// Strict exponentiation. Computes `self.pow(exp)`, panicking if |
1479 | /// overflow occurred. |
1480 | /// |
1481 | /// # Panics |
1482 | /// |
1483 | /// ## Overflow behavior |
1484 | /// |
1485 | /// This function will always panic on overflow, regardless of whether overflow checks are enabled. |
1486 | /// |
1487 | /// # Examples |
1488 | /// |
1489 | /// Basic usage: |
1490 | /// |
1491 | /// ``` |
1492 | /// #![feature(strict_overflow_ops)] |
1493 | #[doc = concat!("assert_eq!(2" , stringify!($SelfT), ".strict_pow(5), 32);" )] |
1494 | /// ``` |
1495 | /// |
1496 | /// The following panics because of overflow: |
1497 | /// |
1498 | /// ```should_panic |
1499 | /// #![feature(strict_overflow_ops)] |
1500 | #[doc = concat!("let _ = " , stringify!($SelfT), "::MAX.strict_pow(2);" )] |
1501 | /// ``` |
1502 | #[unstable(feature = "strict_overflow_ops" , issue = "118260" )] |
1503 | #[rustc_const_unstable(feature = "const_strict_overflow_ops" , issue = "118260" )] |
1504 | #[must_use = "this returns the result of the operation, \ |
1505 | without modifying the original" ] |
1506 | #[inline] |
1507 | #[track_caller] |
1508 | pub const fn strict_pow(self, mut exp: u32) -> Self { |
1509 | if exp == 0 { |
1510 | return 1; |
1511 | } |
1512 | let mut base = self; |
1513 | let mut acc: Self = 1; |
1514 | |
1515 | while exp > 1 { |
1516 | if (exp & 1) == 1 { |
1517 | acc = acc.strict_mul(base); |
1518 | } |
1519 | exp /= 2; |
1520 | base = base.strict_mul(base); |
1521 | } |
1522 | // since exp!=0, finally the exp must be 1. |
1523 | // Deal with the final bit of the exponent separately, since |
1524 | // squaring the base afterwards is not necessary and may cause a |
1525 | // needless overflow. |
1526 | acc.strict_mul(base) |
1527 | } |
1528 | |
1529 | /// Saturating integer addition. Computes `self + rhs`, saturating at |
1530 | /// the numeric bounds instead of overflowing. |
1531 | /// |
1532 | /// # Examples |
1533 | /// |
1534 | /// Basic usage: |
1535 | /// |
1536 | /// ``` |
1537 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".saturating_add(1), 101);" )] |
1538 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MAX.saturating_add(127), " , stringify!($SelfT), "::MAX);" )] |
1539 | /// ``` |
1540 | #[stable(feature = "rust1" , since = "1.0.0" )] |
1541 | #[must_use = "this returns the result of the operation, \ |
1542 | without modifying the original" ] |
1543 | #[rustc_const_stable(feature = "const_saturating_int_methods" , since = "1.47.0" )] |
1544 | #[inline(always)] |
1545 | pub const fn saturating_add(self, rhs: Self) -> Self { |
1546 | intrinsics::saturating_add(self, rhs) |
1547 | } |
1548 | |
1549 | /// Saturating addition with a signed integer. Computes `self + rhs`, |
1550 | /// saturating at the numeric bounds instead of overflowing. |
1551 | /// |
1552 | /// # Examples |
1553 | /// |
1554 | /// Basic usage: |
1555 | /// |
1556 | /// ``` |
1557 | #[doc = concat!("assert_eq!(1" , stringify!($SelfT), ".saturating_add_signed(2), 3);" )] |
1558 | #[doc = concat!("assert_eq!(1" , stringify!($SelfT), ".saturating_add_signed(-2), 0);" )] |
1559 | #[doc = concat!("assert_eq!((" , stringify!($SelfT), "::MAX - 2).saturating_add_signed(4), " , stringify!($SelfT), "::MAX);" )] |
1560 | /// ``` |
1561 | #[stable(feature = "mixed_integer_ops" , since = "1.66.0" )] |
1562 | #[rustc_const_stable(feature = "mixed_integer_ops" , since = "1.66.0" )] |
1563 | #[must_use = "this returns the result of the operation, \ |
1564 | without modifying the original" ] |
1565 | #[inline] |
1566 | pub const fn saturating_add_signed(self, rhs: $SignedT) -> Self { |
1567 | let (res, overflow) = self.overflowing_add(rhs as Self); |
1568 | if overflow == (rhs < 0) { |
1569 | res |
1570 | } else if overflow { |
1571 | Self::MAX |
1572 | } else { |
1573 | 0 |
1574 | } |
1575 | } |
1576 | |
1577 | /// Saturating integer subtraction. Computes `self - rhs`, saturating |
1578 | /// at the numeric bounds instead of overflowing. |
1579 | /// |
1580 | /// # Examples |
1581 | /// |
1582 | /// Basic usage: |
1583 | /// |
1584 | /// ``` |
1585 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".saturating_sub(27), 73);" )] |
1586 | #[doc = concat!("assert_eq!(13" , stringify!($SelfT), ".saturating_sub(127), 0);" )] |
1587 | /// ``` |
1588 | #[stable(feature = "rust1" , since = "1.0.0" )] |
1589 | #[must_use = "this returns the result of the operation, \ |
1590 | without modifying the original" ] |
1591 | #[rustc_const_stable(feature = "const_saturating_int_methods" , since = "1.47.0" )] |
1592 | #[inline(always)] |
1593 | pub const fn saturating_sub(self, rhs: Self) -> Self { |
1594 | intrinsics::saturating_sub(self, rhs) |
1595 | } |
1596 | |
1597 | /// Saturating integer multiplication. Computes `self * rhs`, |
1598 | /// saturating at the numeric bounds instead of overflowing. |
1599 | /// |
1600 | /// # Examples |
1601 | /// |
1602 | /// Basic usage: |
1603 | /// |
1604 | /// ``` |
1605 | #[doc = concat!("assert_eq!(2" , stringify!($SelfT), ".saturating_mul(10), 20);" )] |
1606 | #[doc = concat!("assert_eq!((" , stringify!($SelfT), "::MAX).saturating_mul(10), " , stringify!($SelfT),"::MAX);" )] |
1607 | /// ``` |
1608 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
1609 | #[rustc_const_stable(feature = "const_saturating_int_methods" , since = "1.47.0" )] |
1610 | #[must_use = "this returns the result of the operation, \ |
1611 | without modifying the original" ] |
1612 | #[inline] |
1613 | pub const fn saturating_mul(self, rhs: Self) -> Self { |
1614 | match self.checked_mul(rhs) { |
1615 | Some(x) => x, |
1616 | None => Self::MAX, |
1617 | } |
1618 | } |
1619 | |
1620 | /// Saturating integer division. Computes `self / rhs`, saturating at the |
1621 | /// numeric bounds instead of overflowing. |
1622 | /// |
1623 | /// # Panics |
1624 | /// |
1625 | /// This function will panic if `rhs` is 0. |
1626 | /// |
1627 | /// # Examples |
1628 | /// |
1629 | /// Basic usage: |
1630 | /// |
1631 | /// ``` |
1632 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".saturating_div(2), 2);" )] |
1633 | /// |
1634 | /// ``` |
1635 | #[stable(feature = "saturating_div" , since = "1.58.0" )] |
1636 | #[rustc_const_stable(feature = "saturating_div" , since = "1.58.0" )] |
1637 | #[must_use = "this returns the result of the operation, \ |
1638 | without modifying the original" ] |
1639 | #[inline] |
1640 | #[track_caller] |
1641 | pub const fn saturating_div(self, rhs: Self) -> Self { |
1642 | // on unsigned types, there is no overflow in integer division |
1643 | self.wrapping_div(rhs) |
1644 | } |
1645 | |
1646 | /// Saturating integer exponentiation. Computes `self.pow(exp)`, |
1647 | /// saturating at the numeric bounds instead of overflowing. |
1648 | /// |
1649 | /// # Examples |
1650 | /// |
1651 | /// Basic usage: |
1652 | /// |
1653 | /// ``` |
1654 | #[doc = concat!("assert_eq!(4" , stringify!($SelfT), ".saturating_pow(3), 64);" )] |
1655 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MAX.saturating_pow(2), " , stringify!($SelfT), "::MAX);" )] |
1656 | /// ``` |
1657 | #[stable(feature = "no_panic_pow" , since = "1.34.0" )] |
1658 | #[rustc_const_stable(feature = "const_int_pow" , since = "1.50.0" )] |
1659 | #[must_use = "this returns the result of the operation, \ |
1660 | without modifying the original" ] |
1661 | #[inline] |
1662 | pub const fn saturating_pow(self, exp: u32) -> Self { |
1663 | match self.checked_pow(exp) { |
1664 | Some(x) => x, |
1665 | None => Self::MAX, |
1666 | } |
1667 | } |
1668 | |
1669 | /// Wrapping (modular) addition. Computes `self + rhs`, |
1670 | /// wrapping around at the boundary of the type. |
1671 | /// |
1672 | /// # Examples |
1673 | /// |
1674 | /// Basic usage: |
1675 | /// |
1676 | /// ``` |
1677 | #[doc = concat!("assert_eq!(200" , stringify!($SelfT), ".wrapping_add(55), 255);" )] |
1678 | #[doc = concat!("assert_eq!(200" , stringify!($SelfT), ".wrapping_add(" , stringify!($SelfT), "::MAX), 199);" )] |
1679 | /// ``` |
1680 | #[stable(feature = "rust1" , since = "1.0.0" )] |
1681 | #[rustc_const_stable(feature = "const_wrapping_math" , since = "1.32.0" )] |
1682 | #[must_use = "this returns the result of the operation, \ |
1683 | without modifying the original" ] |
1684 | #[inline(always)] |
1685 | pub const fn wrapping_add(self, rhs: Self) -> Self { |
1686 | intrinsics::wrapping_add(self, rhs) |
1687 | } |
1688 | |
1689 | /// Wrapping (modular) addition with a signed integer. Computes |
1690 | /// `self + rhs`, wrapping around at the boundary of the type. |
1691 | /// |
1692 | /// # Examples |
1693 | /// |
1694 | /// Basic usage: |
1695 | /// |
1696 | /// ``` |
1697 | #[doc = concat!("assert_eq!(1" , stringify!($SelfT), ".wrapping_add_signed(2), 3);" )] |
1698 | #[doc = concat!("assert_eq!(1" , stringify!($SelfT), ".wrapping_add_signed(-2), " , stringify!($SelfT), "::MAX);" )] |
1699 | #[doc = concat!("assert_eq!((" , stringify!($SelfT), "::MAX - 2).wrapping_add_signed(4), 1);" )] |
1700 | /// ``` |
1701 | #[stable(feature = "mixed_integer_ops" , since = "1.66.0" )] |
1702 | #[rustc_const_stable(feature = "mixed_integer_ops" , since = "1.66.0" )] |
1703 | #[must_use = "this returns the result of the operation, \ |
1704 | without modifying the original" ] |
1705 | #[inline] |
1706 | pub const fn wrapping_add_signed(self, rhs: $SignedT) -> Self { |
1707 | self.wrapping_add(rhs as Self) |
1708 | } |
1709 | |
1710 | /// Wrapping (modular) subtraction. Computes `self - rhs`, |
1711 | /// wrapping around at the boundary of the type. |
1712 | /// |
1713 | /// # Examples |
1714 | /// |
1715 | /// Basic usage: |
1716 | /// |
1717 | /// ``` |
1718 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".wrapping_sub(100), 0);" )] |
1719 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".wrapping_sub(" , stringify!($SelfT), "::MAX), 101);" )] |
1720 | /// ``` |
1721 | #[stable(feature = "rust1" , since = "1.0.0" )] |
1722 | #[rustc_const_stable(feature = "const_wrapping_math" , since = "1.32.0" )] |
1723 | #[must_use = "this returns the result of the operation, \ |
1724 | without modifying the original" ] |
1725 | #[inline(always)] |
1726 | pub const fn wrapping_sub(self, rhs: Self) -> Self { |
1727 | intrinsics::wrapping_sub(self, rhs) |
1728 | } |
1729 | |
1730 | /// Wrapping (modular) multiplication. Computes `self * |
1731 | /// rhs`, wrapping around at the boundary of the type. |
1732 | /// |
1733 | /// # Examples |
1734 | /// |
1735 | /// Basic usage: |
1736 | /// |
1737 | /// Please note that this example is shared between integer types. |
1738 | /// Which explains why `u8` is used here. |
1739 | /// |
1740 | /// ``` |
1741 | /// assert_eq!(10u8.wrapping_mul(12), 120); |
1742 | /// assert_eq!(25u8.wrapping_mul(12), 44); |
1743 | /// ``` |
1744 | #[stable(feature = "rust1" , since = "1.0.0" )] |
1745 | #[rustc_const_stable(feature = "const_wrapping_math" , since = "1.32.0" )] |
1746 | #[must_use = "this returns the result of the operation, \ |
1747 | without modifying the original" ] |
1748 | #[inline(always)] |
1749 | pub const fn wrapping_mul(self, rhs: Self) -> Self { |
1750 | intrinsics::wrapping_mul(self, rhs) |
1751 | } |
1752 | |
1753 | /// Wrapping (modular) division. Computes `self / rhs`. |
1754 | /// Wrapped division on unsigned types is just normal division. |
1755 | /// There's no way wrapping could ever happen. |
1756 | /// This function exists, so that all operations |
1757 | /// are accounted for in the wrapping operations. |
1758 | /// |
1759 | /// # Panics |
1760 | /// |
1761 | /// This function will panic if `rhs` is 0. |
1762 | /// |
1763 | /// # Examples |
1764 | /// |
1765 | /// Basic usage: |
1766 | /// |
1767 | /// ``` |
1768 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".wrapping_div(10), 10);" )] |
1769 | /// ``` |
1770 | #[stable(feature = "num_wrapping" , since = "1.2.0" )] |
1771 | #[rustc_const_stable(feature = "const_wrapping_int_methods" , since = "1.52.0" )] |
1772 | #[must_use = "this returns the result of the operation, \ |
1773 | without modifying the original" ] |
1774 | #[inline(always)] |
1775 | #[track_caller] |
1776 | pub const fn wrapping_div(self, rhs: Self) -> Self { |
1777 | self / rhs |
1778 | } |
1779 | |
1780 | /// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`. |
1781 | /// Wrapped division on unsigned types is just normal division. |
1782 | /// There's no way wrapping could ever happen. |
1783 | /// This function exists, so that all operations |
1784 | /// are accounted for in the wrapping operations. |
1785 | /// Since, for the positive integers, all common |
1786 | /// definitions of division are equal, this |
1787 | /// is exactly equal to `self.wrapping_div(rhs)`. |
1788 | /// |
1789 | /// # Panics |
1790 | /// |
1791 | /// This function will panic if `rhs` is 0. |
1792 | /// |
1793 | /// # Examples |
1794 | /// |
1795 | /// Basic usage: |
1796 | /// |
1797 | /// ``` |
1798 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".wrapping_div_euclid(10), 10);" )] |
1799 | /// ``` |
1800 | #[stable(feature = "euclidean_division" , since = "1.38.0" )] |
1801 | #[rustc_const_stable(feature = "const_euclidean_int_methods" , since = "1.52.0" )] |
1802 | #[must_use = "this returns the result of the operation, \ |
1803 | without modifying the original" ] |
1804 | #[inline(always)] |
1805 | #[track_caller] |
1806 | pub const fn wrapping_div_euclid(self, rhs: Self) -> Self { |
1807 | self / rhs |
1808 | } |
1809 | |
1810 | /// Wrapping (modular) remainder. Computes `self % rhs`. |
1811 | /// Wrapped remainder calculation on unsigned types is |
1812 | /// just the regular remainder calculation. |
1813 | /// There's no way wrapping could ever happen. |
1814 | /// This function exists, so that all operations |
1815 | /// are accounted for in the wrapping operations. |
1816 | /// |
1817 | /// # Panics |
1818 | /// |
1819 | /// This function will panic if `rhs` is 0. |
1820 | /// |
1821 | /// # Examples |
1822 | /// |
1823 | /// Basic usage: |
1824 | /// |
1825 | /// ``` |
1826 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".wrapping_rem(10), 0);" )] |
1827 | /// ``` |
1828 | #[stable(feature = "num_wrapping" , since = "1.2.0" )] |
1829 | #[rustc_const_stable(feature = "const_wrapping_int_methods" , since = "1.52.0" )] |
1830 | #[must_use = "this returns the result of the operation, \ |
1831 | without modifying the original" ] |
1832 | #[inline(always)] |
1833 | #[track_caller] |
1834 | pub const fn wrapping_rem(self, rhs: Self) -> Self { |
1835 | self % rhs |
1836 | } |
1837 | |
1838 | /// Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`. |
1839 | /// Wrapped modulo calculation on unsigned types is |
1840 | /// just the regular remainder calculation. |
1841 | /// There's no way wrapping could ever happen. |
1842 | /// This function exists, so that all operations |
1843 | /// are accounted for in the wrapping operations. |
1844 | /// Since, for the positive integers, all common |
1845 | /// definitions of division are equal, this |
1846 | /// is exactly equal to `self.wrapping_rem(rhs)`. |
1847 | /// |
1848 | /// # Panics |
1849 | /// |
1850 | /// This function will panic if `rhs` is 0. |
1851 | /// |
1852 | /// # Examples |
1853 | /// |
1854 | /// Basic usage: |
1855 | /// |
1856 | /// ``` |
1857 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".wrapping_rem_euclid(10), 0);" )] |
1858 | /// ``` |
1859 | #[stable(feature = "euclidean_division" , since = "1.38.0" )] |
1860 | #[rustc_const_stable(feature = "const_euclidean_int_methods" , since = "1.52.0" )] |
1861 | #[must_use = "this returns the result of the operation, \ |
1862 | without modifying the original" ] |
1863 | #[inline(always)] |
1864 | #[track_caller] |
1865 | pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self { |
1866 | self % rhs |
1867 | } |
1868 | |
1869 | /// Wrapping (modular) negation. Computes `-self`, |
1870 | /// wrapping around at the boundary of the type. |
1871 | /// |
1872 | /// Since unsigned types do not have negative equivalents |
1873 | /// all applications of this function will wrap (except for `-0`). |
1874 | /// For values smaller than the corresponding signed type's maximum |
1875 | /// the result is the same as casting the corresponding signed value. |
1876 | /// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where |
1877 | /// `MAX` is the corresponding signed type's maximum. |
1878 | /// |
1879 | /// # Examples |
1880 | /// |
1881 | /// Basic usage: |
1882 | /// |
1883 | /// ``` |
1884 | #[doc = concat!("assert_eq!(0_" , stringify!($SelfT), ".wrapping_neg(), 0);" )] |
1885 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MAX.wrapping_neg(), 1);" )] |
1886 | #[doc = concat!("assert_eq!(13_" , stringify!($SelfT), ".wrapping_neg(), (!13) + 1);" )] |
1887 | #[doc = concat!("assert_eq!(42_" , stringify!($SelfT), ".wrapping_neg(), !(42 - 1));" )] |
1888 | /// ``` |
1889 | #[stable(feature = "num_wrapping" , since = "1.2.0" )] |
1890 | #[rustc_const_stable(feature = "const_wrapping_math" , since = "1.32.0" )] |
1891 | #[must_use = "this returns the result of the operation, \ |
1892 | without modifying the original" ] |
1893 | #[inline(always)] |
1894 | pub const fn wrapping_neg(self) -> Self { |
1895 | (0 as $SelfT).wrapping_sub(self) |
1896 | } |
1897 | |
1898 | /// Panic-free bitwise shift-left; yields `self << mask(rhs)`, |
1899 | /// where `mask` removes any high-order bits of `rhs` that |
1900 | /// would cause the shift to exceed the bitwidth of the type. |
1901 | /// |
1902 | /// Note that this is *not* the same as a rotate-left; the |
1903 | /// RHS of a wrapping shift-left is restricted to the range |
1904 | /// of the type, rather than the bits shifted out of the LHS |
1905 | /// being returned to the other end. The primitive integer |
1906 | /// types all implement a [`rotate_left`](Self::rotate_left) function, |
1907 | /// which may be what you want instead. |
1908 | /// |
1909 | /// # Examples |
1910 | /// |
1911 | /// Basic usage: |
1912 | /// |
1913 | /// ``` |
1914 | #[doc = concat!("assert_eq!(1" , stringify!($SelfT), ".wrapping_shl(7), 128);" )] |
1915 | #[doc = concat!("assert_eq!(1" , stringify!($SelfT), ".wrapping_shl(128), 1);" )] |
1916 | /// ``` |
1917 | #[stable(feature = "num_wrapping" , since = "1.2.0" )] |
1918 | #[rustc_const_stable(feature = "const_wrapping_math" , since = "1.32.0" )] |
1919 | #[must_use = "this returns the result of the operation, \ |
1920 | without modifying the original" ] |
1921 | #[inline(always)] |
1922 | #[rustc_allow_const_fn_unstable(unchecked_shifts)] |
1923 | pub const fn wrapping_shl(self, rhs: u32) -> Self { |
1924 | // SAFETY: the masking by the bitsize of the type ensures that we do not shift |
1925 | // out of bounds |
1926 | unsafe { |
1927 | self.unchecked_shl(rhs & (Self::BITS - 1)) |
1928 | } |
1929 | } |
1930 | |
1931 | /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, |
1932 | /// where `mask` removes any high-order bits of `rhs` that |
1933 | /// would cause the shift to exceed the bitwidth of the type. |
1934 | /// |
1935 | /// Note that this is *not* the same as a rotate-right; the |
1936 | /// RHS of a wrapping shift-right is restricted to the range |
1937 | /// of the type, rather than the bits shifted out of the LHS |
1938 | /// being returned to the other end. The primitive integer |
1939 | /// types all implement a [`rotate_right`](Self::rotate_right) function, |
1940 | /// which may be what you want instead. |
1941 | /// |
1942 | /// # Examples |
1943 | /// |
1944 | /// Basic usage: |
1945 | /// |
1946 | /// ``` |
1947 | #[doc = concat!("assert_eq!(128" , stringify!($SelfT), ".wrapping_shr(7), 1);" )] |
1948 | #[doc = concat!("assert_eq!(128" , stringify!($SelfT), ".wrapping_shr(128), 128);" )] |
1949 | /// ``` |
1950 | #[stable(feature = "num_wrapping" , since = "1.2.0" )] |
1951 | #[rustc_const_stable(feature = "const_wrapping_math" , since = "1.32.0" )] |
1952 | #[must_use = "this returns the result of the operation, \ |
1953 | without modifying the original" ] |
1954 | #[inline(always)] |
1955 | #[rustc_allow_const_fn_unstable(unchecked_shifts)] |
1956 | pub const fn wrapping_shr(self, rhs: u32) -> Self { |
1957 | // SAFETY: the masking by the bitsize of the type ensures that we do not shift |
1958 | // out of bounds |
1959 | unsafe { |
1960 | self.unchecked_shr(rhs & (Self::BITS - 1)) |
1961 | } |
1962 | } |
1963 | |
1964 | /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`, |
1965 | /// wrapping around at the boundary of the type. |
1966 | /// |
1967 | /// # Examples |
1968 | /// |
1969 | /// Basic usage: |
1970 | /// |
1971 | /// ``` |
1972 | #[doc = concat!("assert_eq!(3" , stringify!($SelfT), ".wrapping_pow(5), 243);" )] |
1973 | /// assert_eq!(3u8.wrapping_pow(6), 217); |
1974 | /// ``` |
1975 | #[stable(feature = "no_panic_pow" , since = "1.34.0" )] |
1976 | #[rustc_const_stable(feature = "const_int_pow" , since = "1.50.0" )] |
1977 | #[must_use = "this returns the result of the operation, \ |
1978 | without modifying the original" ] |
1979 | #[inline] |
1980 | pub const fn wrapping_pow(self, mut exp: u32) -> Self { |
1981 | if exp == 0 { |
1982 | return 1; |
1983 | } |
1984 | let mut base = self; |
1985 | let mut acc: Self = 1; |
1986 | |
1987 | while exp > 1 { |
1988 | if (exp & 1) == 1 { |
1989 | acc = acc.wrapping_mul(base); |
1990 | } |
1991 | exp /= 2; |
1992 | base = base.wrapping_mul(base); |
1993 | } |
1994 | |
1995 | // since exp!=0, finally the exp must be 1. |
1996 | // Deal with the final bit of the exponent separately, since |
1997 | // squaring the base afterwards is not necessary and may cause a |
1998 | // needless overflow. |
1999 | acc.wrapping_mul(base) |
2000 | } |
2001 | |
2002 | /// Calculates `self` + `rhs` |
2003 | /// |
2004 | /// Returns a tuple of the addition along with a boolean indicating |
2005 | /// whether an arithmetic overflow would occur. If an overflow would |
2006 | /// have occurred then the wrapped value is returned. |
2007 | /// |
2008 | /// # Examples |
2009 | /// |
2010 | /// Basic usage |
2011 | /// |
2012 | /// ``` |
2013 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".overflowing_add(2), (7, false));" )] |
2014 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MAX.overflowing_add(1), (0, true));" )] |
2015 | /// ``` |
2016 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
2017 | #[rustc_const_stable(feature = "const_wrapping_math" , since = "1.32.0" )] |
2018 | #[must_use = "this returns the result of the operation, \ |
2019 | without modifying the original" ] |
2020 | #[inline(always)] |
2021 | pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) { |
2022 | let (a, b) = intrinsics::add_with_overflow(self as $ActualT, rhs as $ActualT); |
2023 | (a as Self, b) |
2024 | } |
2025 | |
2026 | /// Calculates `self` + `rhs` + `carry` and returns a tuple containing |
2027 | /// the sum and the output carry. |
2028 | /// |
2029 | /// Performs "ternary addition" of two integer operands and a carry-in |
2030 | /// bit, and returns an output integer and a carry-out bit. This allows |
2031 | /// chaining together multiple additions to create a wider addition, and |
2032 | /// can be useful for bignum addition. |
2033 | /// |
2034 | #[doc = concat!("This can be thought of as a " , stringify!($BITS), "-bit \"full adder \", in the electronics sense." )] |
2035 | /// |
2036 | /// If the input carry is false, this method is equivalent to |
2037 | /// [`overflowing_add`](Self::overflowing_add), and the output carry is |
2038 | /// equal to the overflow flag. Note that although carry and overflow |
2039 | /// flags are similar for unsigned integers, they are different for |
2040 | /// signed integers. |
2041 | /// |
2042 | /// # Examples |
2043 | /// |
2044 | /// ``` |
2045 | /// #![feature(bigint_helper_methods)] |
2046 | /// |
2047 | #[doc = concat!("// 3 MAX (a = 3 × 2^" , stringify!($BITS), " + 2^" , stringify!($BITS), " - 1)" )] |
2048 | #[doc = concat!("// + 5 7 (b = 5 × 2^" , stringify!($BITS), " + 7)" )] |
2049 | /// // --------- |
2050 | #[doc = concat!("// 9 6 (sum = 9 × 2^" , stringify!($BITS), " + 6)" )] |
2051 | /// |
2052 | #[doc = concat!("let (a1, a0): (" , stringify!($SelfT), ", " , stringify!($SelfT), ") = (3, " , stringify!($SelfT), "::MAX);" )] |
2053 | #[doc = concat!("let (b1, b0): (" , stringify!($SelfT), ", " , stringify!($SelfT), ") = (5, 7);" )] |
2054 | /// let carry0 = false; |
2055 | /// |
2056 | /// let (sum0, carry1) = a0.carrying_add(b0, carry0); |
2057 | /// assert_eq!(carry1, true); |
2058 | /// let (sum1, carry2) = a1.carrying_add(b1, carry1); |
2059 | /// assert_eq!(carry2, false); |
2060 | /// |
2061 | /// assert_eq!((sum1, sum0), (9, 6)); |
2062 | /// ``` |
2063 | #[unstable(feature = "bigint_helper_methods" , issue = "85532" )] |
2064 | #[rustc_const_unstable(feature = "const_bigint_helper_methods" , issue = "85532" )] |
2065 | #[must_use = "this returns the result of the operation, \ |
2066 | without modifying the original" ] |
2067 | #[inline] |
2068 | pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) { |
2069 | // note: longer-term this should be done via an intrinsic, but this has been shown |
2070 | // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic |
2071 | let (a, b) = self.overflowing_add(rhs); |
2072 | let (c, d) = a.overflowing_add(carry as $SelfT); |
2073 | (c, b || d) |
2074 | } |
2075 | |
2076 | /// Calculates `self` + `rhs` with a signed `rhs` |
2077 | /// |
2078 | /// Returns a tuple of the addition along with a boolean indicating |
2079 | /// whether an arithmetic overflow would occur. If an overflow would |
2080 | /// have occurred then the wrapped value is returned. |
2081 | /// |
2082 | /// # Examples |
2083 | /// |
2084 | /// Basic usage: |
2085 | /// |
2086 | /// ``` |
2087 | #[doc = concat!("assert_eq!(1" , stringify!($SelfT), ".overflowing_add_signed(2), (3, false));" )] |
2088 | #[doc = concat!("assert_eq!(1" , stringify!($SelfT), ".overflowing_add_signed(-2), (" , stringify!($SelfT), "::MAX, true));" )] |
2089 | #[doc = concat!("assert_eq!((" , stringify!($SelfT), "::MAX - 2).overflowing_add_signed(4), (1, true));" )] |
2090 | /// ``` |
2091 | #[stable(feature = "mixed_integer_ops" , since = "1.66.0" )] |
2092 | #[rustc_const_stable(feature = "mixed_integer_ops" , since = "1.66.0" )] |
2093 | #[must_use = "this returns the result of the operation, \ |
2094 | without modifying the original" ] |
2095 | #[inline] |
2096 | pub const fn overflowing_add_signed(self, rhs: $SignedT) -> (Self, bool) { |
2097 | let (res, overflowed) = self.overflowing_add(rhs as Self); |
2098 | (res, overflowed ^ (rhs < 0)) |
2099 | } |
2100 | |
2101 | /// Calculates `self` - `rhs` |
2102 | /// |
2103 | /// Returns a tuple of the subtraction along with a boolean indicating |
2104 | /// whether an arithmetic overflow would occur. If an overflow would |
2105 | /// have occurred then the wrapped value is returned. |
2106 | /// |
2107 | /// # Examples |
2108 | /// |
2109 | /// Basic usage |
2110 | /// |
2111 | /// ``` |
2112 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".overflowing_sub(2), (3, false));" )] |
2113 | #[doc = concat!("assert_eq!(0" , stringify!($SelfT), ".overflowing_sub(1), (" , stringify!($SelfT), "::MAX, true));" )] |
2114 | /// ``` |
2115 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
2116 | #[rustc_const_stable(feature = "const_wrapping_math" , since = "1.32.0" )] |
2117 | #[must_use = "this returns the result of the operation, \ |
2118 | without modifying the original" ] |
2119 | #[inline(always)] |
2120 | pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) { |
2121 | let (a, b) = intrinsics::sub_with_overflow(self as $ActualT, rhs as $ActualT); |
2122 | (a as Self, b) |
2123 | } |
2124 | |
2125 | /// Calculates `self` − `rhs` − `borrow` and returns a tuple |
2126 | /// containing the difference and the output borrow. |
2127 | /// |
2128 | /// Performs "ternary subtraction" by subtracting both an integer |
2129 | /// operand and a borrow-in bit from `self`, and returns an output |
2130 | /// integer and a borrow-out bit. This allows chaining together multiple |
2131 | /// subtractions to create a wider subtraction, and can be useful for |
2132 | /// bignum subtraction. |
2133 | /// |
2134 | /// # Examples |
2135 | /// |
2136 | /// ``` |
2137 | /// #![feature(bigint_helper_methods)] |
2138 | /// |
2139 | #[doc = concat!("// 9 6 (a = 9 × 2^" , stringify!($BITS), " + 6)" )] |
2140 | #[doc = concat!("// - 5 7 (b = 5 × 2^" , stringify!($BITS), " + 7)" )] |
2141 | /// // --------- |
2142 | #[doc = concat!("// 3 MAX (diff = 3 × 2^" , stringify!($BITS), " + 2^" , stringify!($BITS), " - 1)" )] |
2143 | /// |
2144 | #[doc = concat!("let (a1, a0): (" , stringify!($SelfT), ", " , stringify!($SelfT), ") = (9, 6);" )] |
2145 | #[doc = concat!("let (b1, b0): (" , stringify!($SelfT), ", " , stringify!($SelfT), ") = (5, 7);" )] |
2146 | /// let borrow0 = false; |
2147 | /// |
2148 | /// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0); |
2149 | /// assert_eq!(borrow1, true); |
2150 | /// let (diff1, borrow2) = a1.borrowing_sub(b1, borrow1); |
2151 | /// assert_eq!(borrow2, false); |
2152 | /// |
2153 | #[doc = concat!("assert_eq!((diff1, diff0), (3, " , stringify!($SelfT), "::MAX));" )] |
2154 | /// ``` |
2155 | #[unstable(feature = "bigint_helper_methods" , issue = "85532" )] |
2156 | #[rustc_const_unstable(feature = "const_bigint_helper_methods" , issue = "85532" )] |
2157 | #[must_use = "this returns the result of the operation, \ |
2158 | without modifying the original" ] |
2159 | #[inline] |
2160 | pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) { |
2161 | // note: longer-term this should be done via an intrinsic, but this has been shown |
2162 | // to generate optimal code for now, and LLVM doesn't have an equivalent intrinsic |
2163 | let (a, b) = self.overflowing_sub(rhs); |
2164 | let (c, d) = a.overflowing_sub(borrow as $SelfT); |
2165 | (c, b || d) |
2166 | } |
2167 | |
2168 | /// Computes the absolute difference between `self` and `other`. |
2169 | /// |
2170 | /// # Examples |
2171 | /// |
2172 | /// Basic usage: |
2173 | /// |
2174 | /// ``` |
2175 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".abs_diff(80), 20" , stringify!($SelfT), ");" )] |
2176 | #[doc = concat!("assert_eq!(100" , stringify!($SelfT), ".abs_diff(110), 10" , stringify!($SelfT), ");" )] |
2177 | /// ``` |
2178 | #[stable(feature = "int_abs_diff" , since = "1.60.0" )] |
2179 | #[rustc_const_stable(feature = "int_abs_diff" , since = "1.60.0" )] |
2180 | #[must_use = "this returns the result of the operation, \ |
2181 | without modifying the original" ] |
2182 | #[inline] |
2183 | pub const fn abs_diff(self, other: Self) -> Self { |
2184 | if mem::size_of::<Self>() == 1 { |
2185 | // Trick LLVM into generating the psadbw instruction when SSE2 |
2186 | // is available and this function is autovectorized for u8's. |
2187 | (self as i32).wrapping_sub(other as i32).abs() as Self |
2188 | } else { |
2189 | if self < other { |
2190 | other - self |
2191 | } else { |
2192 | self - other |
2193 | } |
2194 | } |
2195 | } |
2196 | |
2197 | /// Calculates the multiplication of `self` and `rhs`. |
2198 | /// |
2199 | /// Returns a tuple of the multiplication along with a boolean |
2200 | /// indicating whether an arithmetic overflow would occur. If an |
2201 | /// overflow would have occurred then the wrapped value is returned. |
2202 | /// |
2203 | /// # Examples |
2204 | /// |
2205 | /// Basic usage: |
2206 | /// |
2207 | /// Please note that this example is shared between integer types. |
2208 | /// Which explains why `u32` is used here. |
2209 | /// |
2210 | /// ``` |
2211 | /// assert_eq!(5u32.overflowing_mul(2), (10, false)); |
2212 | /// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true)); |
2213 | /// ``` |
2214 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
2215 | #[rustc_const_stable(feature = "const_wrapping_math" , since = "1.32.0" )] |
2216 | #[must_use = "this returns the result of the operation, \ |
2217 | without modifying the original" ] |
2218 | #[inline(always)] |
2219 | pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) { |
2220 | let (a, b) = intrinsics::mul_with_overflow(self as $ActualT, rhs as $ActualT); |
2221 | (a as Self, b) |
2222 | } |
2223 | |
2224 | /// Calculates the divisor when `self` is divided by `rhs`. |
2225 | /// |
2226 | /// Returns a tuple of the divisor along with a boolean indicating |
2227 | /// whether an arithmetic overflow would occur. Note that for unsigned |
2228 | /// integers overflow never occurs, so the second value is always |
2229 | /// `false`. |
2230 | /// |
2231 | /// # Panics |
2232 | /// |
2233 | /// This function will panic if `rhs` is 0. |
2234 | /// |
2235 | /// # Examples |
2236 | /// |
2237 | /// Basic usage |
2238 | /// |
2239 | /// ``` |
2240 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".overflowing_div(2), (2, false));" )] |
2241 | /// ``` |
2242 | #[inline(always)] |
2243 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
2244 | #[rustc_const_stable(feature = "const_overflowing_int_methods" , since = "1.52.0" )] |
2245 | #[must_use = "this returns the result of the operation, \ |
2246 | without modifying the original" ] |
2247 | #[track_caller] |
2248 | pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) { |
2249 | (self / rhs, false) |
2250 | } |
2251 | |
2252 | /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`. |
2253 | /// |
2254 | /// Returns a tuple of the divisor along with a boolean indicating |
2255 | /// whether an arithmetic overflow would occur. Note that for unsigned |
2256 | /// integers overflow never occurs, so the second value is always |
2257 | /// `false`. |
2258 | /// Since, for the positive integers, all common |
2259 | /// definitions of division are equal, this |
2260 | /// is exactly equal to `self.overflowing_div(rhs)`. |
2261 | /// |
2262 | /// # Panics |
2263 | /// |
2264 | /// This function will panic if `rhs` is 0. |
2265 | /// |
2266 | /// # Examples |
2267 | /// |
2268 | /// Basic usage |
2269 | /// |
2270 | /// ``` |
2271 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".overflowing_div_euclid(2), (2, false));" )] |
2272 | /// ``` |
2273 | #[inline(always)] |
2274 | #[stable(feature = "euclidean_division" , since = "1.38.0" )] |
2275 | #[rustc_const_stable(feature = "const_euclidean_int_methods" , since = "1.52.0" )] |
2276 | #[must_use = "this returns the result of the operation, \ |
2277 | without modifying the original" ] |
2278 | #[track_caller] |
2279 | pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) { |
2280 | (self / rhs, false) |
2281 | } |
2282 | |
2283 | /// Calculates the remainder when `self` is divided by `rhs`. |
2284 | /// |
2285 | /// Returns a tuple of the remainder after dividing along with a boolean |
2286 | /// indicating whether an arithmetic overflow would occur. Note that for |
2287 | /// unsigned integers overflow never occurs, so the second value is |
2288 | /// always `false`. |
2289 | /// |
2290 | /// # Panics |
2291 | /// |
2292 | /// This function will panic if `rhs` is 0. |
2293 | /// |
2294 | /// # Examples |
2295 | /// |
2296 | /// Basic usage |
2297 | /// |
2298 | /// ``` |
2299 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".overflowing_rem(2), (1, false));" )] |
2300 | /// ``` |
2301 | #[inline(always)] |
2302 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
2303 | #[rustc_const_stable(feature = "const_overflowing_int_methods" , since = "1.52.0" )] |
2304 | #[must_use = "this returns the result of the operation, \ |
2305 | without modifying the original" ] |
2306 | #[track_caller] |
2307 | pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) { |
2308 | (self % rhs, false) |
2309 | } |
2310 | |
2311 | /// Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division. |
2312 | /// |
2313 | /// Returns a tuple of the modulo after dividing along with a boolean |
2314 | /// indicating whether an arithmetic overflow would occur. Note that for |
2315 | /// unsigned integers overflow never occurs, so the second value is |
2316 | /// always `false`. |
2317 | /// Since, for the positive integers, all common |
2318 | /// definitions of division are equal, this operation |
2319 | /// is exactly equal to `self.overflowing_rem(rhs)`. |
2320 | /// |
2321 | /// # Panics |
2322 | /// |
2323 | /// This function will panic if `rhs` is 0. |
2324 | /// |
2325 | /// # Examples |
2326 | /// |
2327 | /// Basic usage |
2328 | /// |
2329 | /// ``` |
2330 | #[doc = concat!("assert_eq!(5" , stringify!($SelfT), ".overflowing_rem_euclid(2), (1, false));" )] |
2331 | /// ``` |
2332 | #[inline(always)] |
2333 | #[stable(feature = "euclidean_division" , since = "1.38.0" )] |
2334 | #[rustc_const_stable(feature = "const_euclidean_int_methods" , since = "1.52.0" )] |
2335 | #[must_use = "this returns the result of the operation, \ |
2336 | without modifying the original" ] |
2337 | #[track_caller] |
2338 | pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) { |
2339 | (self % rhs, false) |
2340 | } |
2341 | |
2342 | /// Negates self in an overflowing fashion. |
2343 | /// |
2344 | /// Returns `!self + 1` using wrapping operations to return the value |
2345 | /// that represents the negation of this unsigned value. Note that for |
2346 | /// positive unsigned values overflow always occurs, but negating 0 does |
2347 | /// not overflow. |
2348 | /// |
2349 | /// # Examples |
2350 | /// |
2351 | /// Basic usage |
2352 | /// |
2353 | /// ``` |
2354 | #[doc = concat!("assert_eq!(0" , stringify!($SelfT), ".overflowing_neg(), (0, false));" )] |
2355 | #[doc = concat!("assert_eq!(2" , stringify!($SelfT), ".overflowing_neg(), (-2i32 as " , stringify!($SelfT), ", true));" )] |
2356 | /// ``` |
2357 | #[inline(always)] |
2358 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
2359 | #[rustc_const_stable(feature = "const_wrapping_math" , since = "1.32.0" )] |
2360 | #[must_use = "this returns the result of the operation, \ |
2361 | without modifying the original" ] |
2362 | pub const fn overflowing_neg(self) -> (Self, bool) { |
2363 | ((!self).wrapping_add(1), self != 0) |
2364 | } |
2365 | |
2366 | /// Shifts self left by `rhs` bits. |
2367 | /// |
2368 | /// Returns a tuple of the shifted version of self along with a boolean |
2369 | /// indicating whether the shift value was larger than or equal to the |
2370 | /// number of bits. If the shift value is too large, then value is |
2371 | /// masked (N-1) where N is the number of bits, and this value is then |
2372 | /// used to perform the shift. |
2373 | /// |
2374 | /// # Examples |
2375 | /// |
2376 | /// Basic usage |
2377 | /// |
2378 | /// ``` |
2379 | #[doc = concat!("assert_eq!(0x1" , stringify!($SelfT), ".overflowing_shl(4), (0x10, false));" )] |
2380 | #[doc = concat!("assert_eq!(0x1" , stringify!($SelfT), ".overflowing_shl(132), (0x10, true));" )] |
2381 | /// ``` |
2382 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
2383 | #[rustc_const_stable(feature = "const_wrapping_math" , since = "1.32.0" )] |
2384 | #[must_use = "this returns the result of the operation, \ |
2385 | without modifying the original" ] |
2386 | #[inline(always)] |
2387 | pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) { |
2388 | (self.wrapping_shl(rhs), rhs >= Self::BITS) |
2389 | } |
2390 | |
2391 | /// Shifts self right by `rhs` bits. |
2392 | /// |
2393 | /// Returns a tuple of the shifted version of self along with a boolean |
2394 | /// indicating whether the shift value was larger than or equal to the |
2395 | /// number of bits. If the shift value is too large, then value is |
2396 | /// masked (N-1) where N is the number of bits, and this value is then |
2397 | /// used to perform the shift. |
2398 | /// |
2399 | /// # Examples |
2400 | /// |
2401 | /// Basic usage |
2402 | /// |
2403 | /// ``` |
2404 | #[doc = concat!("assert_eq!(0x10" , stringify!($SelfT), ".overflowing_shr(4), (0x1, false));" )] |
2405 | #[doc = concat!("assert_eq!(0x10" , stringify!($SelfT), ".overflowing_shr(132), (0x1, true));" )] |
2406 | /// ``` |
2407 | #[stable(feature = "wrapping" , since = "1.7.0" )] |
2408 | #[rustc_const_stable(feature = "const_wrapping_math" , since = "1.32.0" )] |
2409 | #[must_use = "this returns the result of the operation, \ |
2410 | without modifying the original" ] |
2411 | #[inline(always)] |
2412 | pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) { |
2413 | (self.wrapping_shr(rhs), rhs >= Self::BITS) |
2414 | } |
2415 | |
2416 | /// Raises self to the power of `exp`, using exponentiation by squaring. |
2417 | /// |
2418 | /// Returns a tuple of the exponentiation along with a bool indicating |
2419 | /// whether an overflow happened. |
2420 | /// |
2421 | /// # Examples |
2422 | /// |
2423 | /// Basic usage: |
2424 | /// |
2425 | /// ``` |
2426 | #[doc = concat!("assert_eq!(3" , stringify!($SelfT), ".overflowing_pow(5), (243, false));" )] |
2427 | /// assert_eq!(3u8.overflowing_pow(6), (217, true)); |
2428 | /// ``` |
2429 | #[stable(feature = "no_panic_pow" , since = "1.34.0" )] |
2430 | #[rustc_const_stable(feature = "const_int_pow" , since = "1.50.0" )] |
2431 | #[must_use = "this returns the result of the operation, \ |
2432 | without modifying the original" ] |
2433 | #[inline] |
2434 | pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) { |
2435 | if exp == 0{ |
2436 | return (1,false); |
2437 | } |
2438 | let mut base = self; |
2439 | let mut acc: Self = 1; |
2440 | let mut overflown = false; |
2441 | // Scratch space for storing results of overflowing_mul. |
2442 | let mut r; |
2443 | |
2444 | while exp > 1 { |
2445 | if (exp & 1) == 1 { |
2446 | r = acc.overflowing_mul(base); |
2447 | acc = r.0; |
2448 | overflown |= r.1; |
2449 | } |
2450 | exp /= 2; |
2451 | r = base.overflowing_mul(base); |
2452 | base = r.0; |
2453 | overflown |= r.1; |
2454 | } |
2455 | |
2456 | // since exp!=0, finally the exp must be 1. |
2457 | // Deal with the final bit of the exponent separately, since |
2458 | // squaring the base afterwards is not necessary and may cause a |
2459 | // needless overflow. |
2460 | r = acc.overflowing_mul(base); |
2461 | r.1 |= overflown; |
2462 | |
2463 | r |
2464 | } |
2465 | |
2466 | /// Raises self to the power of `exp`, using exponentiation by squaring. |
2467 | /// |
2468 | /// # Examples |
2469 | /// |
2470 | /// Basic usage: |
2471 | /// |
2472 | /// ``` |
2473 | #[doc = concat!("assert_eq!(2" , stringify!($SelfT), ".pow(5), 32);" )] |
2474 | /// ``` |
2475 | #[stable(feature = "rust1" , since = "1.0.0" )] |
2476 | #[rustc_const_stable(feature = "const_int_pow" , since = "1.50.0" )] |
2477 | #[must_use = "this returns the result of the operation, \ |
2478 | without modifying the original" ] |
2479 | #[inline] |
2480 | #[rustc_inherit_overflow_checks] |
2481 | pub const fn pow(self, mut exp: u32) -> Self { |
2482 | if exp == 0 { |
2483 | return 1; |
2484 | } |
2485 | let mut base = self; |
2486 | let mut acc = 1; |
2487 | |
2488 | while exp > 1 { |
2489 | if (exp & 1) == 1 { |
2490 | acc = acc * base; |
2491 | } |
2492 | exp /= 2; |
2493 | base = base * base; |
2494 | } |
2495 | |
2496 | // since exp!=0, finally the exp must be 1. |
2497 | // Deal with the final bit of the exponent separately, since |
2498 | // squaring the base afterwards is not necessary and may cause a |
2499 | // needless overflow. |
2500 | acc * base |
2501 | } |
2502 | |
2503 | /// Returns the square root of the number, rounded down. |
2504 | /// |
2505 | /// # Examples |
2506 | /// |
2507 | /// Basic usage: |
2508 | /// ``` |
2509 | /// #![feature(isqrt)] |
2510 | #[doc = concat!("assert_eq!(10" , stringify!($SelfT), ".isqrt(), 3);" )] |
2511 | /// ``` |
2512 | #[unstable(feature = "isqrt" , issue = "116226" )] |
2513 | #[rustc_const_unstable(feature = "isqrt" , issue = "116226" )] |
2514 | #[must_use = "this returns the result of the operation, \ |
2515 | without modifying the original" ] |
2516 | #[inline] |
2517 | pub const fn isqrt(self) -> Self { |
2518 | if self < 2 { |
2519 | return self; |
2520 | } |
2521 | |
2522 | // The algorithm is based on the one presented in |
2523 | // <https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_(base_2)> |
2524 | // which cites as source the following C code: |
2525 | // <https://web.archive.org/web/20120306040058/http://medialab.freaknet.org/martin/src/sqrt/sqrt.c>. |
2526 | |
2527 | let mut op = self; |
2528 | let mut res = 0; |
2529 | let mut one = 1 << (self.ilog2() & !1); |
2530 | |
2531 | while one != 0 { |
2532 | if op >= res + one { |
2533 | op -= res + one; |
2534 | res = (res >> 1) + one; |
2535 | } else { |
2536 | res >>= 1; |
2537 | } |
2538 | one >>= 2; |
2539 | } |
2540 | |
2541 | // SAFETY: the result is positive and fits in an integer with half as many bits. |
2542 | // Inform the optimizer about it. |
2543 | unsafe { |
2544 | hint::assert_unchecked(0 < res); |
2545 | hint::assert_unchecked(res < 1 << (Self::BITS / 2)); |
2546 | } |
2547 | |
2548 | res |
2549 | } |
2550 | |
2551 | /// Performs Euclidean division. |
2552 | /// |
2553 | /// Since, for the positive integers, all common |
2554 | /// definitions of division are equal, this |
2555 | /// is exactly equal to `self / rhs`. |
2556 | /// |
2557 | /// # Panics |
2558 | /// |
2559 | /// This function will panic if `rhs` is 0. |
2560 | /// |
2561 | /// # Examples |
2562 | /// |
2563 | /// Basic usage: |
2564 | /// |
2565 | /// ``` |
2566 | #[doc = concat!("assert_eq!(7" , stringify!($SelfT), ".div_euclid(4), 1); // or any other integer type" )] |
2567 | /// ``` |
2568 | #[stable(feature = "euclidean_division" , since = "1.38.0" )] |
2569 | #[rustc_const_stable(feature = "const_euclidean_int_methods" , since = "1.52.0" )] |
2570 | #[must_use = "this returns the result of the operation, \ |
2571 | without modifying the original" ] |
2572 | #[inline(always)] |
2573 | #[track_caller] |
2574 | pub const fn div_euclid(self, rhs: Self) -> Self { |
2575 | self / rhs |
2576 | } |
2577 | |
2578 | |
2579 | /// Calculates the least remainder of `self (mod rhs)`. |
2580 | /// |
2581 | /// Since, for the positive integers, all common |
2582 | /// definitions of division are equal, this |
2583 | /// is exactly equal to `self % rhs`. |
2584 | /// |
2585 | /// # Panics |
2586 | /// |
2587 | /// This function will panic if `rhs` is 0. |
2588 | /// |
2589 | /// # Examples |
2590 | /// |
2591 | /// Basic usage: |
2592 | /// |
2593 | /// ``` |
2594 | #[doc = concat!("assert_eq!(7" , stringify!($SelfT), ".rem_euclid(4), 3); // or any other integer type" )] |
2595 | /// ``` |
2596 | #[doc(alias = "modulo" , alias = "mod" )] |
2597 | #[stable(feature = "euclidean_division" , since = "1.38.0" )] |
2598 | #[rustc_const_stable(feature = "const_euclidean_int_methods" , since = "1.52.0" )] |
2599 | #[must_use = "this returns the result of the operation, \ |
2600 | without modifying the original" ] |
2601 | #[inline(always)] |
2602 | #[track_caller] |
2603 | pub const fn rem_euclid(self, rhs: Self) -> Self { |
2604 | self % rhs |
2605 | } |
2606 | |
2607 | /// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity. |
2608 | /// |
2609 | /// This is the same as performing `self / rhs` for all unsigned integers. |
2610 | /// |
2611 | /// # Panics |
2612 | /// |
2613 | /// This function will panic if `rhs` is zero. |
2614 | /// |
2615 | /// # Examples |
2616 | /// |
2617 | /// Basic usage: |
2618 | /// |
2619 | /// ``` |
2620 | /// #![feature(int_roundings)] |
2621 | #[doc = concat!("assert_eq!(7_" , stringify!($SelfT), ".div_floor(4), 1);" )] |
2622 | /// ``` |
2623 | #[unstable(feature = "int_roundings" , issue = "88581" )] |
2624 | #[must_use = "this returns the result of the operation, \ |
2625 | without modifying the original" ] |
2626 | #[inline(always)] |
2627 | #[track_caller] |
2628 | pub const fn div_floor(self, rhs: Self) -> Self { |
2629 | self / rhs |
2630 | } |
2631 | |
2632 | /// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity. |
2633 | /// |
2634 | /// # Panics |
2635 | /// |
2636 | /// This function will panic if `rhs` is zero. |
2637 | /// |
2638 | /// # Examples |
2639 | /// |
2640 | /// Basic usage: |
2641 | /// |
2642 | /// ``` |
2643 | #[doc = concat!("assert_eq!(7_" , stringify!($SelfT), ".div_ceil(4), 2);" )] |
2644 | /// ``` |
2645 | #[stable(feature = "int_roundings1" , since = "1.73.0" )] |
2646 | #[rustc_const_stable(feature = "int_roundings1" , since = "1.73.0" )] |
2647 | #[must_use = "this returns the result of the operation, \ |
2648 | without modifying the original" ] |
2649 | #[inline] |
2650 | #[track_caller] |
2651 | pub const fn div_ceil(self, rhs: Self) -> Self { |
2652 | let d = self / rhs; |
2653 | let r = self % rhs; |
2654 | if r > 0 && rhs > 0 { |
2655 | d + 1 |
2656 | } else { |
2657 | d |
2658 | } |
2659 | } |
2660 | |
2661 | /// Calculates the smallest value greater than or equal to `self` that |
2662 | /// is a multiple of `rhs`. |
2663 | /// |
2664 | /// # Panics |
2665 | /// |
2666 | /// This function will panic if `rhs` is zero. |
2667 | /// |
2668 | /// ## Overflow behavior |
2669 | /// |
2670 | /// On overflow, this function will panic if overflow checks are enabled (default in debug |
2671 | /// mode) and wrap if overflow checks are disabled (default in release mode). |
2672 | /// |
2673 | /// # Examples |
2674 | /// |
2675 | /// Basic usage: |
2676 | /// |
2677 | /// ``` |
2678 | #[doc = concat!("assert_eq!(16_" , stringify!($SelfT), ".next_multiple_of(8), 16);" )] |
2679 | #[doc = concat!("assert_eq!(23_" , stringify!($SelfT), ".next_multiple_of(8), 24);" )] |
2680 | /// ``` |
2681 | #[stable(feature = "int_roundings1" , since = "1.73.0" )] |
2682 | #[rustc_const_stable(feature = "int_roundings1" , since = "1.73.0" )] |
2683 | #[must_use = "this returns the result of the operation, \ |
2684 | without modifying the original" ] |
2685 | #[inline] |
2686 | #[rustc_inherit_overflow_checks] |
2687 | pub const fn next_multiple_of(self, rhs: Self) -> Self { |
2688 | match self % rhs { |
2689 | 0 => self, |
2690 | r => self + (rhs - r) |
2691 | } |
2692 | } |
2693 | |
2694 | /// Calculates the smallest value greater than or equal to `self` that |
2695 | /// is a multiple of `rhs`. Returns `None` if `rhs` is zero or the |
2696 | /// operation would result in overflow. |
2697 | /// |
2698 | /// # Examples |
2699 | /// |
2700 | /// Basic usage: |
2701 | /// |
2702 | /// ``` |
2703 | #[doc = concat!("assert_eq!(16_" , stringify!($SelfT), ".checked_next_multiple_of(8), Some(16));" )] |
2704 | #[doc = concat!("assert_eq!(23_" , stringify!($SelfT), ".checked_next_multiple_of(8), Some(24));" )] |
2705 | #[doc = concat!("assert_eq!(1_" , stringify!($SelfT), ".checked_next_multiple_of(0), None);" )] |
2706 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MAX.checked_next_multiple_of(2), None);" )] |
2707 | /// ``` |
2708 | #[stable(feature = "int_roundings1" , since = "1.73.0" )] |
2709 | #[rustc_const_stable(feature = "int_roundings1" , since = "1.73.0" )] |
2710 | #[must_use = "this returns the result of the operation, \ |
2711 | without modifying the original" ] |
2712 | #[inline] |
2713 | pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> { |
2714 | match try_opt!(self.checked_rem(rhs)) { |
2715 | 0 => Some(self), |
2716 | // rhs - r cannot overflow because r is smaller than rhs |
2717 | r => self.checked_add(rhs - r) |
2718 | } |
2719 | } |
2720 | |
2721 | /// Returns `true` if and only if `self == 2^k` for some `k`. |
2722 | /// |
2723 | /// # Examples |
2724 | /// |
2725 | /// Basic usage: |
2726 | /// |
2727 | /// ``` |
2728 | #[doc = concat!("assert!(16" , stringify!($SelfT), ".is_power_of_two());" )] |
2729 | #[doc = concat!("assert!(!10" , stringify!($SelfT), ".is_power_of_two());" )] |
2730 | /// ``` |
2731 | #[must_use] |
2732 | #[stable(feature = "rust1" , since = "1.0.0" )] |
2733 | #[rustc_const_stable(feature = "const_is_power_of_two" , since = "1.32.0" )] |
2734 | #[inline(always)] |
2735 | pub const fn is_power_of_two(self) -> bool { |
2736 | self.count_ones() == 1 |
2737 | } |
2738 | |
2739 | // Returns one less than next power of two. |
2740 | // (For 8u8 next power of two is 8u8 and for 6u8 it is 8u8) |
2741 | // |
2742 | // 8u8.one_less_than_next_power_of_two() == 7 |
2743 | // 6u8.one_less_than_next_power_of_two() == 7 |
2744 | // |
2745 | // This method cannot overflow, as in the `next_power_of_two` |
2746 | // overflow cases it instead ends up returning the maximum value |
2747 | // of the type, and can return 0 for 0. |
2748 | #[inline] |
2749 | #[rustc_const_stable(feature = "const_int_pow" , since = "1.50.0" )] |
2750 | const fn one_less_than_next_power_of_two(self) -> Self { |
2751 | if self <= 1 { return 0; } |
2752 | |
2753 | let p = self - 1; |
2754 | // SAFETY: Because `p > 0`, it cannot consist entirely of leading zeros. |
2755 | // That means the shift is always in-bounds, and some processors |
2756 | // (such as intel pre-haswell) have more efficient ctlz |
2757 | // intrinsics when the argument is non-zero. |
2758 | let z = unsafe { intrinsics::ctlz_nonzero(p) }; |
2759 | <$SelfT>::MAX >> z |
2760 | } |
2761 | |
2762 | /// Returns the smallest power of two greater than or equal to `self`. |
2763 | /// |
2764 | /// When return value overflows (i.e., `self > (1 << (N-1))` for type |
2765 | /// `uN`), it panics in debug mode and the return value is wrapped to 0 in |
2766 | /// release mode (the only situation in which method can return 0). |
2767 | /// |
2768 | /// # Examples |
2769 | /// |
2770 | /// Basic usage: |
2771 | /// |
2772 | /// ``` |
2773 | #[doc = concat!("assert_eq!(2" , stringify!($SelfT), ".next_power_of_two(), 2);" )] |
2774 | #[doc = concat!("assert_eq!(3" , stringify!($SelfT), ".next_power_of_two(), 4);" )] |
2775 | /// ``` |
2776 | #[stable(feature = "rust1" , since = "1.0.0" )] |
2777 | #[rustc_const_stable(feature = "const_int_pow" , since = "1.50.0" )] |
2778 | #[must_use = "this returns the result of the operation, \ |
2779 | without modifying the original" ] |
2780 | #[inline] |
2781 | #[rustc_inherit_overflow_checks] |
2782 | pub const fn next_power_of_two(self) -> Self { |
2783 | self.one_less_than_next_power_of_two() + 1 |
2784 | } |
2785 | |
2786 | /// Returns the smallest power of two greater than or equal to `n`. If |
2787 | /// the next power of two is greater than the type's maximum value, |
2788 | /// `None` is returned, otherwise the power of two is wrapped in `Some`. |
2789 | /// |
2790 | /// # Examples |
2791 | /// |
2792 | /// Basic usage: |
2793 | /// |
2794 | /// ``` |
2795 | #[doc = concat!("assert_eq!(2" , stringify!($SelfT), ".checked_next_power_of_two(), Some(2));" )] |
2796 | #[doc = concat!("assert_eq!(3" , stringify!($SelfT), ".checked_next_power_of_two(), Some(4));" )] |
2797 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MAX.checked_next_power_of_two(), None);" )] |
2798 | /// ``` |
2799 | #[inline] |
2800 | #[stable(feature = "rust1" , since = "1.0.0" )] |
2801 | #[rustc_const_stable(feature = "const_int_pow" , since = "1.50.0" )] |
2802 | #[must_use = "this returns the result of the operation, \ |
2803 | without modifying the original" ] |
2804 | pub const fn checked_next_power_of_two(self) -> Option<Self> { |
2805 | self.one_less_than_next_power_of_two().checked_add(1) |
2806 | } |
2807 | |
2808 | /// Returns the smallest power of two greater than or equal to `n`. If |
2809 | /// the next power of two is greater than the type's maximum value, |
2810 | /// the return value is wrapped to `0`. |
2811 | /// |
2812 | /// # Examples |
2813 | /// |
2814 | /// Basic usage: |
2815 | /// |
2816 | /// ``` |
2817 | /// #![feature(wrapping_next_power_of_two)] |
2818 | /// |
2819 | #[doc = concat!("assert_eq!(2" , stringify!($SelfT), ".wrapping_next_power_of_two(), 2);" )] |
2820 | #[doc = concat!("assert_eq!(3" , stringify!($SelfT), ".wrapping_next_power_of_two(), 4);" )] |
2821 | #[doc = concat!("assert_eq!(" , stringify!($SelfT), "::MAX.wrapping_next_power_of_two(), 0);" )] |
2822 | /// ``` |
2823 | #[inline] |
2824 | #[unstable(feature = "wrapping_next_power_of_two" , issue = "32463" , |
2825 | reason = "needs decision on wrapping behaviour" )] |
2826 | #[rustc_const_unstable(feature = "wrapping_next_power_of_two" , issue = "32463" )] |
2827 | #[must_use = "this returns the result of the operation, \ |
2828 | without modifying the original" ] |
2829 | pub const fn wrapping_next_power_of_two(self) -> Self { |
2830 | self.one_less_than_next_power_of_two().wrapping_add(1) |
2831 | } |
2832 | |
2833 | /// Return the memory representation of this integer as a byte array in |
2834 | /// big-endian (network) byte order. |
2835 | /// |
2836 | #[doc = $to_xe_bytes_doc] |
2837 | /// |
2838 | /// # Examples |
2839 | /// |
2840 | /// ``` |
2841 | #[doc = concat!("let bytes = " , $swap_op, stringify!($SelfT), ".to_be_bytes();" )] |
2842 | #[doc = concat!("assert_eq!(bytes, " , $be_bytes, ");" )] |
2843 | /// ``` |
2844 | #[stable(feature = "int_to_from_bytes" , since = "1.32.0" )] |
2845 | #[rustc_const_stable(feature = "const_int_conversion" , since = "1.44.0" )] |
2846 | #[must_use = "this returns the result of the operation, \ |
2847 | without modifying the original" ] |
2848 | #[inline] |
2849 | pub const fn to_be_bytes(self) -> [u8; mem::size_of::<Self>()] { |
2850 | self.to_be().to_ne_bytes() |
2851 | } |
2852 | |
2853 | /// Return the memory representation of this integer as a byte array in |
2854 | /// little-endian byte order. |
2855 | /// |
2856 | #[doc = $to_xe_bytes_doc] |
2857 | /// |
2858 | /// # Examples |
2859 | /// |
2860 | /// ``` |
2861 | #[doc = concat!("let bytes = " , $swap_op, stringify!($SelfT), ".to_le_bytes();" )] |
2862 | #[doc = concat!("assert_eq!(bytes, " , $le_bytes, ");" )] |
2863 | /// ``` |
2864 | #[stable(feature = "int_to_from_bytes" , since = "1.32.0" )] |
2865 | #[rustc_const_stable(feature = "const_int_conversion" , since = "1.44.0" )] |
2866 | #[must_use = "this returns the result of the operation, \ |
2867 | without modifying the original" ] |
2868 | #[inline] |
2869 | pub const fn to_le_bytes(self) -> [u8; mem::size_of::<Self>()] { |
2870 | self.to_le().to_ne_bytes() |
2871 | } |
2872 | |
2873 | /// Return the memory representation of this integer as a byte array in |
2874 | /// native byte order. |
2875 | /// |
2876 | /// As the target platform's native endianness is used, portable code |
2877 | /// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate, |
2878 | /// instead. |
2879 | /// |
2880 | #[doc = $to_xe_bytes_doc] |
2881 | /// |
2882 | /// [`to_be_bytes`]: Self::to_be_bytes |
2883 | /// [`to_le_bytes`]: Self::to_le_bytes |
2884 | /// |
2885 | /// # Examples |
2886 | /// |
2887 | /// ``` |
2888 | #[doc = concat!("let bytes = " , $swap_op, stringify!($SelfT), ".to_ne_bytes();" )] |
2889 | /// assert_eq!( |
2890 | /// bytes, |
2891 | /// if cfg!(target_endian = "big") { |
2892 | #[doc = concat!(" " , $be_bytes)] |
2893 | /// } else { |
2894 | #[doc = concat!(" " , $le_bytes)] |
2895 | /// } |
2896 | /// ); |
2897 | /// ``` |
2898 | #[stable(feature = "int_to_from_bytes" , since = "1.32.0" )] |
2899 | #[rustc_const_stable(feature = "const_int_conversion" , since = "1.44.0" )] |
2900 | #[must_use = "this returns the result of the operation, \ |
2901 | without modifying the original" ] |
2902 | // SAFETY: const sound because integers are plain old datatypes so we can always |
2903 | // transmute them to arrays of bytes |
2904 | #[inline] |
2905 | pub const fn to_ne_bytes(self) -> [u8; mem::size_of::<Self>()] { |
2906 | // SAFETY: integers are plain old datatypes so we can always transmute them to |
2907 | // arrays of bytes |
2908 | unsafe { mem::transmute(self) } |
2909 | } |
2910 | |
2911 | /// Create a native endian integer value from its representation |
2912 | /// as a byte array in big endian. |
2913 | /// |
2914 | #[doc = $from_xe_bytes_doc] |
2915 | /// |
2916 | /// # Examples |
2917 | /// |
2918 | /// ``` |
2919 | #[doc = concat!("let value = " , stringify!($SelfT), "::from_be_bytes(" , $be_bytes, ");" )] |
2920 | #[doc = concat!("assert_eq!(value, " , $swap_op, ");" )] |
2921 | /// ``` |
2922 | /// |
2923 | /// When starting from a slice rather than an array, fallible conversion APIs can be used: |
2924 | /// |
2925 | /// ``` |
2926 | #[doc = concat!("fn read_be_" , stringify!($SelfT), "(input: &mut &[u8]) -> " , stringify!($SelfT), " {" )] |
2927 | #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<" , stringify!($SelfT), ">());" )] |
2928 | /// *input = rest; |
2929 | #[doc = concat!(" " , stringify!($SelfT), "::from_be_bytes(int_bytes.try_into().unwrap())" )] |
2930 | /// } |
2931 | /// ``` |
2932 | #[stable(feature = "int_to_from_bytes" , since = "1.32.0" )] |
2933 | #[rustc_const_stable(feature = "const_int_conversion" , since = "1.44.0" )] |
2934 | #[must_use] |
2935 | #[inline] |
2936 | pub const fn from_be_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self { |
2937 | Self::from_be(Self::from_ne_bytes(bytes)) |
2938 | } |
2939 | |
2940 | /// Create a native endian integer value from its representation |
2941 | /// as a byte array in little endian. |
2942 | /// |
2943 | #[doc = $from_xe_bytes_doc] |
2944 | /// |
2945 | /// # Examples |
2946 | /// |
2947 | /// ``` |
2948 | #[doc = concat!("let value = " , stringify!($SelfT), "::from_le_bytes(" , $le_bytes, ");" )] |
2949 | #[doc = concat!("assert_eq!(value, " , $swap_op, ");" )] |
2950 | /// ``` |
2951 | /// |
2952 | /// When starting from a slice rather than an array, fallible conversion APIs can be used: |
2953 | /// |
2954 | /// ``` |
2955 | #[doc = concat!("fn read_le_" , stringify!($SelfT), "(input: &mut &[u8]) -> " , stringify!($SelfT), " {" )] |
2956 | #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<" , stringify!($SelfT), ">());" )] |
2957 | /// *input = rest; |
2958 | #[doc = concat!(" " , stringify!($SelfT), "::from_le_bytes(int_bytes.try_into().unwrap())" )] |
2959 | /// } |
2960 | /// ``` |
2961 | #[stable(feature = "int_to_from_bytes" , since = "1.32.0" )] |
2962 | #[rustc_const_stable(feature = "const_int_conversion" , since = "1.44.0" )] |
2963 | #[must_use] |
2964 | #[inline] |
2965 | pub const fn from_le_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self { |
2966 | Self::from_le(Self::from_ne_bytes(bytes)) |
2967 | } |
2968 | |
2969 | /// Create a native endian integer value from its memory representation |
2970 | /// as a byte array in native endianness. |
2971 | /// |
2972 | /// As the target platform's native endianness is used, portable code |
2973 | /// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as |
2974 | /// appropriate instead. |
2975 | /// |
2976 | /// [`from_be_bytes`]: Self::from_be_bytes |
2977 | /// [`from_le_bytes`]: Self::from_le_bytes |
2978 | /// |
2979 | #[doc = $from_xe_bytes_doc] |
2980 | /// |
2981 | /// # Examples |
2982 | /// |
2983 | /// ``` |
2984 | #[doc = concat!("let value = " , stringify!($SelfT), "::from_ne_bytes(if cfg!(target_endian = \"big \") {" )] |
2985 | #[doc = concat!(" " , $be_bytes, "" )] |
2986 | /// } else { |
2987 | #[doc = concat!(" " , $le_bytes, "" )] |
2988 | /// }); |
2989 | #[doc = concat!("assert_eq!(value, " , $swap_op, ");" )] |
2990 | /// ``` |
2991 | /// |
2992 | /// When starting from a slice rather than an array, fallible conversion APIs can be used: |
2993 | /// |
2994 | /// ``` |
2995 | #[doc = concat!("fn read_ne_" , stringify!($SelfT), "(input: &mut &[u8]) -> " , stringify!($SelfT), " {" )] |
2996 | #[doc = concat!(" let (int_bytes, rest) = input.split_at(std::mem::size_of::<" , stringify!($SelfT), ">());" )] |
2997 | /// *input = rest; |
2998 | #[doc = concat!(" " , stringify!($SelfT), "::from_ne_bytes(int_bytes.try_into().unwrap())" )] |
2999 | /// } |
3000 | /// ``` |
3001 | #[stable(feature = "int_to_from_bytes" , since = "1.32.0" )] |
3002 | #[rustc_const_stable(feature = "const_int_conversion" , since = "1.44.0" )] |
3003 | #[must_use] |
3004 | // SAFETY: const sound because integers are plain old datatypes so we can always |
3005 | // transmute to them |
3006 | #[inline] |
3007 | pub const fn from_ne_bytes(bytes: [u8; mem::size_of::<Self>()]) -> Self { |
3008 | // SAFETY: integers are plain old datatypes so we can always transmute to them |
3009 | unsafe { mem::transmute(bytes) } |
3010 | } |
3011 | |
3012 | /// New code should prefer to use |
3013 | #[doc = concat!("[`" , stringify!($SelfT), "::MIN" , "`] instead." )] |
3014 | /// |
3015 | /// Returns the smallest value that can be represented by this integer type. |
3016 | #[stable(feature = "rust1" , since = "1.0.0" )] |
3017 | #[rustc_promotable] |
3018 | #[inline(always)] |
3019 | #[rustc_const_stable(feature = "const_max_value" , since = "1.32.0" )] |
3020 | #[deprecated(since = "TBD" , note = "replaced by the `MIN` associated constant on this type" )] |
3021 | #[rustc_diagnostic_item = concat!(stringify!($SelfT), "_legacy_fn_min_value" )] |
3022 | pub const fn min_value() -> Self { Self::MIN } |
3023 | |
3024 | /// New code should prefer to use |
3025 | #[doc = concat!("[`" , stringify!($SelfT), "::MAX" , "`] instead." )] |
3026 | /// |
3027 | /// Returns the largest value that can be represented by this integer type. |
3028 | #[stable(feature = "rust1" , since = "1.0.0" )] |
3029 | #[rustc_promotable] |
3030 | #[inline(always)] |
3031 | #[rustc_const_stable(feature = "const_max_value" , since = "1.32.0" )] |
3032 | #[deprecated(since = "TBD" , note = "replaced by the `MAX` associated constant on this type" )] |
3033 | #[rustc_diagnostic_item = concat!(stringify!($SelfT), "_legacy_fn_max_value" )] |
3034 | pub const fn max_value() -> Self { Self::MAX } |
3035 | } |
3036 | } |
3037 | |