1//! Numeric traits and functions for the built-in numeric types.
23#![stable(feature = "rust1", since = "1.0.0")]
45use crate::convert::{BoundedCastFromInt, CheckedCastFromInt};
6use crate::panic::const_panic;
7use crate::str::FromStr;
8use crate::ub_checks::assert_unsafe_precondition;
9use crate::{ascii, intrinsics, mem};
1011// FIXME(const-hack): Used because the `?` operator is not allowed in a const context.
12macro_rules!try_opt {
13 ($e:expr) => {
14match $e {
15Some(x) => x,
16None => return None,
17 }
18 };
19}
2021// Use this when the generated code should differ between signed and unsigned types.
22macro_rules!sign_dependent_expr {
23 (signed ? if signed { $signed_case:expr } if unsigned { $unsigned_case:expr } ) => {
24$signed_case
25};
26 (unsigned ? if signed { $signed_case:expr } if unsigned { $unsigned_case:expr } ) => {
27$unsigned_case
28};
29}
3031// These modules are public only for testing.
32#[doc(hidden)]
33#[unstable(
34 feature = "num_internals",
35 reason = "internal routines only exposed for testing",
36 issue = "none"
37)]
38pub mod imp;
3940#[macro_use]
41mod int_macros; // import int_impl!
42#[macro_use]
43mod uint_macros; // import uint_impl!
4445mod error;
46#[cfg(not(no_fp_fmt_parse))]
47mod float_parse;
48mod nonzero;
49mod saturating;
50mod traits;
51mod wrapping;
5253/// 100% perma-unstable
54#[doc(hidden)]
55pub mod niche_types;
5657#[stable(feature = "int_error_matching", since = "1.55.0")]
58pub use error::IntErrorKind;
59#[stable(feature = "rust1", since = "1.0.0")]
60pub use error::ParseIntError;
61#[stable(feature = "try_from", since = "1.34.0")]
62pub use error::TryFromIntError;
63#[stable(feature = "rust1", since = "1.0.0")]
64#[cfg(not(no_fp_fmt_parse))]
65pub use float_parse::ParseFloatError;
66#[stable(feature = "generic_nonzero", since = "1.79.0")]
67pub use nonzero::NonZero;
68#[unstable(
69 feature = "nonzero_internals",
70 reason = "implementation detail which may disappear or be replaced at any time",
71 issue = "none"
72)]
73pub use nonzero::ZeroablePrimitive;
74#[stable(feature = "signed_nonzero", since = "1.34.0")]
75pub use nonzero::{NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize};
76#[stable(feature = "nonzero", since = "1.28.0")]
77pub use nonzero::{NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroUsize};
78#[stable(feature = "saturating_int_impl", since = "1.74.0")]
79pub use saturating::Saturating;
80#[stable(feature = "rust1", since = "1.0.0")]
81pub use wrapping::Wrapping;
8283macro_rules!u8_xe_bytes_doc {
84 () => {
85"
8687**Note**: This function is meaningless on `u8`. Byte order does not exist as a
88concept for byte-sized integers. This function is only provided in symmetry
89with larger integer types.
9091"
92};
93}
9495macro_rules!i8_xe_bytes_doc {
96 () => {
97"
9899**Note**: This function is meaningless on `i8`. Byte order does not exist as a
100concept for byte-sized integers. This function is only provided in symmetry
101with larger integer types. You can cast from and to `u8` using
102[`cast_signed`](u8::cast_signed) and [`cast_unsigned`](Self::cast_unsigned).
103104"
105};
106}
107108macro_rules!usize_isize_to_xe_bytes_doc {
109 () => {
110"
111112**Note**: This function returns an array of length 2, 4 or 8 bytes
113depending on the target pointer size.
114115"
116};
117}
118119macro_rules!usize_isize_from_xe_bytes_doc {
120 () => {
121"
122123**Note**: This function takes an array of length 2, 4 or 8 bytes
124depending on the target pointer size.
125126"
127};
128}
129130macro_rules!midpoint_impl {
131 ($SelfT:ty, unsigned) => {
132/// Calculates the midpoint (average) between `self` and `rhs`.
133 ///
134 /// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
135 /// sufficiently-large unsigned integral type. This implies that the result is
136 /// always rounded towards zero and that no overflow will ever occur.
137 ///
138 /// # Examples
139 ///
140 /// ```
141#[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(4), 2);")]
142 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".midpoint(4), 2);")]
143/// ```
144#[stable(feature = "num_midpoint", since = "1.85.0")]
145 #[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
146 #[must_use = "this returns the result of the operation, \
147 without modifying the original"]
148 #[doc(alias = "average_floor")]
149 #[doc(alias = "average")]
150 #[inline]
151pub const fn midpoint(self, rhs: $SelfT) -> $SelfT {
152// Use the well known branchless algorithm from Hacker's Delight to compute
153 // `(a + b) / 2` without overflowing: `((a ^ b) >> 1) + (a & b)`.
154((self ^ rhs) >> 1) + (self & rhs)
155 }
156 };
157 ($SelfT:ty, signed) => {
158/// Calculates the midpoint (average) between `self` and `rhs`.
159 ///
160 /// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
161 /// sufficiently-large signed integral type. This implies that the result is
162 /// always rounded towards zero and that no overflow will ever occur.
163 ///
164 /// # Examples
165 ///
166 /// ```
167#[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(4), 2);")]
168 #[doc = concat!("assert_eq!((-1", stringify!($SelfT), ").midpoint(2), 0);")]
169 #[doc = concat!("assert_eq!((-7", stringify!($SelfT), ").midpoint(0), -3);")]
170 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(-7), -3);")]
171 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(7), 3);")]
172/// ```
173#[stable(feature = "num_midpoint_signed", since = "1.87.0")]
174 #[rustc_const_stable(feature = "num_midpoint_signed", since = "1.87.0")]
175 #[must_use = "this returns the result of the operation, \
176 without modifying the original"]
177 #[doc(alias = "average_floor")]
178 #[doc(alias = "average_ceil")]
179 #[doc(alias = "average")]
180 #[inline]
181pub const fn midpoint(self, rhs: Self) -> Self {
182// Use the well known branchless algorithm from Hacker's Delight to compute
183 // `(a + b) / 2` without overflowing: `((a ^ b) >> 1) + (a & b)`.
184let t = ((self ^ rhs) >> 1) + (self & rhs);
185// Except that it fails for integers whose sum is an odd negative number as
186 // their floor is one less than their average. So we adjust the result.
187t + (if t < 0 { 1 } else { 0 } & (self ^ rhs))
188 }
189 };
190 ($SelfT:ty, $WideT:ty, unsigned) => {
191/// Calculates the midpoint (average) between `self` and `rhs`.
192 ///
193 /// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
194 /// sufficiently-large unsigned integral type. This implies that the result is
195 /// always rounded towards zero and that no overflow will ever occur.
196 ///
197 /// # Examples
198 ///
199 /// ```
200#[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(4), 2);")]
201 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".midpoint(4), 2);")]
202/// ```
203#[stable(feature = "num_midpoint", since = "1.85.0")]
204 #[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
205 #[must_use = "this returns the result of the operation, \
206 without modifying the original"]
207 #[doc(alias = "average_floor")]
208 #[doc(alias = "average")]
209 #[inline]
210pub const fn midpoint(self, rhs: $SelfT) -> $SelfT {
211 ((self as $WideT + rhs as $WideT) / 2) as $SelfT
212}
213 };
214 ($SelfT:ty, $WideT:ty, signed) => {
215/// Calculates the midpoint (average) between `self` and `rhs`.
216 ///
217 /// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
218 /// sufficiently-large signed integral type. This implies that the result is
219 /// always rounded towards zero and that no overflow will ever occur.
220 ///
221 /// # Examples
222 ///
223 /// ```
224#[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(4), 2);")]
225 #[doc = concat!("assert_eq!((-1", stringify!($SelfT), ").midpoint(2), 0);")]
226 #[doc = concat!("assert_eq!((-7", stringify!($SelfT), ").midpoint(0), -3);")]
227 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(-7), -3);")]
228 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(7), 3);")]
229/// ```
230#[stable(feature = "num_midpoint_signed", since = "1.87.0")]
231 #[rustc_const_stable(feature = "num_midpoint_signed", since = "1.87.0")]
232 #[must_use = "this returns the result of the operation, \
233 without modifying the original"]
234 #[doc(alias = "average_floor")]
235 #[doc(alias = "average_ceil")]
236 #[doc(alias = "average")]
237 #[inline]
238pub const fn midpoint(self, rhs: $SelfT) -> $SelfT {
239 ((self as $WideT + rhs as $WideT) / 2) as $SelfT
240}
241 };
242}
243244macro_rules!widening_mul_impl {
245 ($SelfT:ty, $WideT:ty) => {
246/// Widening multiplication. Computes `self * rhs`, widening to a larger integer.
247 ///
248 /// The returned value is always exact and can never overflow.
249 ///
250 /// Note that this method is semantically equivalent to [`carrying_mul`] with a
251 /// carry of zero, with the latter instead returning a tuple denoting the low and
252 /// high parts of the result. Consider using it instead if you need
253 /// interoperability with other big int helper functions, or if this method isn't
254 /// available for a given type.
255 ///
256 /// [`carrying_mul`]: Self::carrying_mul
257 ///
258 /// # Examples
259 ///
260 /// ```
261 /// #![feature(widening_mul)]
262 ///
263#[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.widening_mul(0_", stringify!($SelfT), "), 0);")]
264 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.widening_mul(", stringify!($SelfT), "::MAX), ", stringify!($SelfT), "::MAX as ", stringify!($WideT), " * ", stringify!($SelfT), "::MAX as ", stringify!($WideT), ");")]
265/// ```
266#[unstable(feature = "widening_mul", issue = "152016")]
267 #[rustc_const_unstable(feature = "widening_mul", issue = "152016")]
268 #[must_use = "this returns the result of the operation, \
269 without modifying the original"]
270 #[inline]
271pub const fn widening_mul(self, rhs: Self) -> $WideT {
272self as $WideT * rhs as $WideT
273}
274 }
275}
276277macro_rules!widening_carryless_mul_impl {
278 ($SelfT:ty, $WideT:ty) => {
279/// Performs a widening carry-less multiplication.
280 ///
281 /// # Examples
282 ///
283 /// ```
284 /// #![feature(uint_carryless_mul)]
285 ///
286#[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.widening_carryless_mul(",
287stringify!($SelfT), "::MAX), ", stringify!($WideT), "::MAX / 3);")]
288/// ```
289#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
290 #[doc(alias = "clmul")]
291 #[unstable(feature = "uint_carryless_mul", issue = "152080")]
292 #[must_use = "this returns the result of the operation, \
293 without modifying the original"]
294 #[inline]
295pub const fn widening_carryless_mul(self, rhs: $SelfT) -> $WideT {
296 (self as $WideT).carryless_mul(rhs as $WideT)
297 }
298 }
299}
300301macro_rules!carrying_carryless_mul_impl {
302 (u128, u256) => {
303carrying_carryless_mul_impl! { @internal u128 =>
304pub const fn carrying_carryless_mul(self, rhs: Self, carry: Self) -> (Self, Self) {
305let x0 = self as u64;
306let x1 = (self >> 64) as u64;
307let y0 = rhs as u64;
308let y1 = (rhs >> 64) as u64;
309310let z0 = u64::widening_carryless_mul(x0, y0);
311let z2 = u64::widening_carryless_mul(x1, y1);
312313// The grade school algorithm would compute:
314 // z1 = x0y1 ^ x1y0
315316 // Instead, Karatsuba first computes:
317let z3 = u64::widening_carryless_mul(x0 ^ x1, y0 ^ y1);
318// Since it distributes over XOR,
319 // z3 == x0y0 ^ x0y1 ^ x1y0 ^ x1y1
320 // |--| |---------| |--|
321 // == z0 ^ z1 ^ z2
322 // so we can compute z1 as
323let z1 = z3 ^ z0 ^ z2;
324325let lo = z0 ^ (z1 << 64);
326let hi = z2 ^ (z1 >> 64);
327328 (lo ^ carry, hi)
329 }
330 }
331 };
332 ($SelfT:ty, $WideT:ty) => {
333carrying_carryless_mul_impl! { @internal $SelfT =>
334pub const fn carrying_carryless_mul(self, rhs: Self, carry: Self) -> (Self, Self) {
335// Can't use widening_carryless_mul because it's not implemented for usize.
336let p = (self as $WideT).carryless_mul(rhs as $WideT);
337338let lo = (p as $SelfT);
339let hi = (p >> Self::BITS) as $SelfT;
340341 (lo ^ carry, hi)
342 }
343 }
344 };
345 (@internal $SelfT:ty => $($fn:tt)*) => {
346/// Calculates the "full carryless multiplication" without the possibility to overflow.
347 ///
348 /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
349 /// of the result as two separate values, in that order.
350 ///
351 /// # Examples
352 ///
353 /// Please note that this example is shared among integer types, which is why `u8` is used.
354 ///
355 /// ```
356 /// #![feature(uint_carryless_mul)]
357 ///
358 /// assert_eq!(0b1000_0000u8.carrying_carryless_mul(0b1000_0000, 0b0000), (0, 0b0100_0000));
359 /// assert_eq!(0b1000_0000u8.carrying_carryless_mul(0b1000_0000, 0b1111), (0b1111, 0b0100_0000));
360#[doc = concat!("assert_eq!(",
361stringify!($SelfT), "::MAX.carrying_carryless_mul(", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX), ",
362"(!(", stringify!($SelfT), "::MAX / 3), ", stringify!($SelfT), "::MAX / 3));"
363)]
364/// ```
365#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
366 #[doc(alias = "clmul")]
367 #[unstable(feature = "uint_carryless_mul", issue = "152080")]
368 #[must_use = "this returns the result of the operation, \
369 without modifying the original"]
370 #[inline]
371$($fn)*
372 }
373}
374375impl i8 {
376/// The smallest value that can be represented by this integer type
#[doc = "(−2<sup>7</sup>)."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i8::MIN, -128);"]
/// ```
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MIN: Self = !Self::MAX;
/// The largest value that can be represented by this integer type
#[doc = "(2<sup>7</sup> − 1)."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i8::MAX, 127);"]
/// ```
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MAX: Self = (<u8>::MAX >> 1) as Self;
/// The size of this integer type in bits.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i8::BITS, 8);"]
/// ```
#[stable(feature = "int_bits_const", since = "1.53.0")]
pub const BITS: u32 = <u8>::BITS;
/// Returns the number of ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 0b100_0000i8;"]
///
/// assert_eq!(n.count_ones(), 1);
/// ```
///
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[doc(alias = "popcount")]
#[doc(alias = "popcnt")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn count_ones(self) -> u32 { (self as u8).count_ones() }
/// Returns the number of zeros in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i8::MAX.count_zeros(), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn count_zeros(self) -> u32 { (!self).count_ones() }
/// Returns the number of leading zeros in the binary representation of `self`.
///
/// Depending on what you're doing with the value, you might also be interested in the
/// [`ilog2`] function which returns a consistent number, even if the type widens.
///
/// # Examples
///
/// ```
#[doc = "let n = -1i8;"]
///
/// assert_eq!(n.leading_zeros(), 0);
/// ```
#[doc = "[`ilog2`]: i8::ilog2"]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn leading_zeros(self) -> u32 { (self as u8).leading_zeros() }
/// Returns the number of trailing zeros in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = -4i8;"]
///
/// assert_eq!(n.trailing_zeros(), 2);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn trailing_zeros(self) -> u32 { (self as u8).trailing_zeros() }
/// Returns the number of leading ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = -1i8;"]
///
#[doc = "assert_eq!(n.leading_ones(), 8);"]
/// ```
#[stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn leading_ones(self) -> u32 { (self as u8).leading_ones() }
/// Returns the number of trailing ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 3i8;"]
///
/// assert_eq!(n.trailing_ones(), 2);
/// ```
#[stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn trailing_ones(self) -> u32 { (self as u8).trailing_ones() }
/// Returns `self` with only the most significant bit set, or `0` if
/// the input is `0`.
///
/// # Examples
///
/// ```
#[doc = "let n: i8 = 0b_01100100;"]
///
/// assert_eq!(n.isolate_highest_one(), 0b_01000000);
#[doc = "assert_eq!(0_i8.isolate_highest_one(), 0);"]
/// ```
#[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn isolate_highest_one(self) -> Self {
self &
(((1 as i8) << (<i8>::BITS - 1)).wrapping_shr(self.leading_zeros()))
}
/// Returns `self` with only the least significant bit set, or `0` if
/// the input is `0`.
///
/// # Examples
///
/// ```
#[doc = "let n: i8 = 0b_01100100;"]
///
/// assert_eq!(n.isolate_lowest_one(), 0b_00000100);
#[doc = "assert_eq!(0_i8.isolate_lowest_one(), 0);"]
/// ```
#[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn isolate_lowest_one(self) -> Self { self & self.wrapping_neg() }
/// Returns the index of the highest bit set to one in `self`, or `None`
/// if `self` is `0`.
///
/// Note that for non-negative numbers, this is equivalent to
/// [`checked_ilog2`](Self::checked_ilog2).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0b0_i8.highest_one(), None);"]
#[doc = "assert_eq!(0b1_i8.highest_one(), Some(0));"]
#[doc = "assert_eq!(0b1_0000_i8.highest_one(), Some(4));"]
#[doc = "assert_eq!(0b1_1111_i8.highest_one(), Some(4));"]
/// ```
#[stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn highest_one(self) -> Option<u32> { (self as u8).highest_one() }
/// Returns the index of the lowest bit set to one in `self`, or `None`
/// if `self` is `0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0b0_i8.lowest_one(), None);"]
#[doc = "assert_eq!(0b1_i8.lowest_one(), Some(0));"]
#[doc = "assert_eq!(0b1_0000_i8.lowest_one(), Some(4));"]
#[doc = "assert_eq!(0b1_1111_i8.lowest_one(), Some(0));"]
/// ```
#[stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn lowest_one(self) -> Option<u32> { (self as u8).lowest_one() }
/// Returns the bit pattern of `self` reinterpreted as an unsigned integer of the same size.
///
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
/// the same.
///
/// # Examples
///
/// ```
#[doc = "let n = -1i8;"]
///
#[doc = "assert_eq!(n.cast_unsigned(), u8::MAX);"]
/// ```
#[stable(feature = "integer_sign_cast", since = "1.87.0")]
#[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_unsigned(self) -> u8 { self as u8 }
/// Saturating conversion of `self` to an unsigned integer of the same size.
///
/// Negative values are clamped to `0`.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`checked_cast_unsigned`](Self::checked_cast_unsigned),
/// or [`strict_cast_unsigned`](Self::strict_cast_unsigned).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = i8::MIN;"]
///
#[doc = "assert_eq!(n.saturating_cast_unsigned(), 0u8);"]
#[doc = "assert_eq!(64i8.saturating_cast_unsigned(), 64u8);"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_cast_unsigned(self) -> u8 {
if self >= 0 { self.cast_unsigned() } else { 0 }
}
/// Checked conversion of `self` to an unsigned integer of the same size,
/// returning `None` if `self` is negative.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`saturating_cast_unsigned`](Self::saturating_cast_unsigned),
/// or [`strict_cast_unsigned`](Self::strict_cast_unsigned).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = i8::MIN;"]
///
#[doc = "assert_eq!(n.checked_cast_unsigned(), None);"]
#[doc = "assert_eq!(64i8.checked_cast_unsigned(), Some(64u8));"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn checked_cast_unsigned(self) -> Option<u8> {
if self >= 0 { Some(self.cast_unsigned()) } else { None }
}
/// Strict conversion of `self` to an unsigned integer of the same size,
/// which panics if `self` is negative.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`checked_cast_unsigned`](Self::checked_cast_unsigned),
/// or [`saturating_cast_unsigned`](Self::saturating_cast_unsigned).
///
/// # Examples
///
/// ```should_panic
/// #![feature(integer_cast_extras)]
#[doc = "let _ = i8::MIN.strict_cast_unsigned();"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_cast_unsigned(self) -> u8 {
match self.checked_cast_unsigned() {
Some(n) => n,
None => imp::overflow_panic::cast_integer(),
}
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `<<` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = -0x7ei8;"]
#[doc = "let m = 0xa;"]
///
#[doc = "assert_eq!(n.rotate_left(2), m);"]
#[doc = "assert_eq!(n.rotate_left(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn rotate_left(self, n: u32) -> Self {
(self as u8).rotate_left(n) as Self
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `>>` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0xai8;"]
#[doc = "let m = -0x7e;"]
///
#[doc = "assert_eq!(n.rotate_right(2), m);"]
#[doc = "assert_eq!(n.rotate_right(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn rotate_right(self, n: u32) -> Self {
(self as u8).rotate_right(n) as Self
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x12i8;"]
///
/// let m = n.swap_bytes();
///
#[doc = "assert_eq!(m, 0x12);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn swap_bytes(self) -> Self { (self as u8).swap_bytes() as Self }
/// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
/// second least-significant bit becomes second most-significant bit, etc.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x12i8;"]
/// let m = n.reverse_bits();
///
#[doc = "assert_eq!(m, 0x48);"]
#[doc = "assert_eq!(0, 0i8.reverse_bits());"]
/// ```
#[stable(feature = "reverse_bits", since = "1.37.0")]
#[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn reverse_bits(self) -> Self {
(self as u8).reverse_bits() as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are swapped.
///
/// See also [from_be_bytes()](Self::from_be_bytes).
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai8;"]
///
/// if cfg!(target_endian = "big") {
#[doc = " assert_eq!(i8::from_be(n), n)"]
/// } else {
#[doc = " assert_eq!(i8::from_be(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn from_be(x: Self) -> Self { x.swap_bytes() }
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are swapped.
///
/// See also [from_le_bytes()](Self::from_le_bytes).
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai8;"]
///
/// if cfg!(target_endian = "little") {
#[doc = " assert_eq!(i8::from_le(n), n)"]
/// } else {
#[doc = " assert_eq!(i8::from_le(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn from_le(x: Self) -> Self { x }
/// Swaps bytes of `self` on little endian targets.
///
/// On big endian this is a no-op.
///
/// The returned value has the same type as `self`, and will be interpreted
/// as (a potentially different) value of a native-endian
#[doc = "`i8`."]
///
/// See [`to_be_bytes()`](Self::to_be_bytes) for a type-safe alternative.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai8;"]
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be(self) -> Self { self.swap_bytes() }
/// Swaps bytes of `self` on big endian targets.
///
/// On little endian this is a no-op.
///
/// The returned value has the same type as `self`, and will be interpreted
/// as (a potentially different) value of a native-endian
#[doc = "`i8`."]
///
/// See [`to_le_bytes()`](Self::to_le_bytes) for a type-safe alternative.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai8;"]
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le(self) -> Self { self }
/// Checked integer addition. Computes `self + rhs`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i8::MAX - 2).checked_add(1), Some(i8::MAX - 1));"]
#[doc = "assert_eq!((i8::MAX - 2).checked_add(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_add(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer addition. Computes `self + rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i8::MAX - 2).strict_add(1), i8::MAX - 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i8::MAX - 2).strict_add(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_add(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Unchecked integer addition. Computes `self + rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_add(y)` is semantically equivalent to calling
/// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_add`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self + rhs > i8::MAX` or `self + rhs < i8::MIN`,"]
/// i.e. when [`checked_add`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_add`]: i8::checked_add"]
#[doc = "[`wrapping_add`]: i8::wrapping_add"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i8, rhs: i8) {
if !!lhs.overflowing_add(rhs).1 {
let msg =
"unsafe precondition(s) violated: i8::unchecked_add cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_add(self, rhs) }
}
/// Checked addition with an unsigned integer. Computes `self + rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i8.checked_add_unsigned(2), Some(3));"]
#[doc = "assert_eq!((i8::MAX - 2).checked_add_unsigned(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add_unsigned(self, rhs: u8) -> Option<Self> {
let (a, b) = self.overflowing_add_unsigned(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict addition with an unsigned integer. Computes `self + rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i8.strict_add_unsigned(2), 3);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i8::MAX - 2).strict_add_unsigned(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add_unsigned(self, rhs: u8) -> Self {
let (a, b) = self.overflowing_add_unsigned(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Checked integer subtraction. Computes `self - rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i8::MIN + 2).checked_sub(1), Some(i8::MIN + 1));"]
#[doc = "assert_eq!((i8::MIN + 2).checked_sub(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_sub(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer subtraction. Computes `self - rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i8::MIN + 2).strict_sub(1), i8::MIN + 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i8::MIN + 2).strict_sub(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_sub(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
/// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_sub`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self - rhs > i8::MAX` or `self - rhs < i8::MIN`,"]
/// i.e. when [`checked_sub`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_sub`]: i8::checked_sub"]
#[doc = "[`wrapping_sub`]: i8::wrapping_sub"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i8, rhs: i8) {
if !!lhs.overflowing_sub(rhs).1 {
let msg =
"unsafe precondition(s) violated: i8::unchecked_sub cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_sub(self, rhs) }
}
/// Checked subtraction with an unsigned integer. Computes `self - rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i8.checked_sub_unsigned(2), Some(-1));"]
#[doc = "assert_eq!((i8::MIN + 2).checked_sub_unsigned(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub_unsigned(self, rhs: u8) -> Option<Self> {
let (a, b) = self.overflowing_sub_unsigned(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict subtraction with an unsigned integer. Computes `self - rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i8.strict_sub_unsigned(2), -1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i8::MIN + 2).strict_sub_unsigned(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub_unsigned(self, rhs: u8) -> Self {
let (a, b) = self.overflowing_sub_unsigned(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Checked integer multiplication. Computes `self * rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i8::MAX.checked_mul(1), Some(i8::MAX));"]
#[doc = "assert_eq!(i8::MAX.checked_mul(2), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer multiplication. Computes `self * rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i8::MAX.strict_mul(1), i8::MAX);"]
/// ```
///
/// The following panics because of overflow:
///
/// ``` should_panic
#[doc = "let _ = i8::MAX.strict_mul(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_mul(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_mul(rhs);
if b { imp::overflow_panic::mul() } else { a }
}
/// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
/// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_mul`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self * rhs > i8::MAX` or `self * rhs < i8::MIN`,"]
/// i.e. when [`checked_mul`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_mul`]: i8::checked_mul"]
#[doc = "[`wrapping_mul`]: i8::wrapping_mul"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i8, rhs: i8) {
if !!lhs.overflowing_mul(rhs).1 {
let msg =
"unsafe precondition(s) violated: i8::unchecked_mul cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_mul(self, rhs) }
}
/// Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
/// or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i8::MIN + 1).checked_div(-1), Some(127));"]
#[doc = "assert_eq!(i8::MIN.checked_div(-1), None);"]
#[doc = "assert_eq!((1i8).checked_div(0), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1)))
{
None
} else { Some(unsafe { intrinsics::unchecked_div(self, rhs) }) }
}
/// Strict integer division. Computes `self / rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is when one divides `MIN / -1` on a signed type (where
/// [`MIN`](Self::MIN) is the negative minimal value for the type); the result of this is `-MIN`, a positive value
/// that is too large to represent in the type.
///
/// Note that this is equivalent to normal division: `MIN / -1` will also panic both in
/// debug and release builds.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i8::MIN + 1).strict_div(-1), 127);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i8::MIN.strict_div(-1);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1i8).strict_div(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_div(self, rhs: Self) -> Self { self / rhs }
/// Checked Euclidean division. Computes `self.div_euclid(rhs)`,
/// returning `None` if `rhs == 0` or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i8::MIN + 1).checked_div_euclid(-1), Some(127));"]
#[doc = "assert_eq!(i8::MIN.checked_div_euclid(-1), None);"]
#[doc = "assert_eq!((1i8).checked_div_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) {
None
} else { Some(self.div_euclid(rhs)) }
}
/// Strict Euclidean division. Computes `self.div_euclid(rhs)`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is when one divides `MIN / -1` on a signed type (where
/// [`MIN`](Self::MIN) is the negative minimal value for the type); the result of this is `-MIN`, a positive value
/// that is too large to represent in the type.
///
/// Note that this is equivalent to `div_euclid`: `MIN.div_euclid(-1)` will also panic both
/// in debug and release builds.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i8::MIN + 1).strict_div_euclid(-1), 127);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i8::MIN.strict_div_euclid(-1);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1i8).strict_div_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_div_euclid(self, rhs: Self) -> Self {
self.div_euclid(rhs)
}
/// Checked integer division without remainder. Computes `self / rhs`,
/// returning `None` if `rhs == 0`, the division results in overflow,
/// or `self % rhs != 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!((i8::MIN + 1).checked_div_exact(-1), Some(127));"]
#[doc = "assert_eq!((-5i8).checked_div_exact(2), None);"]
#[doc = "assert_eq!(i8::MIN.checked_div_exact(-1), None);"]
#[doc = "assert_eq!((1i8).checked_div_exact(0), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_exact(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1)))
{
None
} else {
unsafe {
if intrinsics::unlikely(intrinsics::unchecked_rem(self, rhs) != 0)
{
None
} else { Some(intrinsics::exact_div(self, rhs)) }
}
}
}
/// Integer division without remainder. Computes `self / rhs`, returning `None` if `self % rhs != 0`.
///
/// # Panics
///
/// This function will panic if `rhs == 0`.
///
/// ## Overflow behavior
///
/// On overflow, this function will panic if overflow checks are enabled (default in debug
/// mode) and wrap if overflow checks are disabled (default in release mode).
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64i8.div_exact(2), Some(32));"]
#[doc = "assert_eq!(64i8.div_exact(32), Some(2));"]
#[doc = "assert_eq!((i8::MIN + 1).div_exact(-1), Some(127));"]
#[doc = "assert_eq!(65i8.div_exact(2), None);"]
/// ```
/// ```should_panic
/// #![feature(exact_div)]
#[doc = "let _ = 64i8.div_exact(0);"]
/// ```
/// ```should_panic
/// #![feature(exact_div)]
#[doc = "let _ = i8::MIN.div_exact(-1);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn div_exact(self, rhs: Self) -> Option<Self> {
if self % rhs != 0 { None } else { Some(self / rhs) }
}
/// Unchecked integer division without remainder. Computes `self / rhs`.
///
/// # Safety
///
/// This results in undefined behavior when `rhs == 0`, `self % rhs != 0`, or
#[doc = "`self == i8::MIN && rhs == -1`,"]
/// i.e. when [`checked_div_exact`](Self::checked_div_exact) would return `None`.
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_div_exact(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i8, rhs: i8) {
if !(rhs != 0 && lhs % rhs == 0 &&
(lhs != <i8>::MIN || rhs != -1)) {
let msg =
"unsafe precondition(s) violated: i8::unchecked_div_exact cannot overflow, divide by zero, or leave a remainder\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::exact_div(self, rhs) }
}
/// Checked integer remainder. Computes `self % rhs`, returning `None` if
/// `rhs == 0` or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i8.checked_rem(2), Some(1));"]
#[doc = "assert_eq!(5i8.checked_rem(0), None);"]
#[doc = "assert_eq!(i8::MIN.checked_rem(-1), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1)))
{
None
} else { Some(unsafe { intrinsics::unchecked_rem(self, rhs) }) }
}
/// Strict integer remainder. Computes `self % rhs`, panicking if
/// the division results in overflow.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is `x % y` for `MIN / -1` on a
/// signed type (where [`MIN`](Self::MIN) is the negative minimal value), which is invalid due to implementation artifacts.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i8.strict_rem(2), 1);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5i8.strict_rem(0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i8::MIN.strict_rem(-1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_rem(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_rem(rhs);
if b { imp::overflow_panic::rem() } else { a }
}
/// Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
/// if `rhs == 0` or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i8.checked_rem_euclid(2), Some(1));"]
#[doc = "assert_eq!(5i8.checked_rem_euclid(0), None);"]
#[doc = "assert_eq!(i8::MIN.checked_rem_euclid(-1), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) {
None
} else { Some(self.rem_euclid(rhs)) }
}
/// Strict Euclidean remainder. Computes `self.rem_euclid(rhs)`, panicking if
/// the division results in overflow.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is `x % y` for `MIN / -1` on a
/// signed type (where [`MIN`](Self::MIN) is the negative minimal value), which is invalid due to implementation artifacts.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i8.strict_rem_euclid(2), 1);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5i8.strict_rem_euclid(0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i8::MIN.strict_rem_euclid(-1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_rem_euclid(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_rem_euclid(rhs);
if b { imp::overflow_panic::rem() } else { a }
}
/// Checked negation. Computes `-self`, returning `None` if `self == MIN`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i8.checked_neg(), Some(-5));"]
#[doc = "assert_eq!(i8::MIN.checked_neg(), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_neg(self) -> Option<Self> {
let (a, b) = self.overflowing_neg();
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Unchecked negation. Computes `-self`, assuming overflow cannot occur.
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self == i8::MIN`,"]
/// i.e. when [`checked_neg`] would return `None`.
///
#[doc = "[`checked_neg`]: i8::checked_neg"]
#[stable(feature = "unchecked_neg", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_neg", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_neg(self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i8) {
if !!lhs.overflowing_neg().1 {
let msg =
"unsafe precondition(s) violated: i8::unchecked_neg cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self);
}
};
unsafe { intrinsics::unchecked_sub(0, self) }
}
/// Strict negation. Computes `-self`, panicking if `self == MIN`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i8.strict_neg(), -5);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i8::MIN.strict_neg();"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_neg(self) -> Self {
let (a, b) = self.overflowing_neg();
if b { imp::overflow_panic::neg() } else { a }
}
/// Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
/// than or equal to the number of bits in `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1i8.checked_shl(4), Some(0x10));"]
#[doc = "assert_eq!(0x1i8.checked_shl(129), None);"]
#[doc = "assert_eq!(0x10i8.checked_shl(7), Some(0));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
if rhs < Self::BITS {
Some(unsafe { self.unchecked_shl(rhs) })
} else { None }
}
/// Strict shift left. Computes `self << rhs`, panicking if `rhs` is larger
/// than or equal to the number of bits in `self`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1i8.strict_shl(4), 0x10);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0x1i8.strict_shl(129);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_shl(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_shl(rhs);
if b { imp::overflow_panic::shl() } else { a }
}
/// Unchecked shift left. Computes `self << rhs`, assuming that
/// `rhs` is less than the number of bits in `self`.
///
/// # Safety
///
/// This results in undefined behavior if `rhs` is larger than
/// or equal to the number of bits in `self`,
/// i.e. when [`checked_shl`] would return `None`.
///
#[doc = "[`checked_shl`]: i8::checked_shl"]
#[stable(feature = "unchecked_shifts", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_shl(self, rhs: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(rhs: u32) {
if !(rhs < <i8>::BITS) {
let msg =
"unsafe precondition(s) violated: i8::unchecked_shl cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(rhs); }
};
unsafe { intrinsics::unchecked_shl(self, rhs) }
}
/// Unbounded shift left. Computes `self << rhs`, without bounding the value of `rhs`.
///
/// If `rhs` is larger or equal to the number of bits in `self`,
/// the entire value is shifted out, and `0` is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1_i8.unbounded_shl(4), 0x10);"]
#[doc = "assert_eq!(0x1_i8.unbounded_shl(129), 0);"]
#[doc = "assert_eq!(0b101_i8.unbounded_shl(0), 0b101);"]
#[doc = "assert_eq!(0b101_i8.unbounded_shl(1), 0b1010);"]
#[doc = "assert_eq!(0b101_i8.unbounded_shl(2), 0b10100);"]
#[doc = "assert_eq!(42_i8.unbounded_shl(8), 0);"]
#[doc = "assert_eq!(42_i8.unbounded_shl(1).unbounded_shl(7), 0);"]
#[doc = "assert_eq!((-13_i8).unbounded_shl(8), 0);"]
#[doc = "assert_eq!((-13_i8).unbounded_shl(1).unbounded_shl(7), 0);"]
/// ```
#[stable(feature = "unbounded_shifts", since = "1.87.0")]
#[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unbounded_shl(self, rhs: u32) -> i8 {
if rhs < Self::BITS { unsafe { self.unchecked_shl(rhs) } } else { 0 }
}
/// Exact shift left. Computes `self << rhs` as long as it can be reversed losslessly.
///
/// Returns `None` if any bits that would be shifted out differ from the resulting sign bit
/// or if `rhs` >=
#[doc = "`i8::BITS`."]
/// Otherwise, returns `Some(self << rhs)`.
///
/// # Examples
///
/// ```
/// #![feature(exact_bitshifts)]
///
#[doc = "assert_eq!(0x1i8.shl_exact(4), Some(0x10));"]
#[doc = "assert_eq!(0x1i8.shl_exact(i8::BITS - 2), Some(1 << i8::BITS - 2));"]
#[doc = "assert_eq!(0x1i8.shl_exact(i8::BITS - 1), None);"]
#[doc =
"assert_eq!((-0x2i8).shl_exact(i8::BITS - 2), Some(-0x2 << i8::BITS - 2));"]
#[doc = "assert_eq!((-0x2i8).shl_exact(i8::BITS - 1), None);"]
/// ```
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn shl_exact(self, rhs: u32) -> Option<i8> {
if rhs < self.leading_zeros() || rhs < self.leading_ones() {
Some(unsafe { self.unchecked_shl(rhs) })
} else { None }
}
/// Unchecked exact shift left. Computes `self << rhs`, assuming the operation can be
/// losslessly reversed and `rhs` cannot be larger than
#[doc = "`i8::BITS`."]
///
/// # Safety
///
/// This results in undefined behavior when `rhs >= self.leading_zeros() && rhs >=
/// self.leading_ones()` i.e. when
#[doc = "[`i8::shl_exact`]"]
/// would return `None`.
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_shl_exact(self, rhs: u32) -> i8 {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(zeros: u32, ones: u32, rhs: u32) {
if !(rhs < zeros || rhs < ones) {
let msg =
"unsafe precondition(s) violated: i8::unchecked_shl_exact cannot shift out bits that would change the value of the first bit\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_library_ub() {
precondition_check(self.leading_zeros(), self.leading_ones(),
rhs);
}
};
unsafe { self.unchecked_shl(rhs) }
}
/// Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
/// larger than or equal to the number of bits in `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10i8.checked_shr(4), Some(0x1));"]
#[doc = "assert_eq!(0x10i8.checked_shr(128), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
if rhs < Self::BITS {
Some(unsafe { self.unchecked_shr(rhs) })
} else { None }
}
/// Strict shift right. Computes `self >> rhs`, panicking if `rhs` is
/// larger than or equal to the number of bits in `self`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10i8.strict_shr(4), 0x1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0x10i8.strict_shr(128);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_shr(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_shr(rhs);
if b { imp::overflow_panic::shr() } else { a }
}
/// Unchecked shift right. Computes `self >> rhs`, assuming that
/// `rhs` is less than the number of bits in `self`.
///
/// # Safety
///
/// This results in undefined behavior if `rhs` is larger than
/// or equal to the number of bits in `self`,
/// i.e. when [`checked_shr`] would return `None`.
///
#[doc = "[`checked_shr`]: i8::checked_shr"]
#[stable(feature = "unchecked_shifts", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_shr(self, rhs: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(rhs: u32) {
if !(rhs < <i8>::BITS) {
let msg =
"unsafe precondition(s) violated: i8::unchecked_shr cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(rhs); }
};
unsafe { intrinsics::unchecked_shr(self, rhs) }
}
/// Unbounded shift right. Computes `self >> rhs`, without bounding the value of `rhs`.
///
/// If `rhs` is larger or equal to the number of bits in `self`,
/// the entire value is shifted out, which yields `0` for a positive number,
/// and `-1` for a negative number.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10_i8.unbounded_shr(4), 0x1);"]
#[doc = "assert_eq!(0x10_i8.unbounded_shr(129), 0);"]
#[doc = "assert_eq!(i8::MIN.unbounded_shr(129), -1);"]
#[doc = "assert_eq!(0b1010_i8.unbounded_shr(0), 0b1010);"]
#[doc = "assert_eq!(0b1010_i8.unbounded_shr(1), 0b101);"]
#[doc = "assert_eq!(0b1010_i8.unbounded_shr(2), 0b10);"]
#[doc = "assert_eq!(42_i8.unbounded_shr(8), 0);"]
#[doc = "assert_eq!(42_i8.unbounded_shr(1).unbounded_shr(7), 0);"]
#[doc = "assert_eq!((-13_i8).unbounded_shr(8), -1);"]
#[doc = "assert_eq!((-13_i8).unbounded_shr(1).unbounded_shr(7), -1);"]
/// ```
#[stable(feature = "unbounded_shifts", since = "1.87.0")]
#[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unbounded_shr(self, rhs: u32) -> i8 {
if rhs < Self::BITS {
unsafe { self.unchecked_shr(rhs) }
} else { unsafe { self.unchecked_shr(Self::BITS - 1) } }
}
/// Exact shift right. Computes `self >> rhs` as long as it can be reversed losslessly.
///
/// Returns `None` if any non-zero bits would be shifted out or if `rhs` >=
#[doc = "`i8::BITS`."]
/// Otherwise, returns `Some(self >> rhs)`.
///
/// # Examples
///
/// ```
/// #![feature(exact_bitshifts)]
///
#[doc = "assert_eq!(0x10i8.shr_exact(4), Some(0x1));"]
#[doc = "assert_eq!(0x10i8.shr_exact(5), None);"]
/// ```
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn shr_exact(self, rhs: u32) -> Option<i8> {
if rhs <= self.trailing_zeros() && rhs < <i8>::BITS {
Some(unsafe { self.unchecked_shr(rhs) })
} else { None }
}
/// Unchecked exact shift right. Computes `self >> rhs`, assuming the operation can be
/// losslessly reversed and `rhs` cannot be larger than
#[doc = "`i8::BITS`."]
///
/// # Safety
///
/// This results in undefined behavior when `rhs > self.trailing_zeros() || rhs >=
#[doc = "i8::BITS`"]
/// i.e. when
#[doc = "[`i8::shr_exact`]"]
/// would return `None`.
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_shr_exact(self, rhs: u32) -> i8 {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(zeros: u32, bits: u32, rhs: u32) {
if !(rhs <= zeros && rhs < bits) {
let msg =
"unsafe precondition(s) violated: i8::unchecked_shr_exact cannot shift out non-zero bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_library_ub() {
precondition_check(self.trailing_zeros(), <i8>::BITS, rhs);
}
};
unsafe { self.unchecked_shr(rhs) }
}
/// Checked absolute value. Computes `self.abs()`, returning `None` if
/// `self == MIN`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-5i8).checked_abs(), Some(5));"]
#[doc = "assert_eq!(i8::MIN.checked_abs(), None);"]
/// ```
#[stable(feature = "no_panic_abs", since = "1.13.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_abs(self) -> Option<Self> {
if self.is_negative() { self.checked_neg() } else { Some(self) }
}
/// Strict absolute value. Computes `self.abs()`, panicking if
/// `self == MIN`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-5i8).strict_abs(), 5);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i8::MIN.strict_abs();"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_abs(self) -> Self {
if self.is_negative() { self.strict_neg() } else { self }
}
/// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(8i8.checked_pow(2), Some(64));"]
#[doc = "assert_eq!(0_i8.checked_pow(0), Some(1));"]
#[doc = "assert_eq!(i8::MAX.checked_pow(2), None);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
let mut base = self;
let mut acc: Self = 1;
if intrinsics::is_val_statically_known(base) &&
base.unsigned_abs().is_power_of_two() {
let k = base.unsigned_abs().ilog2();
let shift =
match k.checked_mul(exp) { Some(x) => x, None => return None, };
return if base < 0 && (exp % 2) == 1 {
(-1 as Self).shl_exact(shift)
} else { (1 as Self).shl_exact(shift) }
}
if exp == 0 { return Some(1); }
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 {
acc =
match acc.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
exp /= 2;
base =
match base.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
return acc.checked_mul(base);
}
loop {
if (exp & 1) == 1 {
acc =
match acc.checked_mul(base) {
Some(x) => x,
None => return None,
};
if exp == 1 { return Some(acc); }
}
exp /= 2;
base =
match base.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
}
/// Strict exponentiation. Computes `self.pow(exp)`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(8i8.strict_pow(2), 64);"]
#[doc = "assert_eq!(0_i8.strict_pow(0), 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i8::MAX.strict_pow(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) {
Some(x) => x,
None => imp::overflow_panic::pow(),
}
}
/// Returns the integer square root of the number, rounded down.
///
/// This function returns the **principal (non-negative) square root**.
/// For a given number `n`, although both `x` and `-x` satisfy x<sup>2</sup> = n,
/// this function always returns the non-negative value.
///
/// Returns `None` if `self` is negative.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i8.checked_isqrt(), Some(3));"]
/// ```
#[stable(feature = "isqrt", since = "1.84.0")]
#[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_isqrt(self) -> Option<Self> {
if self < 0 {
None
} else {
let result = self.cast_unsigned().isqrt().cast_signed();
unsafe {
const MAX_RESULT: i8 =
<i8>::MAX.cast_unsigned().isqrt().cast_signed();
crate::hint::assert_unchecked(result <= MAX_RESULT);
}
Some(result)
}
}
/// Saturating integer addition. Computes `self + rhs`, saturating at the numeric
/// bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i8.saturating_add(1), 101);"]
#[doc = "assert_eq!(i8::MAX.saturating_add(100), i8::MAX);"]
#[doc = "assert_eq!(i8::MIN.saturating_add(-1), i8::MIN);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_add(self, rhs: Self) -> Self {
intrinsics::saturating_add(self, rhs)
}
/// Saturating addition with an unsigned integer. Computes `self + rhs`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i8.saturating_add_unsigned(2), 3);"]
#[doc = "assert_eq!(i8::MAX.saturating_add_unsigned(100), i8::MAX);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_add_unsigned(self, rhs: u8) -> Self {
match self.checked_add_unsigned(rhs) { Some(x) => x, None => Self::MAX, }
}
/// Saturating integer subtraction. Computes `self - rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i8.saturating_sub(127), -27);"]
#[doc = "assert_eq!(i8::MIN.saturating_sub(100), i8::MIN);"]
#[doc = "assert_eq!(i8::MAX.saturating_sub(-1), i8::MAX);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_sub(self, rhs: Self) -> Self {
intrinsics::saturating_sub(self, rhs)
}
/// Saturating subtraction with an unsigned integer. Computes `self - rhs`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i8.saturating_sub_unsigned(127), -27);"]
#[doc = "assert_eq!(i8::MIN.saturating_sub_unsigned(100), i8::MIN);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_sub_unsigned(self, rhs: u8) -> Self {
match self.checked_sub_unsigned(rhs) { Some(x) => x, None => Self::MIN, }
}
/// Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
/// instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i8.saturating_neg(), -100);"]
#[doc = "assert_eq!((-100i8).saturating_neg(), 100);"]
#[doc = "assert_eq!(i8::MIN.saturating_neg(), i8::MAX);"]
#[doc = "assert_eq!(i8::MAX.saturating_neg(), i8::MIN + 1);"]
/// ```
#[stable(feature = "saturating_neg", since = "1.45.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_neg(self) -> Self {
intrinsics::saturating_sub(0, self)
}
/// Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
/// MIN` instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i8.saturating_abs(), 100);"]
#[doc = "assert_eq!((-100i8).saturating_abs(), 100);"]
#[doc = "assert_eq!(i8::MIN.saturating_abs(), i8::MAX);"]
#[doc = "assert_eq!((i8::MIN + 1).saturating_abs(), i8::MAX);"]
/// ```
#[stable(feature = "saturating_neg", since = "1.45.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_abs(self) -> Self {
if self.is_negative() { self.saturating_neg() } else { self }
}
/// Saturating integer multiplication. Computes `self * rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i8.saturating_mul(12), 120);"]
#[doc = "assert_eq!(i8::MAX.saturating_mul(10), i8::MAX);"]
#[doc = "assert_eq!(i8::MIN.saturating_mul(10), i8::MIN);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_mul(self, rhs: Self) -> Self {
match self.checked_mul(rhs) {
Some(x) => x,
None => if (self < 0) == (rhs < 0) { Self::MAX } else { Self::MIN },
}
}
/// Saturating integer division. Computes `self / rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i8.saturating_div(2), 2);"]
#[doc = "assert_eq!(i8::MAX.saturating_div(-1), i8::MIN + 1);"]
#[doc = "assert_eq!(i8::MIN.saturating_div(-1), i8::MAX);"]
///
/// ```
#[stable(feature = "saturating_div", since = "1.58.0")]
#[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_div(self, rhs: Self) -> Self {
match self.overflowing_div(rhs) {
(result, false) => result,
(_result, true) => Self::MAX,
}
}
/// Saturating integer exponentiation. Computes `self.pow(exp)`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-4i8).saturating_pow(3), -64);"]
#[doc = "assert_eq!(0_i8.saturating_pow(0), 1);"]
#[doc = "assert_eq!(i8::MIN.saturating_pow(2), i8::MAX);"]
#[doc = "assert_eq!(i8::MIN.saturating_pow(3), i8::MIN);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) {
Some(x) => x,
None if self < 0 && exp % 2 == 1 => Self::MIN,
None => Self::MAX,
}
}
/// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
/// boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i8.wrapping_add(27), 127);"]
#[doc = "assert_eq!(i8::MAX.wrapping_add(2), i8::MIN + 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_add(self, rhs: Self) -> Self {
intrinsics::wrapping_add(self, rhs)
}
/// Wrapping (modular) addition with an unsigned integer. Computes
/// `self + rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i8.wrapping_add_unsigned(27), 127);"]
#[doc = "assert_eq!(i8::MAX.wrapping_add_unsigned(2), i8::MIN + 1);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_add_unsigned(self, rhs: u8) -> Self {
self.wrapping_add(rhs as Self)
}
/// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
/// boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0i8.wrapping_sub(127), -127);"]
#[doc = "assert_eq!((-2i8).wrapping_sub(i8::MAX), i8::MAX);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_sub(self, rhs: Self) -> Self {
intrinsics::wrapping_sub(self, rhs)
}
/// Wrapping (modular) subtraction with an unsigned integer. Computes
/// `self - rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0i8.wrapping_sub_unsigned(127), -127);"]
#[doc = "assert_eq!((-2i8).wrapping_sub_unsigned(u8::MAX), -1);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_sub_unsigned(self, rhs: u8) -> Self {
self.wrapping_sub(rhs as Self)
}
/// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
/// the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i8.wrapping_mul(12), 120);"]
/// assert_eq!(11i8.wrapping_mul(12), -124);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_mul(self, rhs: Self) -> Self {
intrinsics::wrapping_mul(self, rhs)
}
/// Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
/// boundary of the type.
///
/// The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
/// [`MIN`](Self::MIN) is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
/// that is too large to represent in the type. In such a case, this function returns [`MIN`](Self::MIN) itself.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i8.wrapping_div(10), 10);"]
/// assert_eq!((-128i8).wrapping_div(-1), -128);
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_div(self, rhs: Self) -> Self {
self.overflowing_div(rhs).0
}
/// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
/// wrapping around at the boundary of the type.
///
/// Wrapping will only occur in `MIN / -1` on a signed type (where [`MIN`](Self::MIN) is the negative minimal value
/// for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
/// type. In this case, this method returns [`MIN`](Self::MIN) itself.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i8.wrapping_div_euclid(10), 10);"]
/// assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
self.overflowing_div_euclid(rhs).0
}
/// Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
/// boundary of the type.
///
/// Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
/// invalid for `MIN / -1` on a signed type (where [`MIN`](Self::MIN) is the negative minimal value). In such a case,
/// this function returns `0`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i8.wrapping_rem(10), 0);"]
/// assert_eq!((-128i8).wrapping_rem(-1), 0);
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_rem(self, rhs: Self) -> Self {
self.overflowing_rem(rhs).0
}
/// Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
/// at the boundary of the type.
///
/// Wrapping will only occur in `MIN % -1` on a signed type (where [`MIN`](Self::MIN) is
/// the negative minimal value for the type). In this case, this method returns 0.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i8.wrapping_rem_euclid(10), 0);"]
/// assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
self.overflowing_rem_euclid(rhs).0
}
/// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
/// of the type.
///
/// The only case where such wrapping can occur is when one negates [`MIN`](Self::MIN) on a signed type (where [`MIN`](Self::MIN)
/// is the negative minimal value for the type); this is a positive value that is too large to represent
/// in the type. In such a case, this function returns [`MIN`](Self::MIN) itself.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i8.wrapping_neg(), -100);"]
#[doc = "assert_eq!((-100i8).wrapping_neg(), 100);"]
#[doc = "assert_eq!(i8::MIN.wrapping_neg(), i8::MIN);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_neg(self) -> Self { (0 as i8).wrapping_sub(self) }
/// Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
/// any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
///
/// Beware that, unlike most other `wrapping_*` methods on integers, this
/// does *not* give the same result as doing the shift in infinite precision
/// then truncating as needed. Instead, the behaviour of this method matches what shift instructions
/// do on many processors, and is what the `<<` operator does when overflow
/// checks are disabled, but numerically it's weird. Consider, instead,
/// using [`Self::unbounded_shl`] which has nicer behaviour.
///
/// Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
/// the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
/// The primitive integer types all implement a [`rotate_left`](Self::rotate_left) function,
/// which may be what you want instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-1_i8).wrapping_shl(7), -128);"]
#[doc = "assert_eq!(42_i8.wrapping_shl(8), 42);"]
#[doc = "assert_eq!(42_i8.wrapping_shl(1).wrapping_shl(7), 0);"]
#[doc = "assert_eq!((-1_i8).wrapping_shl(128), -1);"]
#[doc = "assert_eq!(5_i8.wrapping_shl(1025), 10);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_shl(self, rhs: u32) -> Self {
unsafe { self.unchecked_shl(rhs & (Self::BITS - 1)) }
}
/// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
/// removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
///
/// Beware that, unlike most other `wrapping_*` methods on integers, this
/// does *not* give the same result as doing the shift in infinite precision
/// then truncating as needed. Instead, the behaviour of this method matches what shift instructions
/// do on many processors, and is what the `>>` operator does when overflow
/// checks are disabled, but numerically it's weird. Consider, instead,
/// using [`Self::unbounded_shr`] which has nicer behaviour.
///
/// Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
/// to the range of the type, rather than the bits shifted out of the LHS being returned to the other
/// end. The primitive integer types all implement a [`rotate_right`](Self::rotate_right) function,
/// which may be what you want instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-128_i8).wrapping_shr(7), -1);"]
#[doc = "assert_eq!(42_i8.wrapping_shr(8), 42);"]
#[doc = "assert_eq!(42_i8.wrapping_shr(1).wrapping_shr(7), 0);"]
/// assert_eq!((-128_i16).wrapping_shr(64), -128);
#[doc = "assert_eq!(10_i8.wrapping_shr(1025), 5);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_shr(self, rhs: u32) -> Self {
unsafe { self.unchecked_shr(rhs & (Self::BITS - 1)) }
}
/// Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
/// the boundary of the type.
///
/// The only case where such wrapping can occur is when one takes the absolute value of the negative
/// minimal value for the type; this is a positive value that is too large to represent in the type. In
/// such a case, this function returns [`MIN`](Self::MIN) itself.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i8.wrapping_abs(), 100);"]
#[doc = "assert_eq!((-100i8).wrapping_abs(), 100);"]
#[doc = "assert_eq!(i8::MIN.wrapping_abs(), i8::MIN);"]
/// assert_eq!((-128i8).wrapping_abs() as u8, 128);
/// ```
#[stable(feature = "no_panic_abs", since = "1.13.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[allow(unused_attributes)]
#[inline]
pub const fn wrapping_abs(self) -> Self {
if self.is_negative() { self.wrapping_neg() } else { self }
}
/// Computes the absolute value of `self` without any wrapping
/// or panicking.
///
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i8.unsigned_abs(), 100u8);"]
#[doc = "assert_eq!((-100i8).unsigned_abs(), 100u8);"]
/// assert_eq!((-128i8).unsigned_abs(), 128u8);
/// ```
#[stable(feature = "unsigned_abs", since = "1.51.0")]
#[rustc_const_stable(feature = "unsigned_abs", since = "1.51.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unsigned_abs(self) -> u8 { self.wrapping_abs() as u8 }
/// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3i8.wrapping_pow(4), 81);"]
/// assert_eq!(3i8.wrapping_pow(5), -13);
/// assert_eq!(3i8.wrapping_pow(6), -39);
#[doc = "assert_eq!(0_i8.wrapping_pow(0), 1);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_pow(self, exp: u32) -> Self {
let (a, _) = self.overflowing_pow(exp);
a
}
/// Calculates `self` + `rhs`.
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would have
/// occurred then the wrapped value is returned (negative if overflowed
/// above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i8.overflowing_add(2), (7, false));"]
#[doc = "assert_eq!(i8::MAX.overflowing_add(1), (i8::MIN, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::add_with_overflow(self as i8, rhs as i8);
(a as Self, b)
}
/// Calculates `self` + `rhs` + `carry` and checks for overflow.
///
/// Performs "ternary addition" of two integer operands and a carry-in
/// bit, and returns a tuple of the sum along with a boolean indicating
/// whether an arithmetic overflow would occur. On overflow, the wrapped
/// value is returned.
///
/// This allows chaining together multiple additions to create a wider
/// addition, and can be useful for bignum addition. This method should
/// only be used for the most significant word; for the less significant
/// words the unsigned method
#[doc = "[`u8::carrying_add`]"]
/// should be used.
///
/// The output boolean returned by this method is *not* a carry flag,
/// and should *not* be added to a more significant word.
///
/// If overflow occurred, the wrapped value is returned (negative if overflowed
/// above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
///
/// If the input carry is false, this method is equivalent to
/// [`overflowing_add`](Self::overflowing_add).
///
/// # Examples
///
/// ```
/// #![feature(signed_bigint_helpers)]
/// // Only the most significant word is signed.
/// //
#[doc = "// 10 MAX (a = 10 \u{d7} 2^8 + 2^8 - 1)"]
#[doc = "// + -5 9 (b = -5 \u{d7} 2^8 + 9)"]
/// // ---------
#[doc = "// 6 8 (sum = 6 \u{d7} 2^8 + 8)"]
///
#[doc = "let (a1, a0): (i8, u8) = (10, u8::MAX);"]
#[doc = "let (b1, b0): (i8, u8) = (-5, 9);"]
/// let carry0 = false;
///
#[doc = "// u8::carrying_add for the less significant words"]
/// let (sum0, carry1) = a0.carrying_add(b0, carry0);
/// assert_eq!(carry1, true);
///
#[doc = "// i8::carrying_add for the most significant word"]
/// let (sum1, overflow) = a1.carrying_add(b1, carry1);
/// assert_eq!(overflow, false);
///
/// assert_eq!((sum1, sum0), (6, 8));
/// ```
#[unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
let (a, b) = self.overflowing_add(rhs);
let (c, d) = a.overflowing_add(carry as i8);
(c, b != d)
}
/// Calculates `self` + `rhs` with an unsigned `rhs`.
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i8.overflowing_add_unsigned(2), (3, false));"]
#[doc =
"assert_eq!((i8::MIN).overflowing_add_unsigned(u8::MAX), (i8::MAX, false));"]
#[doc =
"assert_eq!((i8::MAX - 2).overflowing_add_unsigned(3), (i8::MIN, true));"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_add_unsigned(self, rhs: u8) -> (Self, bool) {
let rhs = rhs as Self;
let (res, overflowed) = self.overflowing_add(rhs);
(res, overflowed ^ (rhs < 0))
}
/// Calculates `self` - `rhs`.
///
/// Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
/// would occur. If an overflow would have occurred then the wrapped value is returned
/// (negative if overflowed above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i8.overflowing_sub(2), (3, false));"]
#[doc = "assert_eq!(i8::MIN.overflowing_sub(1), (i8::MAX, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::sub_with_overflow(self as i8, rhs as i8);
(a as Self, b)
}
/// Calculates `self` − `rhs` − `borrow` and checks for
/// overflow.
///
/// Performs "ternary subtraction" by subtracting both an integer
/// operand and a borrow-in bit from `self`, and returns a tuple of the
/// difference along with a boolean indicating whether an arithmetic
/// overflow would occur. On overflow, the wrapped value is returned.
///
/// This allows chaining together multiple subtractions to create a
/// wider subtraction, and can be useful for bignum subtraction. This
/// method should only be used for the most significant word; for the
/// less significant words the unsigned method
#[doc = "[`u8::borrowing_sub`]"]
/// should be used.
///
/// The output boolean returned by this method is *not* a borrow flag,
/// and should *not* be subtracted from a more significant word.
///
/// If overflow occurred, the wrapped value is returned (negative if overflowed
/// above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
///
/// If the input borrow is false, this method is equivalent to
/// [`overflowing_sub`](Self::overflowing_sub).
///
/// # Examples
///
/// ```
/// #![feature(signed_bigint_helpers)]
/// // Only the most significant word is signed.
/// //
#[doc = "// 6 8 (a = 6 \u{d7} 2^8 + 8)"]
#[doc = "// - -5 9 (b = -5 \u{d7} 2^8 + 9)"]
/// // ---------
#[doc = "// 10 MAX (diff = 10 \u{d7} 2^8 + 2^8 - 1)"]
///
#[doc = "let (a1, a0): (i8, u8) = (6, 8);"]
#[doc = "let (b1, b0): (i8, u8) = (-5, 9);"]
/// let borrow0 = false;
///
#[doc = "// u8::borrowing_sub for the less significant words"]
/// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);
/// assert_eq!(borrow1, true);
///
#[doc = "// i8::borrowing_sub for the most significant word"]
/// let (diff1, overflow) = a1.borrowing_sub(b1, borrow1);
/// assert_eq!(overflow, false);
///
#[doc = "assert_eq!((diff1, diff0), (10, u8::MAX));"]
/// ```
#[unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
let (a, b) = self.overflowing_sub(rhs);
let (c, d) = a.overflowing_sub(borrow as i8);
(c, b != d)
}
/// Calculates `self` - `rhs` with an unsigned `rhs`.
///
/// Returns a tuple of the subtraction along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i8.overflowing_sub_unsigned(2), (-1, false));"]
#[doc =
"assert_eq!((i8::MAX).overflowing_sub_unsigned(u8::MAX), (i8::MIN, false));"]
#[doc =
"assert_eq!((i8::MIN + 2).overflowing_sub_unsigned(3), (i8::MAX, true));"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_sub_unsigned(self, rhs: u8) -> (Self, bool) {
let rhs = rhs as Self;
let (res, overflowed) = self.overflowing_sub(rhs);
(res, overflowed ^ (rhs < 0))
}
/// Calculates the multiplication of `self` and `rhs`.
///
/// Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
/// would occur. If an overflow would have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i8.overflowing_mul(2), (10, false));"]
/// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::mul_with_overflow(self as i8, rhs as i8);
(a as Self, b)
}
/// Calculates the "full multiplication" `self * rhs + carry`
/// without the possibility to overflow.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// Performs "long multiplication" which takes in an extra amount to add, and may return an
/// additional amount of overflow. This allows for chaining together multiple
/// multiplications to create "big integers" which represent larger values.
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why [`i32`] is used.
///
/// ```
/// #![feature(signed_bigint_helpers)]
/// assert_eq!(5i32.carrying_mul(-2, 0), (4294967286, -1));
/// assert_eq!(5i32.carrying_mul(-2, 10), (0, 0));
/// assert_eq!(1_000_000_000i32.carrying_mul(-10, 0), (2884901888, -3));
/// assert_eq!(1_000_000_000i32.carrying_mul(-10, 10), (2884901898, -3));
#[doc =
"assert_eq!(i8::MAX.carrying_mul(i8::MAX, i8::MAX), (i8::MAX.unsigned_abs() + 1, i8::MAX / 2));"]
/// ```
#[unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[rustc_const_unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_mul(self, rhs: Self, carry: Self) -> (u8, Self) {
Self::carrying_mul_add(self, rhs, carry, 0)
}
/// Calculates the "full multiplication" `self * rhs + carry + add`
/// without the possibility to overflow.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// Performs "long multiplication" which takes in an extra amount to add, and may return an
/// additional amount of overflow. This allows for chaining together multiple
/// multiplications to create "big integers" which represent larger values.
///
/// If you only need one `carry`, then you can use [`Self::carrying_mul`] instead.
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `i32` is used.
///
/// ```
/// #![feature(signed_bigint_helpers)]
/// assert_eq!(5i32.carrying_mul_add(-2, 0, 0), (4294967286, -1));
/// assert_eq!(5i32.carrying_mul_add(-2, 10, 10), (10, 0));
/// assert_eq!(1_000_000_000i32.carrying_mul_add(-10, 0, 0), (2884901888, -3));
/// assert_eq!(1_000_000_000i32.carrying_mul_add(-10, 10, 10), (2884901908, -3));
#[doc =
"assert_eq!(i8::MAX.carrying_mul_add(i8::MAX, i8::MAX, i8::MAX), (u8::MAX, i8::MAX / 2));"]
/// ```
#[unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[rustc_const_unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_mul_add(self, rhs: Self, carry: Self, add: Self)
-> (u8, Self) {
intrinsics::carrying_mul_add(self, rhs, carry, add)
}
/// Calculates the divisor when `self` is divided by `rhs`.
///
/// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
/// occur. If an overflow would occur then self is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i8.overflowing_div(2), (2, false));"]
#[doc = "assert_eq!(i8::MIN.overflowing_div(-1), (i8::MIN, true));"]
/// ```
#[inline]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_overflowing_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
if intrinsics::unlikely((self == Self::MIN) & (rhs == -1)) {
(self, true)
} else { (self / rhs, false) }
}
/// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
///
/// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
/// occur. If an overflow would occur then `self` is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i8.overflowing_div_euclid(2), (2, false));"]
#[doc = "assert_eq!(i8::MIN.overflowing_div_euclid(-1), (i8::MIN, true));"]
/// ```
#[inline]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
if intrinsics::unlikely((self == Self::MIN) & (rhs == -1)) {
(self, true)
} else { (self.div_euclid(rhs), false) }
}
/// Calculates the remainder when `self` is divided by `rhs`.
///
/// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
/// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i8.overflowing_rem(2), (1, false));"]
#[doc = "assert_eq!(i8::MIN.overflowing_rem(-1), (0, true));"]
/// ```
#[inline]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_overflowing_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
if intrinsics::unlikely(rhs == -1) {
(0, self == Self::MIN)
} else { (self % rhs, false) }
}
/// Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
///
/// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
/// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i8.overflowing_rem_euclid(2), (1, false));"]
#[doc = "assert_eq!(i8::MIN.overflowing_rem_euclid(-1), (0, true));"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
if intrinsics::unlikely(rhs == -1) {
(0, self == Self::MIN)
} else { (self.rem_euclid(rhs), false) }
}
/// Negates self, overflowing if this is equal to the minimum value.
///
/// Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
/// happened. If `self` is the minimum value (e.g., [`i32::MIN`] for values of type [`i32`]), then the
/// minimum value will be returned again and `true` will be returned for an overflow happening.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2i8.overflowing_neg(), (-2, false));"]
#[doc = "assert_eq!(i8::MIN.overflowing_neg(), (i8::MIN, true));"]
/// ```
#[inline]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[allow(unused_attributes)]
pub const fn overflowing_neg(self) -> (Self, bool) {
if intrinsics::unlikely(self == Self::MIN) {
(Self::MIN, true)
} else { (-self, false) }
}
/// Shifts self left by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
/// value was larger than or equal to the number of bits. If the shift value is too large, then value is
/// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1i8.overflowing_shl(4), (0x10, false));"]
/// assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));
#[doc = "assert_eq!(0x10i8.overflowing_shl(7), (0, false));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shl(rhs), rhs >= Self::BITS)
}
/// Shifts self right by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
/// value was larger than or equal to the number of bits. If the shift value is too large, then value is
/// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10i8.overflowing_shr(4), (0x1, false));"]
/// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shr(rhs), rhs >= Self::BITS)
}
/// Computes the absolute value of `self`.
///
/// Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
/// happened. If self is the minimum value
#[doc = "(e.g., [`i8::MIN`] for values of type [`i8`]),"]
/// then the minimum value will be returned again and true will be returned
/// for an overflow happening.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i8.overflowing_abs(), (10, false));"]
#[doc = "assert_eq!((-10i8).overflowing_abs(), (10, false));"]
#[doc = "assert_eq!((i8::MIN).overflowing_abs(), (i8::MIN, true));"]
/// ```
#[stable(feature = "no_panic_abs", since = "1.13.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_abs(self) -> (Self, bool) {
(self.wrapping_abs(), self == Self::MIN)
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// Returns a tuple of the exponentiation along with a bool indicating
/// whether an overflow happened.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3i8.overflowing_pow(4), (81, false));"]
#[doc = "assert_eq!(0_i8.overflowing_pow(0), (1, false));"]
/// assert_eq!(3i8.overflowing_pow(5), (-13, true));
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
let mut base = self;
let mut acc: Self = 1;
let mut overflow = false;
let mut tmp_overflow;
if intrinsics::is_val_statically_known(base) &&
base.unsigned_abs().is_power_of_two() {
let k = base.unsigned_abs().ilog2();
let Some(shift) = k.checked_mul(exp) else { return (0, true) };
let base: Self = if base < 0 && (exp % 2) != 0 { -1 } else { 1 };
return (base.unbounded_shl(shift), base.shl_exact(shift).is_none());
}
if exp == 0 { return (1, false); }
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 {
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
}
exp /= 2;
(base, tmp_overflow) = base.overflowing_mul(base);
overflow |= tmp_overflow;
}
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
return (acc, overflow);
}
loop {
if (exp & 1) == 1 {
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
if exp == 1 { return (acc, overflow); }
}
exp /= 2;
(base, tmp_overflow) = base.overflowing_mul(base);
overflow |= tmp_overflow;
}
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// # Examples
///
/// ```
#[doc = "let x: i8 = 2; // or any other integer type"]
///
/// assert_eq!(x.pow(5), 32);
#[doc = "assert_eq!(0_i8.pow(0), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn pow(self, exp: u32) -> Self {
if intrinsics::overflow_checks() {
self.strict_pow(exp)
} else { self.wrapping_pow(exp) }
}
/// Returns the integer square root of the number, rounded down.
///
/// This function returns the **principal (non-negative) square root**.
/// For a given number `n`, although both `x` and `-x` satisfy x<sup>2</sup> = n,
/// this function always returns the non-negative value.
///
/// # Panics
///
/// This function will panic if `self` is negative.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i8.isqrt(), 3);"]
/// ```
#[stable(feature = "isqrt", since = "1.84.0")]
#[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn isqrt(self) -> Self {
match self.checked_isqrt() {
Some(sqrt) => sqrt,
None => imp::int_sqrt::panic_for_negative_argument(),
}
}
/// Calculates the quotient of Euclidean division of `self` by `rhs`.
///
/// This computes the integer `q` such that `self = q * rhs + r`, with
/// `r = self.rem_euclid(rhs)` and `0 <= r < abs(rhs)`.
///
/// In other words, the result is `self / rhs` rounded to the integer `q`
/// such that `self >= q * rhs`.
/// If `self > 0`, this is equal to rounding towards zero (the default in Rust);
/// if `self < 0`, this is equal to rounding away from zero (towards +/- infinity).
/// If `rhs > 0`, this is equal to rounding towards -infinity;
/// if `rhs < 0`, this is equal to rounding towards +infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero or if `self` is [`Self::MIN`]
/// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
///
/// # Examples
///
/// ```
#[doc = "let a: i8 = 7; // or any other integer type"]
/// let b = 4;
///
/// assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
/// assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
/// assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
/// assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_euclid(self, rhs: Self) -> Self {
let q = self / rhs;
if self % rhs < 0 { return if rhs > 0 { q - 1 } else { q + 1 } }
q
}
/// Calculates the least nonnegative remainder of `self` when
/// divided by `rhs`.
///
/// This is done as if by the Euclidean division algorithm -- given
/// `r = self.rem_euclid(rhs)`, the result satisfies
/// `self = rhs * self.div_euclid(rhs) + r` and `0 <= r < abs(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero or if `self` is [`Self::MIN`] and
/// `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
///
/// # Examples
///
/// ```
#[doc = "let a: i8 = 7; // or any other integer type"]
/// let b = 4;
///
/// assert_eq!(a.rem_euclid(b), 3);
/// assert_eq!((-a).rem_euclid(b), 1);
/// assert_eq!(a.rem_euclid(-b), 3);
/// assert_eq!((-a).rem_euclid(-b), 1);
/// ```
///
/// This will panic:
/// ```should_panic
#[doc = "let _ = i8::MIN.rem_euclid(-1);"]
/// ```
#[doc(alias = "modulo", alias = "mod")]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn rem_euclid(self, rhs: Self) -> Self {
let r = self % rhs;
if r < 0 { r.wrapping_add(rhs.wrapping_abs()) } else { r }
}
/// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero or if `self` is [`Self::MIN`]
/// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "let a: i8 = 8;"]
/// let b = 3;
///
/// assert_eq!(a.div_floor(b), 2);
/// assert_eq!(a.div_floor(-b), -3);
/// assert_eq!((-a).div_floor(b), -3);
/// assert_eq!((-a).div_floor(-b), 2);
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_floor(self, rhs: Self) -> Self {
let d = self / rhs;
let r = self % rhs;
let correction = (self ^ rhs) >> (Self::BITS - 1);
if r != 0 { d + correction } else { d }
}
/// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero or if `self` is [`Self::MIN`]
/// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "let a: i8 = 8;"]
/// let b = 3;
///
/// assert_eq!(a.div_ceil(b), 3);
/// assert_eq!(a.div_ceil(-b), -2);
/// assert_eq!((-a).div_ceil(b), -2);
/// assert_eq!((-a).div_ceil(-b), 3);
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_ceil(self, rhs: Self) -> Self {
let d = self / rhs;
let r = self % rhs;
let correction = 1 + ((self ^ rhs) >> (Self::BITS - 1));
if r != 0 { d + correction } else { d }
}
/// If `rhs` is positive, calculates the smallest value greater than or
/// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
/// calculates the largest value less than or equal to `self` that is a
/// multiple of `rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// On overflow, this function will panic if overflow checks are enabled (default in debug
/// mode) and wrap if overflow checks are disabled (default in release mode).
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "assert_eq!(16_i8.next_multiple_of(8), 16);"]
#[doc = "assert_eq!(23_i8.next_multiple_of(8), 24);"]
#[doc = "assert_eq!(16_i8.next_multiple_of(-8), 16);"]
#[doc = "assert_eq!(23_i8.next_multiple_of(-8), 16);"]
#[doc = "assert_eq!((-16_i8).next_multiple_of(8), -16);"]
#[doc = "assert_eq!((-23_i8).next_multiple_of(8), -16);"]
#[doc = "assert_eq!((-16_i8).next_multiple_of(-8), -16);"]
#[doc = "assert_eq!((-23_i8).next_multiple_of(-8), -24);"]
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_multiple_of(self, rhs: Self) -> Self {
if rhs == -1 { return self; }
let r = self % rhs;
let m =
if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) { r + rhs } else { r };
if m == 0 { self } else { self + (rhs - m) }
}
/// If `rhs` is positive, calculates the smallest value greater than or
/// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
/// calculates the largest value less than or equal to `self` that is a
/// multiple of `rhs`. Returns `None` if `rhs` is zero or the operation
/// would result in overflow.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "assert_eq!(16_i8.checked_next_multiple_of(8), Some(16));"]
#[doc = "assert_eq!(23_i8.checked_next_multiple_of(8), Some(24));"]
#[doc = "assert_eq!(16_i8.checked_next_multiple_of(-8), Some(16));"]
#[doc = "assert_eq!(23_i8.checked_next_multiple_of(-8), Some(16));"]
#[doc = "assert_eq!((-16_i8).checked_next_multiple_of(8), Some(-16));"]
#[doc = "assert_eq!((-23_i8).checked_next_multiple_of(8), Some(-16));"]
#[doc = "assert_eq!((-16_i8).checked_next_multiple_of(-8), Some(-16));"]
#[doc = "assert_eq!((-23_i8).checked_next_multiple_of(-8), Some(-24));"]
#[doc = "assert_eq!(1_i8.checked_next_multiple_of(0), None);"]
#[doc = "assert_eq!(i8::MAX.checked_next_multiple_of(2), None);"]
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
if rhs == -1 { return Some(self); }
let r =
match self.checked_rem(rhs) { Some(x) => x, None => return None, };
let m =
if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) { r + rhs } else { r };
if m == 0 { Some(self) } else { self.checked_add(rhs - m) }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// This method might not be optimized owing to implementation details;
/// [`ilog2`][Self::ilog2] can produce results more efficiently for base 2,
/// and [`ilog10`](Self::ilog10) can produce results more efficiently for base 10.
///
/// # Panics
///
/// This function will panic if `self` is less than or equal to zero,
/// or if `base` is less than 2.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i8.ilog(5), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog(self, base: Self) -> u32 {
if !(base >= 2) {
{
crate::panicking::panic_fmt(format_args!("base of integer logarithm must be at least 2"));
}
};
if let Some(log) = self.checked_ilog(base) {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the base 2 logarithm of the number, rounded down.
///
/// # Panics
///
/// This function will panic if `self` is less than or equal to zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2i8.ilog2(), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog2(self) -> u32 {
if let Some(log) = self.checked_ilog2() {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// # Panics
///
/// This function will panic if `self` is less than or equal to zero.
///
/// # Example
///
/// ```
#[doc = "assert_eq!(10i8.ilog10(), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog10(self) -> u32 {
if let Some(log) = self.checked_ilog10() {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// Returns `None` if the number is negative or zero, or if the base is not at least 2.
///
/// This method might not be optimized owing to implementation details;
/// `checked_ilog2` can produce results more efficiently for base 2, and
/// `checked_ilog10` can produce results more efficiently for base 10.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i8.checked_ilog(5), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog(self, base: Self) -> Option<u32> {
if self <= 0 || base <= 1 {
None
} else { (self as u8).checked_ilog(base as u8) }
}
/// Returns the base 2 logarithm of the number, rounded down.
///
/// Returns `None` if the number is negative or zero.
///
/// Note that for non-negative numbers, this is equivalent to
/// [`highest_one`](Self::highest_one).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2i8.checked_ilog2(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog2(self) -> Option<u32> {
if self <= 0 {
None
} else {
let log =
(Self::BITS - 1) -
unsafe { intrinsics::ctlz_nonzero(self) as u32 };
Some(log)
}
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// Returns `None` if the number is negative or zero.
///
/// # Example
///
/// ```
#[doc = "assert_eq!(10i8.checked_ilog10(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog10(self) -> Option<u32> {
imp::int_log10::i8(self as i8)
}
/// Computes the absolute value of `self`.
///
/// # Overflow behavior
///
/// The absolute value of
#[doc = "`i8::MIN`"]
/// cannot be represented as an
#[doc = "`i8`,"]
/// and attempting to calculate it will cause an overflow. This means
/// that code in debug mode will trigger a panic on this case and
/// optimized code will return
#[doc = "`i8::MIN`"]
/// without a panic. If you do not want this behavior, consider
/// using [`unsigned_abs`](Self::unsigned_abs) instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i8.abs(), 10);"]
#[doc = "assert_eq!((-10i8).abs(), 10);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[allow(unused_attributes)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn abs(self) -> Self {
if self.is_negative() { -self } else { self }
}
/// Computes the absolute difference between `self` and `other`.
///
/// This function always returns the correct answer without overflow or
/// panics by returning an unsigned integer.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i8.abs_diff(80), 20u8);"]
#[doc = "assert_eq!(100i8.abs_diff(110), 10u8);"]
#[doc = "assert_eq!((-100i8).abs_diff(80), 180u8);"]
#[doc = "assert_eq!((-100i8).abs_diff(-120), 20u8);"]
#[doc = "assert_eq!(i8::MIN.abs_diff(i8::MAX), u8::MAX);"]
/// ```
#[stable(feature = "int_abs_diff", since = "1.60.0")]
#[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn abs_diff(self, other: Self) -> u8 {
if self < other {
(other as u8).wrapping_sub(self as u8)
} else { (self as u8).wrapping_sub(other as u8) }
}
/// Returns a number representing sign of `self`.
///
/// - `0` if the number is zero
/// - `1` if the number is positive
/// - `-1` if the number is negative
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i8.signum(), 1);"]
#[doc = "assert_eq!(0i8.signum(), 0);"]
#[doc = "assert_eq!((-10i8).signum(), -1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_sign", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn signum(self) -> Self {
crate::intrinsics::three_way_compare(self, 0) as Self
}
/// Returns `true` if `self` is positive and `false` if the number is zero or
/// negative.
///
/// # Examples
///
/// ```
#[doc = "assert!(10i8.is_positive());"]
#[doc = "assert!(!(-10i8).is_positive());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[inline(always)]
pub const fn is_positive(self) -> bool { self > 0 }
/// Returns `true` if `self` is negative and `false` if the number is zero or
/// positive.
///
/// # Examples
///
/// ```
#[doc = "assert!((-10i8).is_negative());"]
#[doc = "assert!(!10i8.is_negative());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[inline(always)]
pub const fn is_negative(self) -> bool { self < 0 }
/// Returns the memory representation of this integer as a byte array in
/// big-endian (network) byte order.
///
#[doc =
"
**Note**: This function is meaningless on `i8`. Byte order does not exist as a
concept for byte-sized integers. This function is only provided in symmetry
with larger integer types. You can cast from and to `u8` using
[`cast_signed`](u8::cast_signed) and [`cast_unsigned`](Self::cast_unsigned).
"]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12i8.to_be_bytes();"]
#[doc = "assert_eq!(bytes, [0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
self.to_be().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// little-endian byte order.
///
#[doc =
"
**Note**: This function is meaningless on `i8`. Byte order does not exist as a
concept for byte-sized integers. This function is only provided in symmetry
with larger integer types. You can cast from and to `u8` using
[`cast_signed`](u8::cast_signed) and [`cast_unsigned`](Self::cast_unsigned).
"]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12i8.to_le_bytes();"]
#[doc = "assert_eq!(bytes, [0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
self.to_le().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code
/// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
/// instead.
///
#[doc =
"
**Note**: This function is meaningless on `i8`. Byte order does not exist as a
concept for byte-sized integers. This function is only provided in symmetry
with larger integer types. You can cast from and to `u8` using
[`cast_signed`](u8::cast_signed) and [`cast_unsigned`](Self::cast_unsigned).
"]
///
/// [`to_be_bytes`]: Self::to_be_bytes
/// [`to_le_bytes`]: Self::to_le_bytes
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12i8.to_ne_bytes();"]
/// assert_eq!(
/// bytes,
/// if cfg!(target_endian = "big") {
#[doc = " [0x12]"]
/// } else {
#[doc = " [0x12]"]
/// }
/// );
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
unsafe { mem::transmute(self) }
}
/// Creates an integer value from its representation as a byte array in
/// big endian.
///
#[doc =
"
**Note**: This function is meaningless on `i8`. Byte order does not exist as a
concept for byte-sized integers. This function is only provided in symmetry
with larger integer types. You can cast from and to `u8` using
[`cast_signed`](u8::cast_signed) and [`cast_unsigned`](Self::cast_unsigned).
"]
///
/// # Examples
///
/// ```
#[doc = "let value = i8::from_be_bytes([0x12]);"]
#[doc = "assert_eq!(value, 0x12);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_be_i8(input: &mut &[u8]) -> i8 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i8>());"]
/// *input = rest;
#[doc = " i8::from_be_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_be(Self::from_ne_bytes(bytes))
}
/// Creates an integer value from its representation as a byte array in
/// little endian.
///
#[doc =
"
**Note**: This function is meaningless on `i8`. Byte order does not exist as a
concept for byte-sized integers. This function is only provided in symmetry
with larger integer types. You can cast from and to `u8` using
[`cast_signed`](u8::cast_signed) and [`cast_unsigned`](Self::cast_unsigned).
"]
///
/// # Examples
///
/// ```
#[doc = "let value = i8::from_le_bytes([0x12]);"]
#[doc = "assert_eq!(value, 0x12);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_le_i8(input: &mut &[u8]) -> i8 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i8>());"]
/// *input = rest;
#[doc = " i8::from_le_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_le(Self::from_ne_bytes(bytes))
}
/// Creates an integer value from its memory representation as a byte
/// array in native endianness.
///
/// As the target platform's native endianness is used, portable code
/// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
/// appropriate instead.
///
/// [`from_be_bytes`]: Self::from_be_bytes
/// [`from_le_bytes`]: Self::from_le_bytes
///
#[doc =
"
**Note**: This function is meaningless on `i8`. Byte order does not exist as a
concept for byte-sized integers. This function is only provided in symmetry
with larger integer types. You can cast from and to `u8` using
[`cast_signed`](u8::cast_signed) and [`cast_unsigned`](Self::cast_unsigned).
"]
///
/// # Examples
///
/// ```
#[doc = "let value = i8::from_ne_bytes(if cfg!(target_endian = \"big\") {"]
#[doc = " [0x12]"]
/// } else {
#[doc = " [0x12]"]
/// });
#[doc = "assert_eq!(value, 0x12);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_ne_i8(input: &mut &[u8]) -> i8 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i8>());"]
/// *input = rest;
#[doc = " i8::from_ne_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use]
#[inline]
pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
unsafe { mem::transmute(bytes) }
}
/// New code should prefer to use
#[doc = "[`i8::MIN`] instead."]
///
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MIN` associated constant on this type")]
#[rustc_diagnostic_item = "i8_legacy_fn_min_value"]
pub const fn min_value() -> Self { Self::MIN }
/// New code should prefer to use
#[doc = "[`i8::MAX`] instead."]
///
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MAX` associated constant on this type")]
#[rustc_diagnostic_item = "i8_legacy_fn_max_value"]
pub const fn max_value() -> Self { Self::MAX }
/// Clamps this number to a symmetric range centred around zero.
///
/// The method clamps the number's magnitude (absolute value) to be at most `limit`.
///
/// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
/// explicit about the intent.
///
/// # Examples
///
/// ```
/// #![feature(clamp_magnitude)]
#[doc = "assert_eq!(120i8.clamp_magnitude(100), 100);"]
#[doc = "assert_eq!(-120i8.clamp_magnitude(100), -100);"]
#[doc = "assert_eq!(80i8.clamp_magnitude(100), 80);"]
#[doc = "assert_eq!(-80i8.clamp_magnitude(100), -80);"]
/// ```
#[must_use =
"this returns the clamped value and does not modify the original"]
#[unstable(feature = "clamp_magnitude", issue = "148519")]
#[inline]
pub fn clamp_magnitude(self, limit: u8) -> Self {
if let Ok(limit) = core::convert::TryInto::<i8>::try_into(limit) {
self.clamp(-limit, limit)
} else { self }
}
/// Truncate an integer to an integer of the same size or smaller, preserving the least
/// significant bits.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i8, 120i8.truncate());"]
#[doc = "assert_eq!(-120i8, (-120i8).truncate());"]
/// assert_eq!(120i8, 376i32.truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
/// instead of truncating.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i8, 120i8.saturating_truncate());"]
#[doc = "assert_eq!(-120i8, (-120i8).saturating_truncate());"]
/// assert_eq!(127i8, 376i32.saturating_truncate());
/// assert_eq!(-128i8, (-1000i32).saturating_truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn saturating_truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_saturating_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
/// is outside the bounds of the smaller type.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(Some(120i8), 120i8.checked_truncate());"]
#[doc = "assert_eq!(Some(-120i8), (-120i8).checked_truncate());"]
/// assert_eq!(None, 376i32.checked_truncate::<i8>());
/// assert_eq!(None, (-1000i32).checked_truncate::<i8>());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn checked_truncate<Target>(self) -> Option<Target> where
Self: [const] traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_checked_truncate(self)
}
/// Widen to an integer of the same size or larger, preserving its value.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i128, 120i8.widen());"]
#[doc = "assert_eq!(-120i128, (-120i8).widen());"]
/// ```
#[must_use =
"this returns the widened value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn widen<Target>(self) -> Target where Self: [const]
traits::WidenTarget<Target> {
traits::WidenTarget::internal_widen(self)
}
/// Converts `self` to the target integer type, saturating at the numeric
/// bounds instead of overflowing.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(i8::MAX, i8::MAX.saturating_cast());"]
#[doc = "assert_eq!(i8::MIN, i8::MIN.saturating_cast());"]
#[doc = "assert_eq!(42u8, 42i8.saturating_cast());"]
#[doc = "assert_eq!(0u8, (-42i8).saturating_cast());"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn saturating_cast<T: [const] BoundedCastFromInt<Self>>(self) -> T {
T::saturating_cast_from(self)
}
/// Converts `self` to the target integer type, wrapping around at the
/// boundary of the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(i8::MAX as i8, i8::MAX.wrapping_cast());"]
#[doc = "assert_eq!(i8::MIN as i8, i8::MIN.wrapping_cast());"]
#[doc = "assert_eq!(42u8, 42i8.wrapping_cast());"]
#[doc = "assert_eq!(u8::MAX - 41, (-42i8).wrapping_cast());"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn wrapping_cast<T: [const] BoundedCastFromInt<Self>>(self) -> T {
T::wrapping_cast_from(self)
}
/// Converts `self` to the target integer type, returning `None` if the value
/// is not representable by the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(Some(42u8), 42i8.checked_cast());"]
#[doc = "assert_eq!((-42i8).checked_cast::<u8>(), None);"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn checked_cast<T: [const] CheckedCastFromInt<Self>>(self)
-> Option<T> {
T::checked_cast_from(self)
}
/// Converts `self` to the target integer type, panicking if the value
/// is not representable by the target type.
///
/// # Panics
///
/// This function will panic if the value is not representable by the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(42u8, 42i8.strict_cast());"]
/// ```
///
/// The following will panic:
///
/// ```should_panic
/// #![feature(integer_casts)]
#[doc = "let _ = (-42i8).strict_cast::<u8>();"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
#[track_caller]
pub const fn strict_cast<T: [const] CheckedCastFromInt<Self>>(self) -> T {
T::strict_cast_from(self)
}
/// Converts `self` to the target integer type, assuming the value is
/// representable by the target type.
///
/// # Safety
///
/// This results in undefined behavior if the integer value of `self` is bigger than `T::MAX`,
/// or smaller than `T::MIN`, where `T` is the target type.
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const unsafe fn unchecked_cast<T: [const] CheckedCastFromInt<Self>>(self)
-> T {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(in_bounds: bool) {
if !in_bounds {
let msg =
"unsafe precondition(s) violated: i8::unchecked_cast must fit in the target type\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check({
let cast_val = self.checked_cast::<T>();
let ret = cast_val.is_some();
core::mem::forget(cast_val);
ret
});
}
};
unsafe { T::unchecked_cast_from(self) }
}int_impl! {
377Self = i8,
378 ActualT = i8,
379 UnsignedT = u8,
380 BITS = 8,
381 BITS_MINUS_ONE = 7,
382 Min = -128,
383 Max = 127,
384 rot = 2,
385 rot_op = "-0x7e",
386 rot_result = "0xa",
387 swap_op = "0x12",
388 swapped = "0x12",
389 reversed = "0x48",
390 le_bytes = "[0x12]",
391 be_bytes = "[0x12]",
392 to_xe_bytes_doc = i8_xe_bytes_doc!(),
393 from_xe_bytes_doc = i8_xe_bytes_doc!(),
394 bound_condition = "",
395 }396/// Calculates the midpoint (average) between `self` and `rhs`.
///
/// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
/// sufficiently-large signed integral type. This implies that the result is
/// always rounded towards zero and that no overflow will ever occur.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0i8.midpoint(4), 2);"]
#[doc = "assert_eq!((-1i8).midpoint(2), 0);"]
#[doc = "assert_eq!((-7i8).midpoint(0), -3);"]
#[doc = "assert_eq!(0i8.midpoint(-7), -3);"]
#[doc = "assert_eq!(0i8.midpoint(7), 3);"]
/// ```
#[stable(feature = "num_midpoint_signed", since = "1.87.0")]
#[rustc_const_stable(feature = "num_midpoint_signed", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[doc(alias = "average_floor")]
#[doc(alias = "average_ceil")]
#[doc(alias = "average")]
#[inline]
pub const fn midpoint(self, rhs: i8) -> i8 {
((self as i16 + rhs as i16) / 2) as i8
}midpoint_impl! { i8, i16, signed }397/// Widening multiplication. Computes `self * rhs`, widening to a larger integer.
///
/// The returned value is always exact and can never overflow.
///
/// Note that this method is semantically equivalent to [`carrying_mul`] with a
/// carry of zero, with the latter instead returning a tuple denoting the low and
/// high parts of the result. Consider using it instead if you need
/// interoperability with other big int helper functions, or if this method isn't
/// available for a given type.
///
/// [`carrying_mul`]: Self::carrying_mul
///
/// # Examples
///
/// ```
/// #![feature(widening_mul)]
///
#[doc = "assert_eq!(i8::MAX.widening_mul(0_i8), 0);"]
#[doc =
"assert_eq!(i8::MAX.widening_mul(i8::MAX), i8::MAX as i16 * i8::MAX as i16);"]
/// ```
#[unstable(feature = "widening_mul", issue = "152016")]
#[rustc_const_unstable(feature = "widening_mul", issue = "152016")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn widening_mul(self, rhs: Self) -> i16 { self as i16 * rhs as i16 }widening_mul_impl! { i8, i16 }398}
399400impl i16 {
401/// The smallest value that can be represented by this integer type
#[doc = "(−2<sup>15</sup>)."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i16::MIN, -32768);"]
/// ```
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MIN: Self = !Self::MAX;
/// The largest value that can be represented by this integer type
#[doc = "(2<sup>15</sup> − 1)."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i16::MAX, 32767);"]
/// ```
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MAX: Self = (<u16>::MAX >> 1) as Self;
/// The size of this integer type in bits.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i16::BITS, 16);"]
/// ```
#[stable(feature = "int_bits_const", since = "1.53.0")]
pub const BITS: u32 = <u16>::BITS;
/// Returns the number of ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 0b100_0000i16;"]
///
/// assert_eq!(n.count_ones(), 1);
/// ```
///
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[doc(alias = "popcount")]
#[doc(alias = "popcnt")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn count_ones(self) -> u32 { (self as u16).count_ones() }
/// Returns the number of zeros in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i16::MAX.count_zeros(), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn count_zeros(self) -> u32 { (!self).count_ones() }
/// Returns the number of leading zeros in the binary representation of `self`.
///
/// Depending on what you're doing with the value, you might also be interested in the
/// [`ilog2`] function which returns a consistent number, even if the type widens.
///
/// # Examples
///
/// ```
#[doc = "let n = -1i16;"]
///
/// assert_eq!(n.leading_zeros(), 0);
/// ```
#[doc = "[`ilog2`]: i16::ilog2"]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn leading_zeros(self) -> u32 { (self as u16).leading_zeros() }
/// Returns the number of trailing zeros in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = -4i16;"]
///
/// assert_eq!(n.trailing_zeros(), 2);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn trailing_zeros(self) -> u32 { (self as u16).trailing_zeros() }
/// Returns the number of leading ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = -1i16;"]
///
#[doc = "assert_eq!(n.leading_ones(), 16);"]
/// ```
#[stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn leading_ones(self) -> u32 { (self as u16).leading_ones() }
/// Returns the number of trailing ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 3i16;"]
///
/// assert_eq!(n.trailing_ones(), 2);
/// ```
#[stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn trailing_ones(self) -> u32 { (self as u16).trailing_ones() }
/// Returns `self` with only the most significant bit set, or `0` if
/// the input is `0`.
///
/// # Examples
///
/// ```
#[doc = "let n: i16 = 0b_01100100;"]
///
/// assert_eq!(n.isolate_highest_one(), 0b_01000000);
#[doc = "assert_eq!(0_i16.isolate_highest_one(), 0);"]
/// ```
#[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn isolate_highest_one(self) -> Self {
self &
(((1 as i16) << (<i16>::BITS - 1)).wrapping_shr(self.leading_zeros()))
}
/// Returns `self` with only the least significant bit set, or `0` if
/// the input is `0`.
///
/// # Examples
///
/// ```
#[doc = "let n: i16 = 0b_01100100;"]
///
/// assert_eq!(n.isolate_lowest_one(), 0b_00000100);
#[doc = "assert_eq!(0_i16.isolate_lowest_one(), 0);"]
/// ```
#[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn isolate_lowest_one(self) -> Self { self & self.wrapping_neg() }
/// Returns the index of the highest bit set to one in `self`, or `None`
/// if `self` is `0`.
///
/// Note that for non-negative numbers, this is equivalent to
/// [`checked_ilog2`](Self::checked_ilog2).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0b0_i16.highest_one(), None);"]
#[doc = "assert_eq!(0b1_i16.highest_one(), Some(0));"]
#[doc = "assert_eq!(0b1_0000_i16.highest_one(), Some(4));"]
#[doc = "assert_eq!(0b1_1111_i16.highest_one(), Some(4));"]
/// ```
#[stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn highest_one(self) -> Option<u32> { (self as u16).highest_one() }
/// Returns the index of the lowest bit set to one in `self`, or `None`
/// if `self` is `0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0b0_i16.lowest_one(), None);"]
#[doc = "assert_eq!(0b1_i16.lowest_one(), Some(0));"]
#[doc = "assert_eq!(0b1_0000_i16.lowest_one(), Some(4));"]
#[doc = "assert_eq!(0b1_1111_i16.lowest_one(), Some(0));"]
/// ```
#[stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn lowest_one(self) -> Option<u32> { (self as u16).lowest_one() }
/// Returns the bit pattern of `self` reinterpreted as an unsigned integer of the same size.
///
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
/// the same.
///
/// # Examples
///
/// ```
#[doc = "let n = -1i16;"]
///
#[doc = "assert_eq!(n.cast_unsigned(), u16::MAX);"]
/// ```
#[stable(feature = "integer_sign_cast", since = "1.87.0")]
#[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_unsigned(self) -> u16 { self as u16 }
/// Saturating conversion of `self` to an unsigned integer of the same size.
///
/// Negative values are clamped to `0`.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`checked_cast_unsigned`](Self::checked_cast_unsigned),
/// or [`strict_cast_unsigned`](Self::strict_cast_unsigned).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = i16::MIN;"]
///
#[doc = "assert_eq!(n.saturating_cast_unsigned(), 0u16);"]
#[doc = "assert_eq!(64i16.saturating_cast_unsigned(), 64u16);"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_cast_unsigned(self) -> u16 {
if self >= 0 { self.cast_unsigned() } else { 0 }
}
/// Checked conversion of `self` to an unsigned integer of the same size,
/// returning `None` if `self` is negative.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`saturating_cast_unsigned`](Self::saturating_cast_unsigned),
/// or [`strict_cast_unsigned`](Self::strict_cast_unsigned).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = i16::MIN;"]
///
#[doc = "assert_eq!(n.checked_cast_unsigned(), None);"]
#[doc = "assert_eq!(64i16.checked_cast_unsigned(), Some(64u16));"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn checked_cast_unsigned(self) -> Option<u16> {
if self >= 0 { Some(self.cast_unsigned()) } else { None }
}
/// Strict conversion of `self` to an unsigned integer of the same size,
/// which panics if `self` is negative.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`checked_cast_unsigned`](Self::checked_cast_unsigned),
/// or [`saturating_cast_unsigned`](Self::saturating_cast_unsigned).
///
/// # Examples
///
/// ```should_panic
/// #![feature(integer_cast_extras)]
#[doc = "let _ = i16::MIN.strict_cast_unsigned();"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_cast_unsigned(self) -> u16 {
match self.checked_cast_unsigned() {
Some(n) => n,
None => imp::overflow_panic::cast_integer(),
}
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `<<` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = -0x5ffdi16;"]
#[doc = "let m = 0x3a;"]
///
#[doc = "assert_eq!(n.rotate_left(4), m);"]
#[doc = "assert_eq!(n.rotate_left(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn rotate_left(self, n: u32) -> Self {
(self as u16).rotate_left(n) as Self
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `>>` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x3ai16;"]
#[doc = "let m = -0x5ffd;"]
///
#[doc = "assert_eq!(n.rotate_right(4), m);"]
#[doc = "assert_eq!(n.rotate_right(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn rotate_right(self, n: u32) -> Self {
(self as u16).rotate_right(n) as Self
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1234i16;"]
///
/// let m = n.swap_bytes();
///
#[doc = "assert_eq!(m, 0x3412);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn swap_bytes(self) -> Self { (self as u16).swap_bytes() as Self }
/// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
/// second least-significant bit becomes second most-significant bit, etc.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1234i16;"]
/// let m = n.reverse_bits();
///
#[doc = "assert_eq!(m, 0x2c48);"]
#[doc = "assert_eq!(0, 0i16.reverse_bits());"]
/// ```
#[stable(feature = "reverse_bits", since = "1.37.0")]
#[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn reverse_bits(self) -> Self {
(self as u16).reverse_bits() as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are swapped.
///
/// See also [from_be_bytes()](Self::from_be_bytes).
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai16;"]
///
/// if cfg!(target_endian = "big") {
#[doc = " assert_eq!(i16::from_be(n), n)"]
/// } else {
#[doc = " assert_eq!(i16::from_be(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn from_be(x: Self) -> Self { x.swap_bytes() }
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are swapped.
///
/// See also [from_le_bytes()](Self::from_le_bytes).
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai16;"]
///
/// if cfg!(target_endian = "little") {
#[doc = " assert_eq!(i16::from_le(n), n)"]
/// } else {
#[doc = " assert_eq!(i16::from_le(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn from_le(x: Self) -> Self { x }
/// Swaps bytes of `self` on little endian targets.
///
/// On big endian this is a no-op.
///
/// The returned value has the same type as `self`, and will be interpreted
/// as (a potentially different) value of a native-endian
#[doc = "`i16`."]
///
/// See [`to_be_bytes()`](Self::to_be_bytes) for a type-safe alternative.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai16;"]
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be(self) -> Self { self.swap_bytes() }
/// Swaps bytes of `self` on big endian targets.
///
/// On little endian this is a no-op.
///
/// The returned value has the same type as `self`, and will be interpreted
/// as (a potentially different) value of a native-endian
#[doc = "`i16`."]
///
/// See [`to_le_bytes()`](Self::to_le_bytes) for a type-safe alternative.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai16;"]
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le(self) -> Self { self }
/// Checked integer addition. Computes `self + rhs`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i16::MAX - 2).checked_add(1), Some(i16::MAX - 1));"]
#[doc = "assert_eq!((i16::MAX - 2).checked_add(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_add(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer addition. Computes `self + rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i16::MAX - 2).strict_add(1), i16::MAX - 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i16::MAX - 2).strict_add(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_add(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Unchecked integer addition. Computes `self + rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_add(y)` is semantically equivalent to calling
/// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_add`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self + rhs > i16::MAX` or `self + rhs < i16::MIN`,"]
/// i.e. when [`checked_add`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_add`]: i16::checked_add"]
#[doc = "[`wrapping_add`]: i16::wrapping_add"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i16, rhs: i16) {
if !!lhs.overflowing_add(rhs).1 {
let msg =
"unsafe precondition(s) violated: i16::unchecked_add cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_add(self, rhs) }
}
/// Checked addition with an unsigned integer. Computes `self + rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i16.checked_add_unsigned(2), Some(3));"]
#[doc = "assert_eq!((i16::MAX - 2).checked_add_unsigned(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add_unsigned(self, rhs: u16) -> Option<Self> {
let (a, b) = self.overflowing_add_unsigned(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict addition with an unsigned integer. Computes `self + rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i16.strict_add_unsigned(2), 3);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i16::MAX - 2).strict_add_unsigned(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add_unsigned(self, rhs: u16) -> Self {
let (a, b) = self.overflowing_add_unsigned(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Checked integer subtraction. Computes `self - rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i16::MIN + 2).checked_sub(1), Some(i16::MIN + 1));"]
#[doc = "assert_eq!((i16::MIN + 2).checked_sub(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_sub(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer subtraction. Computes `self - rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i16::MIN + 2).strict_sub(1), i16::MIN + 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i16::MIN + 2).strict_sub(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_sub(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
/// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_sub`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self - rhs > i16::MAX` or `self - rhs < i16::MIN`,"]
/// i.e. when [`checked_sub`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_sub`]: i16::checked_sub"]
#[doc = "[`wrapping_sub`]: i16::wrapping_sub"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i16, rhs: i16) {
if !!lhs.overflowing_sub(rhs).1 {
let msg =
"unsafe precondition(s) violated: i16::unchecked_sub cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_sub(self, rhs) }
}
/// Checked subtraction with an unsigned integer. Computes `self - rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i16.checked_sub_unsigned(2), Some(-1));"]
#[doc = "assert_eq!((i16::MIN + 2).checked_sub_unsigned(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub_unsigned(self, rhs: u16) -> Option<Self> {
let (a, b) = self.overflowing_sub_unsigned(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict subtraction with an unsigned integer. Computes `self - rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i16.strict_sub_unsigned(2), -1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i16::MIN + 2).strict_sub_unsigned(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub_unsigned(self, rhs: u16) -> Self {
let (a, b) = self.overflowing_sub_unsigned(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Checked integer multiplication. Computes `self * rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i16::MAX.checked_mul(1), Some(i16::MAX));"]
#[doc = "assert_eq!(i16::MAX.checked_mul(2), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer multiplication. Computes `self * rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i16::MAX.strict_mul(1), i16::MAX);"]
/// ```
///
/// The following panics because of overflow:
///
/// ``` should_panic
#[doc = "let _ = i16::MAX.strict_mul(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_mul(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_mul(rhs);
if b { imp::overflow_panic::mul() } else { a }
}
/// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
/// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_mul`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self * rhs > i16::MAX` or `self * rhs < i16::MIN`,"]
/// i.e. when [`checked_mul`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_mul`]: i16::checked_mul"]
#[doc = "[`wrapping_mul`]: i16::wrapping_mul"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i16, rhs: i16) {
if !!lhs.overflowing_mul(rhs).1 {
let msg =
"unsafe precondition(s) violated: i16::unchecked_mul cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_mul(self, rhs) }
}
/// Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
/// or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i16::MIN + 1).checked_div(-1), Some(32767));"]
#[doc = "assert_eq!(i16::MIN.checked_div(-1), None);"]
#[doc = "assert_eq!((1i16).checked_div(0), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1)))
{
None
} else { Some(unsafe { intrinsics::unchecked_div(self, rhs) }) }
}
/// Strict integer division. Computes `self / rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is when one divides `MIN / -1` on a signed type (where
/// [`MIN`](Self::MIN) is the negative minimal value for the type); the result of this is `-MIN`, a positive value
/// that is too large to represent in the type.
///
/// Note that this is equivalent to normal division: `MIN / -1` will also panic both in
/// debug and release builds.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i16::MIN + 1).strict_div(-1), 32767);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i16::MIN.strict_div(-1);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1i16).strict_div(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_div(self, rhs: Self) -> Self { self / rhs }
/// Checked Euclidean division. Computes `self.div_euclid(rhs)`,
/// returning `None` if `rhs == 0` or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i16::MIN + 1).checked_div_euclid(-1), Some(32767));"]
#[doc = "assert_eq!(i16::MIN.checked_div_euclid(-1), None);"]
#[doc = "assert_eq!((1i16).checked_div_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) {
None
} else { Some(self.div_euclid(rhs)) }
}
/// Strict Euclidean division. Computes `self.div_euclid(rhs)`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is when one divides `MIN / -1` on a signed type (where
/// [`MIN`](Self::MIN) is the negative minimal value for the type); the result of this is `-MIN`, a positive value
/// that is too large to represent in the type.
///
/// Note that this is equivalent to `div_euclid`: `MIN.div_euclid(-1)` will also panic both
/// in debug and release builds.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i16::MIN + 1).strict_div_euclid(-1), 32767);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i16::MIN.strict_div_euclid(-1);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1i16).strict_div_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_div_euclid(self, rhs: Self) -> Self {
self.div_euclid(rhs)
}
/// Checked integer division without remainder. Computes `self / rhs`,
/// returning `None` if `rhs == 0`, the division results in overflow,
/// or `self % rhs != 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!((i16::MIN + 1).checked_div_exact(-1), Some(32767));"]
#[doc = "assert_eq!((-5i16).checked_div_exact(2), None);"]
#[doc = "assert_eq!(i16::MIN.checked_div_exact(-1), None);"]
#[doc = "assert_eq!((1i16).checked_div_exact(0), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_exact(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1)))
{
None
} else {
unsafe {
if intrinsics::unlikely(intrinsics::unchecked_rem(self, rhs) != 0)
{
None
} else { Some(intrinsics::exact_div(self, rhs)) }
}
}
}
/// Integer division without remainder. Computes `self / rhs`, returning `None` if `self % rhs != 0`.
///
/// # Panics
///
/// This function will panic if `rhs == 0`.
///
/// ## Overflow behavior
///
/// On overflow, this function will panic if overflow checks are enabled (default in debug
/// mode) and wrap if overflow checks are disabled (default in release mode).
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64i16.div_exact(2), Some(32));"]
#[doc = "assert_eq!(64i16.div_exact(32), Some(2));"]
#[doc = "assert_eq!((i16::MIN + 1).div_exact(-1), Some(32767));"]
#[doc = "assert_eq!(65i16.div_exact(2), None);"]
/// ```
/// ```should_panic
/// #![feature(exact_div)]
#[doc = "let _ = 64i16.div_exact(0);"]
/// ```
/// ```should_panic
/// #![feature(exact_div)]
#[doc = "let _ = i16::MIN.div_exact(-1);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn div_exact(self, rhs: Self) -> Option<Self> {
if self % rhs != 0 { None } else { Some(self / rhs) }
}
/// Unchecked integer division without remainder. Computes `self / rhs`.
///
/// # Safety
///
/// This results in undefined behavior when `rhs == 0`, `self % rhs != 0`, or
#[doc = "`self == i16::MIN && rhs == -1`,"]
/// i.e. when [`checked_div_exact`](Self::checked_div_exact) would return `None`.
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_div_exact(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i16, rhs: i16) {
if !(rhs != 0 && lhs % rhs == 0 &&
(lhs != <i16>::MIN || rhs != -1)) {
let msg =
"unsafe precondition(s) violated: i16::unchecked_div_exact cannot overflow, divide by zero, or leave a remainder\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::exact_div(self, rhs) }
}
/// Checked integer remainder. Computes `self % rhs`, returning `None` if
/// `rhs == 0` or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i16.checked_rem(2), Some(1));"]
#[doc = "assert_eq!(5i16.checked_rem(0), None);"]
#[doc = "assert_eq!(i16::MIN.checked_rem(-1), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1)))
{
None
} else { Some(unsafe { intrinsics::unchecked_rem(self, rhs) }) }
}
/// Strict integer remainder. Computes `self % rhs`, panicking if
/// the division results in overflow.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is `x % y` for `MIN / -1` on a
/// signed type (where [`MIN`](Self::MIN) is the negative minimal value), which is invalid due to implementation artifacts.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i16.strict_rem(2), 1);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5i16.strict_rem(0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i16::MIN.strict_rem(-1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_rem(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_rem(rhs);
if b { imp::overflow_panic::rem() } else { a }
}
/// Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
/// if `rhs == 0` or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i16.checked_rem_euclid(2), Some(1));"]
#[doc = "assert_eq!(5i16.checked_rem_euclid(0), None);"]
#[doc = "assert_eq!(i16::MIN.checked_rem_euclid(-1), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) {
None
} else { Some(self.rem_euclid(rhs)) }
}
/// Strict Euclidean remainder. Computes `self.rem_euclid(rhs)`, panicking if
/// the division results in overflow.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is `x % y` for `MIN / -1` on a
/// signed type (where [`MIN`](Self::MIN) is the negative minimal value), which is invalid due to implementation artifacts.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i16.strict_rem_euclid(2), 1);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5i16.strict_rem_euclid(0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i16::MIN.strict_rem_euclid(-1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_rem_euclid(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_rem_euclid(rhs);
if b { imp::overflow_panic::rem() } else { a }
}
/// Checked negation. Computes `-self`, returning `None` if `self == MIN`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i16.checked_neg(), Some(-5));"]
#[doc = "assert_eq!(i16::MIN.checked_neg(), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_neg(self) -> Option<Self> {
let (a, b) = self.overflowing_neg();
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Unchecked negation. Computes `-self`, assuming overflow cannot occur.
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self == i16::MIN`,"]
/// i.e. when [`checked_neg`] would return `None`.
///
#[doc = "[`checked_neg`]: i16::checked_neg"]
#[stable(feature = "unchecked_neg", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_neg", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_neg(self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i16) {
if !!lhs.overflowing_neg().1 {
let msg =
"unsafe precondition(s) violated: i16::unchecked_neg cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self);
}
};
unsafe { intrinsics::unchecked_sub(0, self) }
}
/// Strict negation. Computes `-self`, panicking if `self == MIN`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i16.strict_neg(), -5);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i16::MIN.strict_neg();"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_neg(self) -> Self {
let (a, b) = self.overflowing_neg();
if b { imp::overflow_panic::neg() } else { a }
}
/// Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
/// than or equal to the number of bits in `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1i16.checked_shl(4), Some(0x10));"]
#[doc = "assert_eq!(0x1i16.checked_shl(129), None);"]
#[doc = "assert_eq!(0x10i16.checked_shl(15), Some(0));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
if rhs < Self::BITS {
Some(unsafe { self.unchecked_shl(rhs) })
} else { None }
}
/// Strict shift left. Computes `self << rhs`, panicking if `rhs` is larger
/// than or equal to the number of bits in `self`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1i16.strict_shl(4), 0x10);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0x1i16.strict_shl(129);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_shl(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_shl(rhs);
if b { imp::overflow_panic::shl() } else { a }
}
/// Unchecked shift left. Computes `self << rhs`, assuming that
/// `rhs` is less than the number of bits in `self`.
///
/// # Safety
///
/// This results in undefined behavior if `rhs` is larger than
/// or equal to the number of bits in `self`,
/// i.e. when [`checked_shl`] would return `None`.
///
#[doc = "[`checked_shl`]: i16::checked_shl"]
#[stable(feature = "unchecked_shifts", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_shl(self, rhs: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(rhs: u32) {
if !(rhs < <i16>::BITS) {
let msg =
"unsafe precondition(s) violated: i16::unchecked_shl cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(rhs); }
};
unsafe { intrinsics::unchecked_shl(self, rhs) }
}
/// Unbounded shift left. Computes `self << rhs`, without bounding the value of `rhs`.
///
/// If `rhs` is larger or equal to the number of bits in `self`,
/// the entire value is shifted out, and `0` is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1_i16.unbounded_shl(4), 0x10);"]
#[doc = "assert_eq!(0x1_i16.unbounded_shl(129), 0);"]
#[doc = "assert_eq!(0b101_i16.unbounded_shl(0), 0b101);"]
#[doc = "assert_eq!(0b101_i16.unbounded_shl(1), 0b1010);"]
#[doc = "assert_eq!(0b101_i16.unbounded_shl(2), 0b10100);"]
#[doc = "assert_eq!(42_i16.unbounded_shl(16), 0);"]
#[doc = "assert_eq!(42_i16.unbounded_shl(1).unbounded_shl(15), 0);"]
#[doc = "assert_eq!((-13_i16).unbounded_shl(16), 0);"]
#[doc = "assert_eq!((-13_i16).unbounded_shl(1).unbounded_shl(15), 0);"]
/// ```
#[stable(feature = "unbounded_shifts", since = "1.87.0")]
#[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unbounded_shl(self, rhs: u32) -> i16 {
if rhs < Self::BITS { unsafe { self.unchecked_shl(rhs) } } else { 0 }
}
/// Exact shift left. Computes `self << rhs` as long as it can be reversed losslessly.
///
/// Returns `None` if any bits that would be shifted out differ from the resulting sign bit
/// or if `rhs` >=
#[doc = "`i16::BITS`."]
/// Otherwise, returns `Some(self << rhs)`.
///
/// # Examples
///
/// ```
/// #![feature(exact_bitshifts)]
///
#[doc = "assert_eq!(0x1i16.shl_exact(4), Some(0x10));"]
#[doc =
"assert_eq!(0x1i16.shl_exact(i16::BITS - 2), Some(1 << i16::BITS - 2));"]
#[doc = "assert_eq!(0x1i16.shl_exact(i16::BITS - 1), None);"]
#[doc =
"assert_eq!((-0x2i16).shl_exact(i16::BITS - 2), Some(-0x2 << i16::BITS - 2));"]
#[doc = "assert_eq!((-0x2i16).shl_exact(i16::BITS - 1), None);"]
/// ```
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn shl_exact(self, rhs: u32) -> Option<i16> {
if rhs < self.leading_zeros() || rhs < self.leading_ones() {
Some(unsafe { self.unchecked_shl(rhs) })
} else { None }
}
/// Unchecked exact shift left. Computes `self << rhs`, assuming the operation can be
/// losslessly reversed and `rhs` cannot be larger than
#[doc = "`i16::BITS`."]
///
/// # Safety
///
/// This results in undefined behavior when `rhs >= self.leading_zeros() && rhs >=
/// self.leading_ones()` i.e. when
#[doc = "[`i16::shl_exact`]"]
/// would return `None`.
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_shl_exact(self, rhs: u32) -> i16 {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(zeros: u32, ones: u32, rhs: u32) {
if !(rhs < zeros || rhs < ones) {
let msg =
"unsafe precondition(s) violated: i16::unchecked_shl_exact cannot shift out bits that would change the value of the first bit\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_library_ub() {
precondition_check(self.leading_zeros(), self.leading_ones(),
rhs);
}
};
unsafe { self.unchecked_shl(rhs) }
}
/// Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
/// larger than or equal to the number of bits in `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10i16.checked_shr(4), Some(0x1));"]
#[doc = "assert_eq!(0x10i16.checked_shr(128), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
if rhs < Self::BITS {
Some(unsafe { self.unchecked_shr(rhs) })
} else { None }
}
/// Strict shift right. Computes `self >> rhs`, panicking if `rhs` is
/// larger than or equal to the number of bits in `self`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10i16.strict_shr(4), 0x1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0x10i16.strict_shr(128);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_shr(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_shr(rhs);
if b { imp::overflow_panic::shr() } else { a }
}
/// Unchecked shift right. Computes `self >> rhs`, assuming that
/// `rhs` is less than the number of bits in `self`.
///
/// # Safety
///
/// This results in undefined behavior if `rhs` is larger than
/// or equal to the number of bits in `self`,
/// i.e. when [`checked_shr`] would return `None`.
///
#[doc = "[`checked_shr`]: i16::checked_shr"]
#[stable(feature = "unchecked_shifts", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_shr(self, rhs: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(rhs: u32) {
if !(rhs < <i16>::BITS) {
let msg =
"unsafe precondition(s) violated: i16::unchecked_shr cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(rhs); }
};
unsafe { intrinsics::unchecked_shr(self, rhs) }
}
/// Unbounded shift right. Computes `self >> rhs`, without bounding the value of `rhs`.
///
/// If `rhs` is larger or equal to the number of bits in `self`,
/// the entire value is shifted out, which yields `0` for a positive number,
/// and `-1` for a negative number.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10_i16.unbounded_shr(4), 0x1);"]
#[doc = "assert_eq!(0x10_i16.unbounded_shr(129), 0);"]
#[doc = "assert_eq!(i16::MIN.unbounded_shr(129), -1);"]
#[doc = "assert_eq!(0b1010_i16.unbounded_shr(0), 0b1010);"]
#[doc = "assert_eq!(0b1010_i16.unbounded_shr(1), 0b101);"]
#[doc = "assert_eq!(0b1010_i16.unbounded_shr(2), 0b10);"]
#[doc = "assert_eq!(42_i16.unbounded_shr(16), 0);"]
#[doc = "assert_eq!(42_i16.unbounded_shr(1).unbounded_shr(15), 0);"]
#[doc = "assert_eq!((-13_i16).unbounded_shr(16), -1);"]
#[doc = "assert_eq!((-13_i16).unbounded_shr(1).unbounded_shr(15), -1);"]
/// ```
#[stable(feature = "unbounded_shifts", since = "1.87.0")]
#[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unbounded_shr(self, rhs: u32) -> i16 {
if rhs < Self::BITS {
unsafe { self.unchecked_shr(rhs) }
} else { unsafe { self.unchecked_shr(Self::BITS - 1) } }
}
/// Exact shift right. Computes `self >> rhs` as long as it can be reversed losslessly.
///
/// Returns `None` if any non-zero bits would be shifted out or if `rhs` >=
#[doc = "`i16::BITS`."]
/// Otherwise, returns `Some(self >> rhs)`.
///
/// # Examples
///
/// ```
/// #![feature(exact_bitshifts)]
///
#[doc = "assert_eq!(0x10i16.shr_exact(4), Some(0x1));"]
#[doc = "assert_eq!(0x10i16.shr_exact(5), None);"]
/// ```
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn shr_exact(self, rhs: u32) -> Option<i16> {
if rhs <= self.trailing_zeros() && rhs < <i16>::BITS {
Some(unsafe { self.unchecked_shr(rhs) })
} else { None }
}
/// Unchecked exact shift right. Computes `self >> rhs`, assuming the operation can be
/// losslessly reversed and `rhs` cannot be larger than
#[doc = "`i16::BITS`."]
///
/// # Safety
///
/// This results in undefined behavior when `rhs > self.trailing_zeros() || rhs >=
#[doc = "i16::BITS`"]
/// i.e. when
#[doc = "[`i16::shr_exact`]"]
/// would return `None`.
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_shr_exact(self, rhs: u32) -> i16 {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(zeros: u32, bits: u32, rhs: u32) {
if !(rhs <= zeros && rhs < bits) {
let msg =
"unsafe precondition(s) violated: i16::unchecked_shr_exact cannot shift out non-zero bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_library_ub() {
precondition_check(self.trailing_zeros(), <i16>::BITS, rhs);
}
};
unsafe { self.unchecked_shr(rhs) }
}
/// Checked absolute value. Computes `self.abs()`, returning `None` if
/// `self == MIN`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-5i16).checked_abs(), Some(5));"]
#[doc = "assert_eq!(i16::MIN.checked_abs(), None);"]
/// ```
#[stable(feature = "no_panic_abs", since = "1.13.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_abs(self) -> Option<Self> {
if self.is_negative() { self.checked_neg() } else { Some(self) }
}
/// Strict absolute value. Computes `self.abs()`, panicking if
/// `self == MIN`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-5i16).strict_abs(), 5);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i16::MIN.strict_abs();"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_abs(self) -> Self {
if self.is_negative() { self.strict_neg() } else { self }
}
/// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(8i16.checked_pow(2), Some(64));"]
#[doc = "assert_eq!(0_i16.checked_pow(0), Some(1));"]
#[doc = "assert_eq!(i16::MAX.checked_pow(2), None);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
let mut base = self;
let mut acc: Self = 1;
if intrinsics::is_val_statically_known(base) &&
base.unsigned_abs().is_power_of_two() {
let k = base.unsigned_abs().ilog2();
let shift =
match k.checked_mul(exp) { Some(x) => x, None => return None, };
return if base < 0 && (exp % 2) == 1 {
(-1 as Self).shl_exact(shift)
} else { (1 as Self).shl_exact(shift) }
}
if exp == 0 { return Some(1); }
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 {
acc =
match acc.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
exp /= 2;
base =
match base.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
return acc.checked_mul(base);
}
loop {
if (exp & 1) == 1 {
acc =
match acc.checked_mul(base) {
Some(x) => x,
None => return None,
};
if exp == 1 { return Some(acc); }
}
exp /= 2;
base =
match base.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
}
/// Strict exponentiation. Computes `self.pow(exp)`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(8i16.strict_pow(2), 64);"]
#[doc = "assert_eq!(0_i16.strict_pow(0), 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i16::MAX.strict_pow(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) {
Some(x) => x,
None => imp::overflow_panic::pow(),
}
}
/// Returns the integer square root of the number, rounded down.
///
/// This function returns the **principal (non-negative) square root**.
/// For a given number `n`, although both `x` and `-x` satisfy x<sup>2</sup> = n,
/// this function always returns the non-negative value.
///
/// Returns `None` if `self` is negative.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i16.checked_isqrt(), Some(3));"]
/// ```
#[stable(feature = "isqrt", since = "1.84.0")]
#[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_isqrt(self) -> Option<Self> {
if self < 0 {
None
} else {
let result = self.cast_unsigned().isqrt().cast_signed();
unsafe {
const MAX_RESULT: i16 =
<i16>::MAX.cast_unsigned().isqrt().cast_signed();
crate::hint::assert_unchecked(result <= MAX_RESULT);
}
Some(result)
}
}
/// Saturating integer addition. Computes `self + rhs`, saturating at the numeric
/// bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i16.saturating_add(1), 101);"]
#[doc = "assert_eq!(i16::MAX.saturating_add(100), i16::MAX);"]
#[doc = "assert_eq!(i16::MIN.saturating_add(-1), i16::MIN);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_add(self, rhs: Self) -> Self {
intrinsics::saturating_add(self, rhs)
}
/// Saturating addition with an unsigned integer. Computes `self + rhs`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i16.saturating_add_unsigned(2), 3);"]
#[doc = "assert_eq!(i16::MAX.saturating_add_unsigned(100), i16::MAX);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_add_unsigned(self, rhs: u16) -> Self {
match self.checked_add_unsigned(rhs) { Some(x) => x, None => Self::MAX, }
}
/// Saturating integer subtraction. Computes `self - rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i16.saturating_sub(127), -27);"]
#[doc = "assert_eq!(i16::MIN.saturating_sub(100), i16::MIN);"]
#[doc = "assert_eq!(i16::MAX.saturating_sub(-1), i16::MAX);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_sub(self, rhs: Self) -> Self {
intrinsics::saturating_sub(self, rhs)
}
/// Saturating subtraction with an unsigned integer. Computes `self - rhs`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i16.saturating_sub_unsigned(127), -27);"]
#[doc = "assert_eq!(i16::MIN.saturating_sub_unsigned(100), i16::MIN);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_sub_unsigned(self, rhs: u16) -> Self {
match self.checked_sub_unsigned(rhs) { Some(x) => x, None => Self::MIN, }
}
/// Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
/// instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i16.saturating_neg(), -100);"]
#[doc = "assert_eq!((-100i16).saturating_neg(), 100);"]
#[doc = "assert_eq!(i16::MIN.saturating_neg(), i16::MAX);"]
#[doc = "assert_eq!(i16::MAX.saturating_neg(), i16::MIN + 1);"]
/// ```
#[stable(feature = "saturating_neg", since = "1.45.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_neg(self) -> Self {
intrinsics::saturating_sub(0, self)
}
/// Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
/// MIN` instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i16.saturating_abs(), 100);"]
#[doc = "assert_eq!((-100i16).saturating_abs(), 100);"]
#[doc = "assert_eq!(i16::MIN.saturating_abs(), i16::MAX);"]
#[doc = "assert_eq!((i16::MIN + 1).saturating_abs(), i16::MAX);"]
/// ```
#[stable(feature = "saturating_neg", since = "1.45.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_abs(self) -> Self {
if self.is_negative() { self.saturating_neg() } else { self }
}
/// Saturating integer multiplication. Computes `self * rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i16.saturating_mul(12), 120);"]
#[doc = "assert_eq!(i16::MAX.saturating_mul(10), i16::MAX);"]
#[doc = "assert_eq!(i16::MIN.saturating_mul(10), i16::MIN);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_mul(self, rhs: Self) -> Self {
match self.checked_mul(rhs) {
Some(x) => x,
None => if (self < 0) == (rhs < 0) { Self::MAX } else { Self::MIN },
}
}
/// Saturating integer division. Computes `self / rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i16.saturating_div(2), 2);"]
#[doc = "assert_eq!(i16::MAX.saturating_div(-1), i16::MIN + 1);"]
#[doc = "assert_eq!(i16::MIN.saturating_div(-1), i16::MAX);"]
///
/// ```
#[stable(feature = "saturating_div", since = "1.58.0")]
#[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_div(self, rhs: Self) -> Self {
match self.overflowing_div(rhs) {
(result, false) => result,
(_result, true) => Self::MAX,
}
}
/// Saturating integer exponentiation. Computes `self.pow(exp)`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-4i16).saturating_pow(3), -64);"]
#[doc = "assert_eq!(0_i16.saturating_pow(0), 1);"]
#[doc = "assert_eq!(i16::MIN.saturating_pow(2), i16::MAX);"]
#[doc = "assert_eq!(i16::MIN.saturating_pow(3), i16::MIN);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) {
Some(x) => x,
None if self < 0 && exp % 2 == 1 => Self::MIN,
None => Self::MAX,
}
}
/// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
/// boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i16.wrapping_add(27), 127);"]
#[doc = "assert_eq!(i16::MAX.wrapping_add(2), i16::MIN + 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_add(self, rhs: Self) -> Self {
intrinsics::wrapping_add(self, rhs)
}
/// Wrapping (modular) addition with an unsigned integer. Computes
/// `self + rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i16.wrapping_add_unsigned(27), 127);"]
#[doc = "assert_eq!(i16::MAX.wrapping_add_unsigned(2), i16::MIN + 1);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_add_unsigned(self, rhs: u16) -> Self {
self.wrapping_add(rhs as Self)
}
/// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
/// boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0i16.wrapping_sub(127), -127);"]
#[doc = "assert_eq!((-2i16).wrapping_sub(i16::MAX), i16::MAX);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_sub(self, rhs: Self) -> Self {
intrinsics::wrapping_sub(self, rhs)
}
/// Wrapping (modular) subtraction with an unsigned integer. Computes
/// `self - rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0i16.wrapping_sub_unsigned(127), -127);"]
#[doc = "assert_eq!((-2i16).wrapping_sub_unsigned(u16::MAX), -1);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_sub_unsigned(self, rhs: u16) -> Self {
self.wrapping_sub(rhs as Self)
}
/// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
/// the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i16.wrapping_mul(12), 120);"]
/// assert_eq!(11i8.wrapping_mul(12), -124);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_mul(self, rhs: Self) -> Self {
intrinsics::wrapping_mul(self, rhs)
}
/// Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
/// boundary of the type.
///
/// The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
/// [`MIN`](Self::MIN) is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
/// that is too large to represent in the type. In such a case, this function returns [`MIN`](Self::MIN) itself.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i16.wrapping_div(10), 10);"]
/// assert_eq!((-128i8).wrapping_div(-1), -128);
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_div(self, rhs: Self) -> Self {
self.overflowing_div(rhs).0
}
/// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
/// wrapping around at the boundary of the type.
///
/// Wrapping will only occur in `MIN / -1` on a signed type (where [`MIN`](Self::MIN) is the negative minimal value
/// for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
/// type. In this case, this method returns [`MIN`](Self::MIN) itself.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i16.wrapping_div_euclid(10), 10);"]
/// assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
self.overflowing_div_euclid(rhs).0
}
/// Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
/// boundary of the type.
///
/// Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
/// invalid for `MIN / -1` on a signed type (where [`MIN`](Self::MIN) is the negative minimal value). In such a case,
/// this function returns `0`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i16.wrapping_rem(10), 0);"]
/// assert_eq!((-128i8).wrapping_rem(-1), 0);
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_rem(self, rhs: Self) -> Self {
self.overflowing_rem(rhs).0
}
/// Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
/// at the boundary of the type.
///
/// Wrapping will only occur in `MIN % -1` on a signed type (where [`MIN`](Self::MIN) is
/// the negative minimal value for the type). In this case, this method returns 0.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i16.wrapping_rem_euclid(10), 0);"]
/// assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
self.overflowing_rem_euclid(rhs).0
}
/// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
/// of the type.
///
/// The only case where such wrapping can occur is when one negates [`MIN`](Self::MIN) on a signed type (where [`MIN`](Self::MIN)
/// is the negative minimal value for the type); this is a positive value that is too large to represent
/// in the type. In such a case, this function returns [`MIN`](Self::MIN) itself.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i16.wrapping_neg(), -100);"]
#[doc = "assert_eq!((-100i16).wrapping_neg(), 100);"]
#[doc = "assert_eq!(i16::MIN.wrapping_neg(), i16::MIN);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_neg(self) -> Self { (0 as i16).wrapping_sub(self) }
/// Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
/// any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
///
/// Beware that, unlike most other `wrapping_*` methods on integers, this
/// does *not* give the same result as doing the shift in infinite precision
/// then truncating as needed. Instead, the behaviour of this method matches what shift instructions
/// do on many processors, and is what the `<<` operator does when overflow
/// checks are disabled, but numerically it's weird. Consider, instead,
/// using [`Self::unbounded_shl`] which has nicer behaviour.
///
/// Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
/// the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
/// The primitive integer types all implement a [`rotate_left`](Self::rotate_left) function,
/// which may be what you want instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-1_i16).wrapping_shl(7), -128);"]
#[doc = "assert_eq!(42_i16.wrapping_shl(16), 42);"]
#[doc = "assert_eq!(42_i16.wrapping_shl(1).wrapping_shl(15), 0);"]
#[doc = "assert_eq!((-1_i16).wrapping_shl(128), -1);"]
#[doc = "assert_eq!(5_i16.wrapping_shl(1025), 10);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_shl(self, rhs: u32) -> Self {
unsafe { self.unchecked_shl(rhs & (Self::BITS - 1)) }
}
/// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
/// removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
///
/// Beware that, unlike most other `wrapping_*` methods on integers, this
/// does *not* give the same result as doing the shift in infinite precision
/// then truncating as needed. Instead, the behaviour of this method matches what shift instructions
/// do on many processors, and is what the `>>` operator does when overflow
/// checks are disabled, but numerically it's weird. Consider, instead,
/// using [`Self::unbounded_shr`] which has nicer behaviour.
///
/// Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
/// to the range of the type, rather than the bits shifted out of the LHS being returned to the other
/// end. The primitive integer types all implement a [`rotate_right`](Self::rotate_right) function,
/// which may be what you want instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-128_i16).wrapping_shr(7), -1);"]
#[doc = "assert_eq!(42_i16.wrapping_shr(16), 42);"]
#[doc = "assert_eq!(42_i16.wrapping_shr(1).wrapping_shr(15), 0);"]
/// assert_eq!((-128_i16).wrapping_shr(64), -128);
#[doc = "assert_eq!(10_i16.wrapping_shr(1025), 5);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_shr(self, rhs: u32) -> Self {
unsafe { self.unchecked_shr(rhs & (Self::BITS - 1)) }
}
/// Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
/// the boundary of the type.
///
/// The only case where such wrapping can occur is when one takes the absolute value of the negative
/// minimal value for the type; this is a positive value that is too large to represent in the type. In
/// such a case, this function returns [`MIN`](Self::MIN) itself.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i16.wrapping_abs(), 100);"]
#[doc = "assert_eq!((-100i16).wrapping_abs(), 100);"]
#[doc = "assert_eq!(i16::MIN.wrapping_abs(), i16::MIN);"]
/// assert_eq!((-128i8).wrapping_abs() as u8, 128);
/// ```
#[stable(feature = "no_panic_abs", since = "1.13.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[allow(unused_attributes)]
#[inline]
pub const fn wrapping_abs(self) -> Self {
if self.is_negative() { self.wrapping_neg() } else { self }
}
/// Computes the absolute value of `self` without any wrapping
/// or panicking.
///
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i16.unsigned_abs(), 100u16);"]
#[doc = "assert_eq!((-100i16).unsigned_abs(), 100u16);"]
/// assert_eq!((-128i8).unsigned_abs(), 128u8);
/// ```
#[stable(feature = "unsigned_abs", since = "1.51.0")]
#[rustc_const_stable(feature = "unsigned_abs", since = "1.51.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unsigned_abs(self) -> u16 { self.wrapping_abs() as u16 }
/// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3i16.wrapping_pow(4), 81);"]
/// assert_eq!(3i8.wrapping_pow(5), -13);
/// assert_eq!(3i8.wrapping_pow(6), -39);
#[doc = "assert_eq!(0_i16.wrapping_pow(0), 1);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_pow(self, exp: u32) -> Self {
let (a, _) = self.overflowing_pow(exp);
a
}
/// Calculates `self` + `rhs`.
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would have
/// occurred then the wrapped value is returned (negative if overflowed
/// above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i16.overflowing_add(2), (7, false));"]
#[doc = "assert_eq!(i16::MAX.overflowing_add(1), (i16::MIN, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::add_with_overflow(self as i16, rhs as i16);
(a as Self, b)
}
/// Calculates `self` + `rhs` + `carry` and checks for overflow.
///
/// Performs "ternary addition" of two integer operands and a carry-in
/// bit, and returns a tuple of the sum along with a boolean indicating
/// whether an arithmetic overflow would occur. On overflow, the wrapped
/// value is returned.
///
/// This allows chaining together multiple additions to create a wider
/// addition, and can be useful for bignum addition. This method should
/// only be used for the most significant word; for the less significant
/// words the unsigned method
#[doc = "[`u16::carrying_add`]"]
/// should be used.
///
/// The output boolean returned by this method is *not* a carry flag,
/// and should *not* be added to a more significant word.
///
/// If overflow occurred, the wrapped value is returned (negative if overflowed
/// above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
///
/// If the input carry is false, this method is equivalent to
/// [`overflowing_add`](Self::overflowing_add).
///
/// # Examples
///
/// ```
/// #![feature(signed_bigint_helpers)]
/// // Only the most significant word is signed.
/// //
#[doc = "// 10 MAX (a = 10 \u{d7} 2^16 + 2^16 - 1)"]
#[doc = "// + -5 9 (b = -5 \u{d7} 2^16 + 9)"]
/// // ---------
#[doc = "// 6 8 (sum = 6 \u{d7} 2^16 + 8)"]
///
#[doc = "let (a1, a0): (i16, u16) = (10, u16::MAX);"]
#[doc = "let (b1, b0): (i16, u16) = (-5, 9);"]
/// let carry0 = false;
///
#[doc = "// u16::carrying_add for the less significant words"]
/// let (sum0, carry1) = a0.carrying_add(b0, carry0);
/// assert_eq!(carry1, true);
///
#[doc = "// i16::carrying_add for the most significant word"]
/// let (sum1, overflow) = a1.carrying_add(b1, carry1);
/// assert_eq!(overflow, false);
///
/// assert_eq!((sum1, sum0), (6, 8));
/// ```
#[unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
let (a, b) = self.overflowing_add(rhs);
let (c, d) = a.overflowing_add(carry as i16);
(c, b != d)
}
/// Calculates `self` + `rhs` with an unsigned `rhs`.
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i16.overflowing_add_unsigned(2), (3, false));"]
#[doc =
"assert_eq!((i16::MIN).overflowing_add_unsigned(u16::MAX), (i16::MAX, false));"]
#[doc =
"assert_eq!((i16::MAX - 2).overflowing_add_unsigned(3), (i16::MIN, true));"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_add_unsigned(self, rhs: u16) -> (Self, bool) {
let rhs = rhs as Self;
let (res, overflowed) = self.overflowing_add(rhs);
(res, overflowed ^ (rhs < 0))
}
/// Calculates `self` - `rhs`.
///
/// Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
/// would occur. If an overflow would have occurred then the wrapped value is returned
/// (negative if overflowed above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i16.overflowing_sub(2), (3, false));"]
#[doc = "assert_eq!(i16::MIN.overflowing_sub(1), (i16::MAX, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::sub_with_overflow(self as i16, rhs as i16);
(a as Self, b)
}
/// Calculates `self` − `rhs` − `borrow` and checks for
/// overflow.
///
/// Performs "ternary subtraction" by subtracting both an integer
/// operand and a borrow-in bit from `self`, and returns a tuple of the
/// difference along with a boolean indicating whether an arithmetic
/// overflow would occur. On overflow, the wrapped value is returned.
///
/// This allows chaining together multiple subtractions to create a
/// wider subtraction, and can be useful for bignum subtraction. This
/// method should only be used for the most significant word; for the
/// less significant words the unsigned method
#[doc = "[`u16::borrowing_sub`]"]
/// should be used.
///
/// The output boolean returned by this method is *not* a borrow flag,
/// and should *not* be subtracted from a more significant word.
///
/// If overflow occurred, the wrapped value is returned (negative if overflowed
/// above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
///
/// If the input borrow is false, this method is equivalent to
/// [`overflowing_sub`](Self::overflowing_sub).
///
/// # Examples
///
/// ```
/// #![feature(signed_bigint_helpers)]
/// // Only the most significant word is signed.
/// //
#[doc = "// 6 8 (a = 6 \u{d7} 2^16 + 8)"]
#[doc = "// - -5 9 (b = -5 \u{d7} 2^16 + 9)"]
/// // ---------
#[doc = "// 10 MAX (diff = 10 \u{d7} 2^16 + 2^16 - 1)"]
///
#[doc = "let (a1, a0): (i16, u16) = (6, 8);"]
#[doc = "let (b1, b0): (i16, u16) = (-5, 9);"]
/// let borrow0 = false;
///
#[doc = "// u16::borrowing_sub for the less significant words"]
/// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);
/// assert_eq!(borrow1, true);
///
#[doc = "// i16::borrowing_sub for the most significant word"]
/// let (diff1, overflow) = a1.borrowing_sub(b1, borrow1);
/// assert_eq!(overflow, false);
///
#[doc = "assert_eq!((diff1, diff0), (10, u16::MAX));"]
/// ```
#[unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
let (a, b) = self.overflowing_sub(rhs);
let (c, d) = a.overflowing_sub(borrow as i16);
(c, b != d)
}
/// Calculates `self` - `rhs` with an unsigned `rhs`.
///
/// Returns a tuple of the subtraction along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i16.overflowing_sub_unsigned(2), (-1, false));"]
#[doc =
"assert_eq!((i16::MAX).overflowing_sub_unsigned(u16::MAX), (i16::MIN, false));"]
#[doc =
"assert_eq!((i16::MIN + 2).overflowing_sub_unsigned(3), (i16::MAX, true));"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_sub_unsigned(self, rhs: u16) -> (Self, bool) {
let rhs = rhs as Self;
let (res, overflowed) = self.overflowing_sub(rhs);
(res, overflowed ^ (rhs < 0))
}
/// Calculates the multiplication of `self` and `rhs`.
///
/// Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
/// would occur. If an overflow would have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i16.overflowing_mul(2), (10, false));"]
/// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::mul_with_overflow(self as i16, rhs as i16);
(a as Self, b)
}
/// Calculates the "full multiplication" `self * rhs + carry`
/// without the possibility to overflow.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// Performs "long multiplication" which takes in an extra amount to add, and may return an
/// additional amount of overflow. This allows for chaining together multiple
/// multiplications to create "big integers" which represent larger values.
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why [`i32`] is used.
///
/// ```
/// #![feature(signed_bigint_helpers)]
/// assert_eq!(5i32.carrying_mul(-2, 0), (4294967286, -1));
/// assert_eq!(5i32.carrying_mul(-2, 10), (0, 0));
/// assert_eq!(1_000_000_000i32.carrying_mul(-10, 0), (2884901888, -3));
/// assert_eq!(1_000_000_000i32.carrying_mul(-10, 10), (2884901898, -3));
#[doc =
"assert_eq!(i16::MAX.carrying_mul(i16::MAX, i16::MAX), (i16::MAX.unsigned_abs() + 1, i16::MAX / 2));"]
/// ```
#[unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[rustc_const_unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_mul(self, rhs: Self, carry: Self) -> (u16, Self) {
Self::carrying_mul_add(self, rhs, carry, 0)
}
/// Calculates the "full multiplication" `self * rhs + carry + add`
/// without the possibility to overflow.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// Performs "long multiplication" which takes in an extra amount to add, and may return an
/// additional amount of overflow. This allows for chaining together multiple
/// multiplications to create "big integers" which represent larger values.
///
/// If you only need one `carry`, then you can use [`Self::carrying_mul`] instead.
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `i32` is used.
///
/// ```
/// #![feature(signed_bigint_helpers)]
/// assert_eq!(5i32.carrying_mul_add(-2, 0, 0), (4294967286, -1));
/// assert_eq!(5i32.carrying_mul_add(-2, 10, 10), (10, 0));
/// assert_eq!(1_000_000_000i32.carrying_mul_add(-10, 0, 0), (2884901888, -3));
/// assert_eq!(1_000_000_000i32.carrying_mul_add(-10, 10, 10), (2884901908, -3));
#[doc =
"assert_eq!(i16::MAX.carrying_mul_add(i16::MAX, i16::MAX, i16::MAX), (u16::MAX, i16::MAX / 2));"]
/// ```
#[unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[rustc_const_unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_mul_add(self, rhs: Self, carry: Self, add: Self)
-> (u16, Self) {
intrinsics::carrying_mul_add(self, rhs, carry, add)
}
/// Calculates the divisor when `self` is divided by `rhs`.
///
/// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
/// occur. If an overflow would occur then self is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i16.overflowing_div(2), (2, false));"]
#[doc = "assert_eq!(i16::MIN.overflowing_div(-1), (i16::MIN, true));"]
/// ```
#[inline]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_overflowing_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
if intrinsics::unlikely((self == Self::MIN) & (rhs == -1)) {
(self, true)
} else { (self / rhs, false) }
}
/// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
///
/// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
/// occur. If an overflow would occur then `self` is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i16.overflowing_div_euclid(2), (2, false));"]
#[doc = "assert_eq!(i16::MIN.overflowing_div_euclid(-1), (i16::MIN, true));"]
/// ```
#[inline]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
if intrinsics::unlikely((self == Self::MIN) & (rhs == -1)) {
(self, true)
} else { (self.div_euclid(rhs), false) }
}
/// Calculates the remainder when `self` is divided by `rhs`.
///
/// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
/// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i16.overflowing_rem(2), (1, false));"]
#[doc = "assert_eq!(i16::MIN.overflowing_rem(-1), (0, true));"]
/// ```
#[inline]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_overflowing_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
if intrinsics::unlikely(rhs == -1) {
(0, self == Self::MIN)
} else { (self % rhs, false) }
}
/// Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
///
/// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
/// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i16.overflowing_rem_euclid(2), (1, false));"]
#[doc = "assert_eq!(i16::MIN.overflowing_rem_euclid(-1), (0, true));"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
if intrinsics::unlikely(rhs == -1) {
(0, self == Self::MIN)
} else { (self.rem_euclid(rhs), false) }
}
/// Negates self, overflowing if this is equal to the minimum value.
///
/// Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
/// happened. If `self` is the minimum value (e.g., [`i32::MIN`] for values of type [`i32`]), then the
/// minimum value will be returned again and `true` will be returned for an overflow happening.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2i16.overflowing_neg(), (-2, false));"]
#[doc = "assert_eq!(i16::MIN.overflowing_neg(), (i16::MIN, true));"]
/// ```
#[inline]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[allow(unused_attributes)]
pub const fn overflowing_neg(self) -> (Self, bool) {
if intrinsics::unlikely(self == Self::MIN) {
(Self::MIN, true)
} else { (-self, false) }
}
/// Shifts self left by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
/// value was larger than or equal to the number of bits. If the shift value is too large, then value is
/// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1i16.overflowing_shl(4), (0x10, false));"]
/// assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));
#[doc = "assert_eq!(0x10i16.overflowing_shl(15), (0, false));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shl(rhs), rhs >= Self::BITS)
}
/// Shifts self right by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
/// value was larger than or equal to the number of bits. If the shift value is too large, then value is
/// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10i16.overflowing_shr(4), (0x1, false));"]
/// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shr(rhs), rhs >= Self::BITS)
}
/// Computes the absolute value of `self`.
///
/// Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
/// happened. If self is the minimum value
#[doc = "(e.g., [`i16::MIN`] for values of type [`i16`]),"]
/// then the minimum value will be returned again and true will be returned
/// for an overflow happening.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i16.overflowing_abs(), (10, false));"]
#[doc = "assert_eq!((-10i16).overflowing_abs(), (10, false));"]
#[doc = "assert_eq!((i16::MIN).overflowing_abs(), (i16::MIN, true));"]
/// ```
#[stable(feature = "no_panic_abs", since = "1.13.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_abs(self) -> (Self, bool) {
(self.wrapping_abs(), self == Self::MIN)
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// Returns a tuple of the exponentiation along with a bool indicating
/// whether an overflow happened.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3i16.overflowing_pow(4), (81, false));"]
#[doc = "assert_eq!(0_i16.overflowing_pow(0), (1, false));"]
/// assert_eq!(3i8.overflowing_pow(5), (-13, true));
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
let mut base = self;
let mut acc: Self = 1;
let mut overflow = false;
let mut tmp_overflow;
if intrinsics::is_val_statically_known(base) &&
base.unsigned_abs().is_power_of_two() {
let k = base.unsigned_abs().ilog2();
let Some(shift) = k.checked_mul(exp) else { return (0, true) };
let base: Self = if base < 0 && (exp % 2) != 0 { -1 } else { 1 };
return (base.unbounded_shl(shift), base.shl_exact(shift).is_none());
}
if exp == 0 { return (1, false); }
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 {
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
}
exp /= 2;
(base, tmp_overflow) = base.overflowing_mul(base);
overflow |= tmp_overflow;
}
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
return (acc, overflow);
}
loop {
if (exp & 1) == 1 {
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
if exp == 1 { return (acc, overflow); }
}
exp /= 2;
(base, tmp_overflow) = base.overflowing_mul(base);
overflow |= tmp_overflow;
}
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// # Examples
///
/// ```
#[doc = "let x: i16 = 2; // or any other integer type"]
///
/// assert_eq!(x.pow(5), 32);
#[doc = "assert_eq!(0_i16.pow(0), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn pow(self, exp: u32) -> Self {
if intrinsics::overflow_checks() {
self.strict_pow(exp)
} else { self.wrapping_pow(exp) }
}
/// Returns the integer square root of the number, rounded down.
///
/// This function returns the **principal (non-negative) square root**.
/// For a given number `n`, although both `x` and `-x` satisfy x<sup>2</sup> = n,
/// this function always returns the non-negative value.
///
/// # Panics
///
/// This function will panic if `self` is negative.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i16.isqrt(), 3);"]
/// ```
#[stable(feature = "isqrt", since = "1.84.0")]
#[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn isqrt(self) -> Self {
match self.checked_isqrt() {
Some(sqrt) => sqrt,
None => imp::int_sqrt::panic_for_negative_argument(),
}
}
/// Calculates the quotient of Euclidean division of `self` by `rhs`.
///
/// This computes the integer `q` such that `self = q * rhs + r`, with
/// `r = self.rem_euclid(rhs)` and `0 <= r < abs(rhs)`.
///
/// In other words, the result is `self / rhs` rounded to the integer `q`
/// such that `self >= q * rhs`.
/// If `self > 0`, this is equal to rounding towards zero (the default in Rust);
/// if `self < 0`, this is equal to rounding away from zero (towards +/- infinity).
/// If `rhs > 0`, this is equal to rounding towards -infinity;
/// if `rhs < 0`, this is equal to rounding towards +infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero or if `self` is [`Self::MIN`]
/// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
///
/// # Examples
///
/// ```
#[doc = "let a: i16 = 7; // or any other integer type"]
/// let b = 4;
///
/// assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
/// assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
/// assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
/// assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_euclid(self, rhs: Self) -> Self {
let q = self / rhs;
if self % rhs < 0 { return if rhs > 0 { q - 1 } else { q + 1 } }
q
}
/// Calculates the least nonnegative remainder of `self` when
/// divided by `rhs`.
///
/// This is done as if by the Euclidean division algorithm -- given
/// `r = self.rem_euclid(rhs)`, the result satisfies
/// `self = rhs * self.div_euclid(rhs) + r` and `0 <= r < abs(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero or if `self` is [`Self::MIN`] and
/// `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
///
/// # Examples
///
/// ```
#[doc = "let a: i16 = 7; // or any other integer type"]
/// let b = 4;
///
/// assert_eq!(a.rem_euclid(b), 3);
/// assert_eq!((-a).rem_euclid(b), 1);
/// assert_eq!(a.rem_euclid(-b), 3);
/// assert_eq!((-a).rem_euclid(-b), 1);
/// ```
///
/// This will panic:
/// ```should_panic
#[doc = "let _ = i16::MIN.rem_euclid(-1);"]
/// ```
#[doc(alias = "modulo", alias = "mod")]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn rem_euclid(self, rhs: Self) -> Self {
let r = self % rhs;
if r < 0 { r.wrapping_add(rhs.wrapping_abs()) } else { r }
}
/// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero or if `self` is [`Self::MIN`]
/// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "let a: i16 = 8;"]
/// let b = 3;
///
/// assert_eq!(a.div_floor(b), 2);
/// assert_eq!(a.div_floor(-b), -3);
/// assert_eq!((-a).div_floor(b), -3);
/// assert_eq!((-a).div_floor(-b), 2);
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_floor(self, rhs: Self) -> Self {
let d = self / rhs;
let r = self % rhs;
let correction = (self ^ rhs) >> (Self::BITS - 1);
if r != 0 { d + correction } else { d }
}
/// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero or if `self` is [`Self::MIN`]
/// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "let a: i16 = 8;"]
/// let b = 3;
///
/// assert_eq!(a.div_ceil(b), 3);
/// assert_eq!(a.div_ceil(-b), -2);
/// assert_eq!((-a).div_ceil(b), -2);
/// assert_eq!((-a).div_ceil(-b), 3);
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_ceil(self, rhs: Self) -> Self {
let d = self / rhs;
let r = self % rhs;
let correction = 1 + ((self ^ rhs) >> (Self::BITS - 1));
if r != 0 { d + correction } else { d }
}
/// If `rhs` is positive, calculates the smallest value greater than or
/// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
/// calculates the largest value less than or equal to `self` that is a
/// multiple of `rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// On overflow, this function will panic if overflow checks are enabled (default in debug
/// mode) and wrap if overflow checks are disabled (default in release mode).
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "assert_eq!(16_i16.next_multiple_of(8), 16);"]
#[doc = "assert_eq!(23_i16.next_multiple_of(8), 24);"]
#[doc = "assert_eq!(16_i16.next_multiple_of(-8), 16);"]
#[doc = "assert_eq!(23_i16.next_multiple_of(-8), 16);"]
#[doc = "assert_eq!((-16_i16).next_multiple_of(8), -16);"]
#[doc = "assert_eq!((-23_i16).next_multiple_of(8), -16);"]
#[doc = "assert_eq!((-16_i16).next_multiple_of(-8), -16);"]
#[doc = "assert_eq!((-23_i16).next_multiple_of(-8), -24);"]
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_multiple_of(self, rhs: Self) -> Self {
if rhs == -1 { return self; }
let r = self % rhs;
let m =
if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) { r + rhs } else { r };
if m == 0 { self } else { self + (rhs - m) }
}
/// If `rhs` is positive, calculates the smallest value greater than or
/// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
/// calculates the largest value less than or equal to `self` that is a
/// multiple of `rhs`. Returns `None` if `rhs` is zero or the operation
/// would result in overflow.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "assert_eq!(16_i16.checked_next_multiple_of(8), Some(16));"]
#[doc = "assert_eq!(23_i16.checked_next_multiple_of(8), Some(24));"]
#[doc = "assert_eq!(16_i16.checked_next_multiple_of(-8), Some(16));"]
#[doc = "assert_eq!(23_i16.checked_next_multiple_of(-8), Some(16));"]
#[doc = "assert_eq!((-16_i16).checked_next_multiple_of(8), Some(-16));"]
#[doc = "assert_eq!((-23_i16).checked_next_multiple_of(8), Some(-16));"]
#[doc = "assert_eq!((-16_i16).checked_next_multiple_of(-8), Some(-16));"]
#[doc = "assert_eq!((-23_i16).checked_next_multiple_of(-8), Some(-24));"]
#[doc = "assert_eq!(1_i16.checked_next_multiple_of(0), None);"]
#[doc = "assert_eq!(i16::MAX.checked_next_multiple_of(2), None);"]
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
if rhs == -1 { return Some(self); }
let r =
match self.checked_rem(rhs) { Some(x) => x, None => return None, };
let m =
if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) { r + rhs } else { r };
if m == 0 { Some(self) } else { self.checked_add(rhs - m) }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// This method might not be optimized owing to implementation details;
/// [`ilog2`][Self::ilog2] can produce results more efficiently for base 2,
/// and [`ilog10`](Self::ilog10) can produce results more efficiently for base 10.
///
/// # Panics
///
/// This function will panic if `self` is less than or equal to zero,
/// or if `base` is less than 2.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i16.ilog(5), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog(self, base: Self) -> u32 {
if !(base >= 2) {
{
crate::panicking::panic_fmt(format_args!("base of integer logarithm must be at least 2"));
}
};
if let Some(log) = self.checked_ilog(base) {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the base 2 logarithm of the number, rounded down.
///
/// # Panics
///
/// This function will panic if `self` is less than or equal to zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2i16.ilog2(), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog2(self) -> u32 {
if let Some(log) = self.checked_ilog2() {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// # Panics
///
/// This function will panic if `self` is less than or equal to zero.
///
/// # Example
///
/// ```
#[doc = "assert_eq!(10i16.ilog10(), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog10(self) -> u32 {
if let Some(log) = self.checked_ilog10() {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// Returns `None` if the number is negative or zero, or if the base is not at least 2.
///
/// This method might not be optimized owing to implementation details;
/// `checked_ilog2` can produce results more efficiently for base 2, and
/// `checked_ilog10` can produce results more efficiently for base 10.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i16.checked_ilog(5), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog(self, base: Self) -> Option<u32> {
if self <= 0 || base <= 1 {
None
} else { (self as u16).checked_ilog(base as u16) }
}
/// Returns the base 2 logarithm of the number, rounded down.
///
/// Returns `None` if the number is negative or zero.
///
/// Note that for non-negative numbers, this is equivalent to
/// [`highest_one`](Self::highest_one).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2i16.checked_ilog2(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog2(self) -> Option<u32> {
if self <= 0 {
None
} else {
let log =
(Self::BITS - 1) -
unsafe { intrinsics::ctlz_nonzero(self) as u32 };
Some(log)
}
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// Returns `None` if the number is negative or zero.
///
/// # Example
///
/// ```
#[doc = "assert_eq!(10i16.checked_ilog10(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog10(self) -> Option<u32> {
imp::int_log10::i16(self as i16)
}
/// Computes the absolute value of `self`.
///
/// # Overflow behavior
///
/// The absolute value of
#[doc = "`i16::MIN`"]
/// cannot be represented as an
#[doc = "`i16`,"]
/// and attempting to calculate it will cause an overflow. This means
/// that code in debug mode will trigger a panic on this case and
/// optimized code will return
#[doc = "`i16::MIN`"]
/// without a panic. If you do not want this behavior, consider
/// using [`unsigned_abs`](Self::unsigned_abs) instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i16.abs(), 10);"]
#[doc = "assert_eq!((-10i16).abs(), 10);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[allow(unused_attributes)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn abs(self) -> Self {
if self.is_negative() { -self } else { self }
}
/// Computes the absolute difference between `self` and `other`.
///
/// This function always returns the correct answer without overflow or
/// panics by returning an unsigned integer.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i16.abs_diff(80), 20u16);"]
#[doc = "assert_eq!(100i16.abs_diff(110), 10u16);"]
#[doc = "assert_eq!((-100i16).abs_diff(80), 180u16);"]
#[doc = "assert_eq!((-100i16).abs_diff(-120), 20u16);"]
#[doc = "assert_eq!(i16::MIN.abs_diff(i16::MAX), u16::MAX);"]
/// ```
#[stable(feature = "int_abs_diff", since = "1.60.0")]
#[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn abs_diff(self, other: Self) -> u16 {
if self < other {
(other as u16).wrapping_sub(self as u16)
} else { (self as u16).wrapping_sub(other as u16) }
}
/// Returns a number representing sign of `self`.
///
/// - `0` if the number is zero
/// - `1` if the number is positive
/// - `-1` if the number is negative
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i16.signum(), 1);"]
#[doc = "assert_eq!(0i16.signum(), 0);"]
#[doc = "assert_eq!((-10i16).signum(), -1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_sign", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn signum(self) -> Self {
crate::intrinsics::three_way_compare(self, 0) as Self
}
/// Returns `true` if `self` is positive and `false` if the number is zero or
/// negative.
///
/// # Examples
///
/// ```
#[doc = "assert!(10i16.is_positive());"]
#[doc = "assert!(!(-10i16).is_positive());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[inline(always)]
pub const fn is_positive(self) -> bool { self > 0 }
/// Returns `true` if `self` is negative and `false` if the number is zero or
/// positive.
///
/// # Examples
///
/// ```
#[doc = "assert!((-10i16).is_negative());"]
#[doc = "assert!(!10i16.is_negative());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[inline(always)]
pub const fn is_negative(self) -> bool { self < 0 }
/// Returns the memory representation of this integer as a byte array in
/// big-endian (network) byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234i16.to_be_bytes();"]
#[doc = "assert_eq!(bytes, [0x12, 0x34]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
self.to_be().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// little-endian byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234i16.to_le_bytes();"]
#[doc = "assert_eq!(bytes, [0x34, 0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
self.to_le().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code
/// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
/// instead.
///
#[doc = ""]
///
/// [`to_be_bytes`]: Self::to_be_bytes
/// [`to_le_bytes`]: Self::to_le_bytes
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234i16.to_ne_bytes();"]
/// assert_eq!(
/// bytes,
/// if cfg!(target_endian = "big") {
#[doc = " [0x12, 0x34]"]
/// } else {
#[doc = " [0x34, 0x12]"]
/// }
/// );
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
unsafe { mem::transmute(self) }
}
/// Creates an integer value from its representation as a byte array in
/// big endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = i16::from_be_bytes([0x12, 0x34]);"]
#[doc = "assert_eq!(value, 0x1234);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_be_i16(input: &mut &[u8]) -> i16 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i16>());"]
/// *input = rest;
#[doc = " i16::from_be_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_be(Self::from_ne_bytes(bytes))
}
/// Creates an integer value from its representation as a byte array in
/// little endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = i16::from_le_bytes([0x34, 0x12]);"]
#[doc = "assert_eq!(value, 0x1234);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_le_i16(input: &mut &[u8]) -> i16 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i16>());"]
/// *input = rest;
#[doc = " i16::from_le_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_le(Self::from_ne_bytes(bytes))
}
/// Creates an integer value from its memory representation as a byte
/// array in native endianness.
///
/// As the target platform's native endianness is used, portable code
/// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
/// appropriate instead.
///
/// [`from_be_bytes`]: Self::from_be_bytes
/// [`from_le_bytes`]: Self::from_le_bytes
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = i16::from_ne_bytes(if cfg!(target_endian = \"big\") {"]
#[doc = " [0x12, 0x34]"]
/// } else {
#[doc = " [0x34, 0x12]"]
/// });
#[doc = "assert_eq!(value, 0x1234);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_ne_i16(input: &mut &[u8]) -> i16 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i16>());"]
/// *input = rest;
#[doc = " i16::from_ne_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use]
#[inline]
pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
unsafe { mem::transmute(bytes) }
}
/// New code should prefer to use
#[doc = "[`i16::MIN`] instead."]
///
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MIN` associated constant on this type")]
#[rustc_diagnostic_item = "i16_legacy_fn_min_value"]
pub const fn min_value() -> Self { Self::MIN }
/// New code should prefer to use
#[doc = "[`i16::MAX`] instead."]
///
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MAX` associated constant on this type")]
#[rustc_diagnostic_item = "i16_legacy_fn_max_value"]
pub const fn max_value() -> Self { Self::MAX }
/// Clamps this number to a symmetric range centred around zero.
///
/// The method clamps the number's magnitude (absolute value) to be at most `limit`.
///
/// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
/// explicit about the intent.
///
/// # Examples
///
/// ```
/// #![feature(clamp_magnitude)]
#[doc = "assert_eq!(120i16.clamp_magnitude(100), 100);"]
#[doc = "assert_eq!(-120i16.clamp_magnitude(100), -100);"]
#[doc = "assert_eq!(80i16.clamp_magnitude(100), 80);"]
#[doc = "assert_eq!(-80i16.clamp_magnitude(100), -80);"]
/// ```
#[must_use =
"this returns the clamped value and does not modify the original"]
#[unstable(feature = "clamp_magnitude", issue = "148519")]
#[inline]
pub fn clamp_magnitude(self, limit: u16) -> Self {
if let Ok(limit) = core::convert::TryInto::<i16>::try_into(limit) {
self.clamp(-limit, limit)
} else { self }
}
/// Truncate an integer to an integer of the same size or smaller, preserving the least
/// significant bits.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i8, 120i16.truncate());"]
#[doc = "assert_eq!(-120i8, (-120i16).truncate());"]
/// assert_eq!(120i8, 376i32.truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
/// instead of truncating.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i8, 120i16.saturating_truncate());"]
#[doc = "assert_eq!(-120i8, (-120i16).saturating_truncate());"]
/// assert_eq!(127i8, 376i32.saturating_truncate());
/// assert_eq!(-128i8, (-1000i32).saturating_truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn saturating_truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_saturating_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
/// is outside the bounds of the smaller type.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(Some(120i8), 120i16.checked_truncate());"]
#[doc = "assert_eq!(Some(-120i8), (-120i16).checked_truncate());"]
/// assert_eq!(None, 376i32.checked_truncate::<i8>());
/// assert_eq!(None, (-1000i32).checked_truncate::<i8>());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn checked_truncate<Target>(self) -> Option<Target> where
Self: [const] traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_checked_truncate(self)
}
/// Widen to an integer of the same size or larger, preserving its value.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i128, 120i8.widen());"]
#[doc = "assert_eq!(-120i128, (-120i8).widen());"]
/// ```
#[must_use =
"this returns the widened value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn widen<Target>(self) -> Target where Self: [const]
traits::WidenTarget<Target> {
traits::WidenTarget::internal_widen(self)
}
/// Converts `self` to the target integer type, saturating at the numeric
/// bounds instead of overflowing.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(i8::MAX, i16::MAX.saturating_cast());"]
#[doc = "assert_eq!(i8::MIN, i16::MIN.saturating_cast());"]
#[doc = "assert_eq!(42u8, 42i16.saturating_cast());"]
#[doc = "assert_eq!(0u8, (-42i16).saturating_cast());"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn saturating_cast<T: [const] BoundedCastFromInt<Self>>(self) -> T {
T::saturating_cast_from(self)
}
/// Converts `self` to the target integer type, wrapping around at the
/// boundary of the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(i16::MAX as i8, i16::MAX.wrapping_cast());"]
#[doc = "assert_eq!(i16::MIN as i8, i16::MIN.wrapping_cast());"]
#[doc = "assert_eq!(42u8, 42i16.wrapping_cast());"]
#[doc = "assert_eq!(u8::MAX - 41, (-42i16).wrapping_cast());"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn wrapping_cast<T: [const] BoundedCastFromInt<Self>>(self) -> T {
T::wrapping_cast_from(self)
}
/// Converts `self` to the target integer type, returning `None` if the value
/// is not representable by the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(Some(42u8), 42i16.checked_cast());"]
#[doc = "assert_eq!((-42i16).checked_cast::<u8>(), None);"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn checked_cast<T: [const] CheckedCastFromInt<Self>>(self)
-> Option<T> {
T::checked_cast_from(self)
}
/// Converts `self` to the target integer type, panicking if the value
/// is not representable by the target type.
///
/// # Panics
///
/// This function will panic if the value is not representable by the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(42u8, 42i16.strict_cast());"]
/// ```
///
/// The following will panic:
///
/// ```should_panic
/// #![feature(integer_casts)]
#[doc = "let _ = (-42i16).strict_cast::<u8>();"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
#[track_caller]
pub const fn strict_cast<T: [const] CheckedCastFromInt<Self>>(self) -> T {
T::strict_cast_from(self)
}
/// Converts `self` to the target integer type, assuming the value is
/// representable by the target type.
///
/// # Safety
///
/// This results in undefined behavior if the integer value of `self` is bigger than `T::MAX`,
/// or smaller than `T::MIN`, where `T` is the target type.
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const unsafe fn unchecked_cast<T: [const] CheckedCastFromInt<Self>>(self)
-> T {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(in_bounds: bool) {
if !in_bounds {
let msg =
"unsafe precondition(s) violated: i16::unchecked_cast must fit in the target type\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check({
let cast_val = self.checked_cast::<T>();
let ret = cast_val.is_some();
core::mem::forget(cast_val);
ret
});
}
};
unsafe { T::unchecked_cast_from(self) }
}int_impl! {
402Self = i16,
403 ActualT = i16,
404 UnsignedT = u16,
405 BITS = 16,
406 BITS_MINUS_ONE = 15,
407 Min = -32768,
408 Max = 32767,
409 rot = 4,
410 rot_op = "-0x5ffd",
411 rot_result = "0x3a",
412 swap_op = "0x1234",
413 swapped = "0x3412",
414 reversed = "0x2c48",
415 le_bytes = "[0x34, 0x12]",
416 be_bytes = "[0x12, 0x34]",
417 to_xe_bytes_doc = "",
418 from_xe_bytes_doc = "",
419 bound_condition = "",
420 }421/// Calculates the midpoint (average) between `self` and `rhs`.
///
/// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
/// sufficiently-large signed integral type. This implies that the result is
/// always rounded towards zero and that no overflow will ever occur.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0i16.midpoint(4), 2);"]
#[doc = "assert_eq!((-1i16).midpoint(2), 0);"]
#[doc = "assert_eq!((-7i16).midpoint(0), -3);"]
#[doc = "assert_eq!(0i16.midpoint(-7), -3);"]
#[doc = "assert_eq!(0i16.midpoint(7), 3);"]
/// ```
#[stable(feature = "num_midpoint_signed", since = "1.87.0")]
#[rustc_const_stable(feature = "num_midpoint_signed", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[doc(alias = "average_floor")]
#[doc(alias = "average_ceil")]
#[doc(alias = "average")]
#[inline]
pub const fn midpoint(self, rhs: i16) -> i16 {
((self as i32 + rhs as i32) / 2) as i16
}midpoint_impl! { i16, i32, signed }422/// Widening multiplication. Computes `self * rhs`, widening to a larger integer.
///
/// The returned value is always exact and can never overflow.
///
/// Note that this method is semantically equivalent to [`carrying_mul`] with a
/// carry of zero, with the latter instead returning a tuple denoting the low and
/// high parts of the result. Consider using it instead if you need
/// interoperability with other big int helper functions, or if this method isn't
/// available for a given type.
///
/// [`carrying_mul`]: Self::carrying_mul
///
/// # Examples
///
/// ```
/// #![feature(widening_mul)]
///
#[doc = "assert_eq!(i16::MAX.widening_mul(0_i16), 0);"]
#[doc =
"assert_eq!(i16::MAX.widening_mul(i16::MAX), i16::MAX as i32 * i16::MAX as i32);"]
/// ```
#[unstable(feature = "widening_mul", issue = "152016")]
#[rustc_const_unstable(feature = "widening_mul", issue = "152016")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn widening_mul(self, rhs: Self) -> i32 { self as i32 * rhs as i32 }widening_mul_impl! { i16, i32 }423}
424425impl i32 {
426/// The smallest value that can be represented by this integer type
#[doc = "(−2<sup>31</sup>)."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i32::MIN, -2147483648);"]
/// ```
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MIN: Self = !Self::MAX;
/// The largest value that can be represented by this integer type
#[doc = "(2<sup>31</sup> − 1)."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i32::MAX, 2147483647);"]
/// ```
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MAX: Self = (<u32>::MAX >> 1) as Self;
/// The size of this integer type in bits.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i32::BITS, 32);"]
/// ```
#[stable(feature = "int_bits_const", since = "1.53.0")]
pub const BITS: u32 = <u32>::BITS;
/// Returns the number of ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 0b100_0000i32;"]
///
/// assert_eq!(n.count_ones(), 1);
/// ```
///
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[doc(alias = "popcount")]
#[doc(alias = "popcnt")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn count_ones(self) -> u32 { (self as u32).count_ones() }
/// Returns the number of zeros in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i32::MAX.count_zeros(), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn count_zeros(self) -> u32 { (!self).count_ones() }
/// Returns the number of leading zeros in the binary representation of `self`.
///
/// Depending on what you're doing with the value, you might also be interested in the
/// [`ilog2`] function which returns a consistent number, even if the type widens.
///
/// # Examples
///
/// ```
#[doc = "let n = -1i32;"]
///
/// assert_eq!(n.leading_zeros(), 0);
/// ```
#[doc = "[`ilog2`]: i32::ilog2"]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn leading_zeros(self) -> u32 { (self as u32).leading_zeros() }
/// Returns the number of trailing zeros in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = -4i32;"]
///
/// assert_eq!(n.trailing_zeros(), 2);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn trailing_zeros(self) -> u32 { (self as u32).trailing_zeros() }
/// Returns the number of leading ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = -1i32;"]
///
#[doc = "assert_eq!(n.leading_ones(), 32);"]
/// ```
#[stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn leading_ones(self) -> u32 { (self as u32).leading_ones() }
/// Returns the number of trailing ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 3i32;"]
///
/// assert_eq!(n.trailing_ones(), 2);
/// ```
#[stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn trailing_ones(self) -> u32 { (self as u32).trailing_ones() }
/// Returns `self` with only the most significant bit set, or `0` if
/// the input is `0`.
///
/// # Examples
///
/// ```
#[doc = "let n: i32 = 0b_01100100;"]
///
/// assert_eq!(n.isolate_highest_one(), 0b_01000000);
#[doc = "assert_eq!(0_i32.isolate_highest_one(), 0);"]
/// ```
#[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn isolate_highest_one(self) -> Self {
self &
(((1 as i32) << (<i32>::BITS - 1)).wrapping_shr(self.leading_zeros()))
}
/// Returns `self` with only the least significant bit set, or `0` if
/// the input is `0`.
///
/// # Examples
///
/// ```
#[doc = "let n: i32 = 0b_01100100;"]
///
/// assert_eq!(n.isolate_lowest_one(), 0b_00000100);
#[doc = "assert_eq!(0_i32.isolate_lowest_one(), 0);"]
/// ```
#[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn isolate_lowest_one(self) -> Self { self & self.wrapping_neg() }
/// Returns the index of the highest bit set to one in `self`, or `None`
/// if `self` is `0`.
///
/// Note that for non-negative numbers, this is equivalent to
/// [`checked_ilog2`](Self::checked_ilog2).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0b0_i32.highest_one(), None);"]
#[doc = "assert_eq!(0b1_i32.highest_one(), Some(0));"]
#[doc = "assert_eq!(0b1_0000_i32.highest_one(), Some(4));"]
#[doc = "assert_eq!(0b1_1111_i32.highest_one(), Some(4));"]
/// ```
#[stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn highest_one(self) -> Option<u32> { (self as u32).highest_one() }
/// Returns the index of the lowest bit set to one in `self`, or `None`
/// if `self` is `0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0b0_i32.lowest_one(), None);"]
#[doc = "assert_eq!(0b1_i32.lowest_one(), Some(0));"]
#[doc = "assert_eq!(0b1_0000_i32.lowest_one(), Some(4));"]
#[doc = "assert_eq!(0b1_1111_i32.lowest_one(), Some(0));"]
/// ```
#[stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn lowest_one(self) -> Option<u32> { (self as u32).lowest_one() }
/// Returns the bit pattern of `self` reinterpreted as an unsigned integer of the same size.
///
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
/// the same.
///
/// # Examples
///
/// ```
#[doc = "let n = -1i32;"]
///
#[doc = "assert_eq!(n.cast_unsigned(), u32::MAX);"]
/// ```
#[stable(feature = "integer_sign_cast", since = "1.87.0")]
#[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_unsigned(self) -> u32 { self as u32 }
/// Saturating conversion of `self` to an unsigned integer of the same size.
///
/// Negative values are clamped to `0`.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`checked_cast_unsigned`](Self::checked_cast_unsigned),
/// or [`strict_cast_unsigned`](Self::strict_cast_unsigned).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = i32::MIN;"]
///
#[doc = "assert_eq!(n.saturating_cast_unsigned(), 0u32);"]
#[doc = "assert_eq!(64i32.saturating_cast_unsigned(), 64u32);"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_cast_unsigned(self) -> u32 {
if self >= 0 { self.cast_unsigned() } else { 0 }
}
/// Checked conversion of `self` to an unsigned integer of the same size,
/// returning `None` if `self` is negative.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`saturating_cast_unsigned`](Self::saturating_cast_unsigned),
/// or [`strict_cast_unsigned`](Self::strict_cast_unsigned).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = i32::MIN;"]
///
#[doc = "assert_eq!(n.checked_cast_unsigned(), None);"]
#[doc = "assert_eq!(64i32.checked_cast_unsigned(), Some(64u32));"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn checked_cast_unsigned(self) -> Option<u32> {
if self >= 0 { Some(self.cast_unsigned()) } else { None }
}
/// Strict conversion of `self` to an unsigned integer of the same size,
/// which panics if `self` is negative.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`checked_cast_unsigned`](Self::checked_cast_unsigned),
/// or [`saturating_cast_unsigned`](Self::saturating_cast_unsigned).
///
/// # Examples
///
/// ```should_panic
/// #![feature(integer_cast_extras)]
#[doc = "let _ = i32::MIN.strict_cast_unsigned();"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_cast_unsigned(self) -> u32 {
match self.checked_cast_unsigned() {
Some(n) => n,
None => imp::overflow_panic::cast_integer(),
}
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `<<` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x10000b3i32;"]
#[doc = "let m = 0xb301;"]
///
#[doc = "assert_eq!(n.rotate_left(8), m);"]
#[doc = "assert_eq!(n.rotate_left(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn rotate_left(self, n: u32) -> Self {
(self as u32).rotate_left(n) as Self
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `>>` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0xb301i32;"]
#[doc = "let m = 0x10000b3;"]
///
#[doc = "assert_eq!(n.rotate_right(8), m);"]
#[doc = "assert_eq!(n.rotate_right(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn rotate_right(self, n: u32) -> Self {
(self as u32).rotate_right(n) as Self
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x12345678i32;"]
///
/// let m = n.swap_bytes();
///
#[doc = "assert_eq!(m, 0x78563412);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn swap_bytes(self) -> Self { (self as u32).swap_bytes() as Self }
/// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
/// second least-significant bit becomes second most-significant bit, etc.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x12345678i32;"]
/// let m = n.reverse_bits();
///
#[doc = "assert_eq!(m, 0x1e6a2c48);"]
#[doc = "assert_eq!(0, 0i32.reverse_bits());"]
/// ```
#[stable(feature = "reverse_bits", since = "1.37.0")]
#[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn reverse_bits(self) -> Self {
(self as u32).reverse_bits() as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are swapped.
///
/// See also [from_be_bytes()](Self::from_be_bytes).
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai32;"]
///
/// if cfg!(target_endian = "big") {
#[doc = " assert_eq!(i32::from_be(n), n)"]
/// } else {
#[doc = " assert_eq!(i32::from_be(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn from_be(x: Self) -> Self { x.swap_bytes() }
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are swapped.
///
/// See also [from_le_bytes()](Self::from_le_bytes).
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai32;"]
///
/// if cfg!(target_endian = "little") {
#[doc = " assert_eq!(i32::from_le(n), n)"]
/// } else {
#[doc = " assert_eq!(i32::from_le(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn from_le(x: Self) -> Self { x }
/// Swaps bytes of `self` on little endian targets.
///
/// On big endian this is a no-op.
///
/// The returned value has the same type as `self`, and will be interpreted
/// as (a potentially different) value of a native-endian
#[doc = "`i32`."]
///
/// See [`to_be_bytes()`](Self::to_be_bytes) for a type-safe alternative.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai32;"]
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be(self) -> Self { self.swap_bytes() }
/// Swaps bytes of `self` on big endian targets.
///
/// On little endian this is a no-op.
///
/// The returned value has the same type as `self`, and will be interpreted
/// as (a potentially different) value of a native-endian
#[doc = "`i32`."]
///
/// See [`to_le_bytes()`](Self::to_le_bytes) for a type-safe alternative.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai32;"]
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le(self) -> Self { self }
/// Checked integer addition. Computes `self + rhs`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i32::MAX - 2).checked_add(1), Some(i32::MAX - 1));"]
#[doc = "assert_eq!((i32::MAX - 2).checked_add(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_add(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer addition. Computes `self + rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i32::MAX - 2).strict_add(1), i32::MAX - 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i32::MAX - 2).strict_add(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_add(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Unchecked integer addition. Computes `self + rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_add(y)` is semantically equivalent to calling
/// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_add`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self + rhs > i32::MAX` or `self + rhs < i32::MIN`,"]
/// i.e. when [`checked_add`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_add`]: i32::checked_add"]
#[doc = "[`wrapping_add`]: i32::wrapping_add"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i32, rhs: i32) {
if !!lhs.overflowing_add(rhs).1 {
let msg =
"unsafe precondition(s) violated: i32::unchecked_add cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_add(self, rhs) }
}
/// Checked addition with an unsigned integer. Computes `self + rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i32.checked_add_unsigned(2), Some(3));"]
#[doc = "assert_eq!((i32::MAX - 2).checked_add_unsigned(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add_unsigned(self, rhs: u32) -> Option<Self> {
let (a, b) = self.overflowing_add_unsigned(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict addition with an unsigned integer. Computes `self + rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i32.strict_add_unsigned(2), 3);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i32::MAX - 2).strict_add_unsigned(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add_unsigned(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_add_unsigned(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Checked integer subtraction. Computes `self - rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i32::MIN + 2).checked_sub(1), Some(i32::MIN + 1));"]
#[doc = "assert_eq!((i32::MIN + 2).checked_sub(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_sub(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer subtraction. Computes `self - rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i32::MIN + 2).strict_sub(1), i32::MIN + 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i32::MIN + 2).strict_sub(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_sub(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
/// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_sub`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self - rhs > i32::MAX` or `self - rhs < i32::MIN`,"]
/// i.e. when [`checked_sub`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_sub`]: i32::checked_sub"]
#[doc = "[`wrapping_sub`]: i32::wrapping_sub"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i32, rhs: i32) {
if !!lhs.overflowing_sub(rhs).1 {
let msg =
"unsafe precondition(s) violated: i32::unchecked_sub cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_sub(self, rhs) }
}
/// Checked subtraction with an unsigned integer. Computes `self - rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i32.checked_sub_unsigned(2), Some(-1));"]
#[doc = "assert_eq!((i32::MIN + 2).checked_sub_unsigned(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub_unsigned(self, rhs: u32) -> Option<Self> {
let (a, b) = self.overflowing_sub_unsigned(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict subtraction with an unsigned integer. Computes `self - rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i32.strict_sub_unsigned(2), -1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i32::MIN + 2).strict_sub_unsigned(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub_unsigned(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_sub_unsigned(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Checked integer multiplication. Computes `self * rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i32::MAX.checked_mul(1), Some(i32::MAX));"]
#[doc = "assert_eq!(i32::MAX.checked_mul(2), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer multiplication. Computes `self * rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i32::MAX.strict_mul(1), i32::MAX);"]
/// ```
///
/// The following panics because of overflow:
///
/// ``` should_panic
#[doc = "let _ = i32::MAX.strict_mul(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_mul(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_mul(rhs);
if b { imp::overflow_panic::mul() } else { a }
}
/// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
/// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_mul`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self * rhs > i32::MAX` or `self * rhs < i32::MIN`,"]
/// i.e. when [`checked_mul`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_mul`]: i32::checked_mul"]
#[doc = "[`wrapping_mul`]: i32::wrapping_mul"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i32, rhs: i32) {
if !!lhs.overflowing_mul(rhs).1 {
let msg =
"unsafe precondition(s) violated: i32::unchecked_mul cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_mul(self, rhs) }
}
/// Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
/// or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i32::MIN + 1).checked_div(-1), Some(2147483647));"]
#[doc = "assert_eq!(i32::MIN.checked_div(-1), None);"]
#[doc = "assert_eq!((1i32).checked_div(0), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1)))
{
None
} else { Some(unsafe { intrinsics::unchecked_div(self, rhs) }) }
}
/// Strict integer division. Computes `self / rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is when one divides `MIN / -1` on a signed type (where
/// [`MIN`](Self::MIN) is the negative minimal value for the type); the result of this is `-MIN`, a positive value
/// that is too large to represent in the type.
///
/// Note that this is equivalent to normal division: `MIN / -1` will also panic both in
/// debug and release builds.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i32::MIN + 1).strict_div(-1), 2147483647);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i32::MIN.strict_div(-1);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1i32).strict_div(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_div(self, rhs: Self) -> Self { self / rhs }
/// Checked Euclidean division. Computes `self.div_euclid(rhs)`,
/// returning `None` if `rhs == 0` or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc =
"assert_eq!((i32::MIN + 1).checked_div_euclid(-1), Some(2147483647));"]
#[doc = "assert_eq!(i32::MIN.checked_div_euclid(-1), None);"]
#[doc = "assert_eq!((1i32).checked_div_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) {
None
} else { Some(self.div_euclid(rhs)) }
}
/// Strict Euclidean division. Computes `self.div_euclid(rhs)`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is when one divides `MIN / -1` on a signed type (where
/// [`MIN`](Self::MIN) is the negative minimal value for the type); the result of this is `-MIN`, a positive value
/// that is too large to represent in the type.
///
/// Note that this is equivalent to `div_euclid`: `MIN.div_euclid(-1)` will also panic both
/// in debug and release builds.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i32::MIN + 1).strict_div_euclid(-1), 2147483647);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i32::MIN.strict_div_euclid(-1);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1i32).strict_div_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_div_euclid(self, rhs: Self) -> Self {
self.div_euclid(rhs)
}
/// Checked integer division without remainder. Computes `self / rhs`,
/// returning `None` if `rhs == 0`, the division results in overflow,
/// or `self % rhs != 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!((i32::MIN + 1).checked_div_exact(-1), Some(2147483647));"]
#[doc = "assert_eq!((-5i32).checked_div_exact(2), None);"]
#[doc = "assert_eq!(i32::MIN.checked_div_exact(-1), None);"]
#[doc = "assert_eq!((1i32).checked_div_exact(0), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_exact(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1)))
{
None
} else {
unsafe {
if intrinsics::unlikely(intrinsics::unchecked_rem(self, rhs) != 0)
{
None
} else { Some(intrinsics::exact_div(self, rhs)) }
}
}
}
/// Integer division without remainder. Computes `self / rhs`, returning `None` if `self % rhs != 0`.
///
/// # Panics
///
/// This function will panic if `rhs == 0`.
///
/// ## Overflow behavior
///
/// On overflow, this function will panic if overflow checks are enabled (default in debug
/// mode) and wrap if overflow checks are disabled (default in release mode).
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64i32.div_exact(2), Some(32));"]
#[doc = "assert_eq!(64i32.div_exact(32), Some(2));"]
#[doc = "assert_eq!((i32::MIN + 1).div_exact(-1), Some(2147483647));"]
#[doc = "assert_eq!(65i32.div_exact(2), None);"]
/// ```
/// ```should_panic
/// #![feature(exact_div)]
#[doc = "let _ = 64i32.div_exact(0);"]
/// ```
/// ```should_panic
/// #![feature(exact_div)]
#[doc = "let _ = i32::MIN.div_exact(-1);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn div_exact(self, rhs: Self) -> Option<Self> {
if self % rhs != 0 { None } else { Some(self / rhs) }
}
/// Unchecked integer division without remainder. Computes `self / rhs`.
///
/// # Safety
///
/// This results in undefined behavior when `rhs == 0`, `self % rhs != 0`, or
#[doc = "`self == i32::MIN && rhs == -1`,"]
/// i.e. when [`checked_div_exact`](Self::checked_div_exact) would return `None`.
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_div_exact(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i32, rhs: i32) {
if !(rhs != 0 && lhs % rhs == 0 &&
(lhs != <i32>::MIN || rhs != -1)) {
let msg =
"unsafe precondition(s) violated: i32::unchecked_div_exact cannot overflow, divide by zero, or leave a remainder\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::exact_div(self, rhs) }
}
/// Checked integer remainder. Computes `self % rhs`, returning `None` if
/// `rhs == 0` or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i32.checked_rem(2), Some(1));"]
#[doc = "assert_eq!(5i32.checked_rem(0), None);"]
#[doc = "assert_eq!(i32::MIN.checked_rem(-1), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1)))
{
None
} else { Some(unsafe { intrinsics::unchecked_rem(self, rhs) }) }
}
/// Strict integer remainder. Computes `self % rhs`, panicking if
/// the division results in overflow.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is `x % y` for `MIN / -1` on a
/// signed type (where [`MIN`](Self::MIN) is the negative minimal value), which is invalid due to implementation artifacts.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i32.strict_rem(2), 1);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5i32.strict_rem(0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i32::MIN.strict_rem(-1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_rem(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_rem(rhs);
if b { imp::overflow_panic::rem() } else { a }
}
/// Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
/// if `rhs == 0` or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i32.checked_rem_euclid(2), Some(1));"]
#[doc = "assert_eq!(5i32.checked_rem_euclid(0), None);"]
#[doc = "assert_eq!(i32::MIN.checked_rem_euclid(-1), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) {
None
} else { Some(self.rem_euclid(rhs)) }
}
/// Strict Euclidean remainder. Computes `self.rem_euclid(rhs)`, panicking if
/// the division results in overflow.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is `x % y` for `MIN / -1` on a
/// signed type (where [`MIN`](Self::MIN) is the negative minimal value), which is invalid due to implementation artifacts.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i32.strict_rem_euclid(2), 1);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5i32.strict_rem_euclid(0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i32::MIN.strict_rem_euclid(-1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_rem_euclid(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_rem_euclid(rhs);
if b { imp::overflow_panic::rem() } else { a }
}
/// Checked negation. Computes `-self`, returning `None` if `self == MIN`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i32.checked_neg(), Some(-5));"]
#[doc = "assert_eq!(i32::MIN.checked_neg(), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_neg(self) -> Option<Self> {
let (a, b) = self.overflowing_neg();
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Unchecked negation. Computes `-self`, assuming overflow cannot occur.
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self == i32::MIN`,"]
/// i.e. when [`checked_neg`] would return `None`.
///
#[doc = "[`checked_neg`]: i32::checked_neg"]
#[stable(feature = "unchecked_neg", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_neg", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_neg(self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i32) {
if !!lhs.overflowing_neg().1 {
let msg =
"unsafe precondition(s) violated: i32::unchecked_neg cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self);
}
};
unsafe { intrinsics::unchecked_sub(0, self) }
}
/// Strict negation. Computes `-self`, panicking if `self == MIN`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i32.strict_neg(), -5);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i32::MIN.strict_neg();"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_neg(self) -> Self {
let (a, b) = self.overflowing_neg();
if b { imp::overflow_panic::neg() } else { a }
}
/// Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
/// than or equal to the number of bits in `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1i32.checked_shl(4), Some(0x10));"]
#[doc = "assert_eq!(0x1i32.checked_shl(129), None);"]
#[doc = "assert_eq!(0x10i32.checked_shl(31), Some(0));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
if rhs < Self::BITS {
Some(unsafe { self.unchecked_shl(rhs) })
} else { None }
}
/// Strict shift left. Computes `self << rhs`, panicking if `rhs` is larger
/// than or equal to the number of bits in `self`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1i32.strict_shl(4), 0x10);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0x1i32.strict_shl(129);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_shl(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_shl(rhs);
if b { imp::overflow_panic::shl() } else { a }
}
/// Unchecked shift left. Computes `self << rhs`, assuming that
/// `rhs` is less than the number of bits in `self`.
///
/// # Safety
///
/// This results in undefined behavior if `rhs` is larger than
/// or equal to the number of bits in `self`,
/// i.e. when [`checked_shl`] would return `None`.
///
#[doc = "[`checked_shl`]: i32::checked_shl"]
#[stable(feature = "unchecked_shifts", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_shl(self, rhs: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(rhs: u32) {
if !(rhs < <i32>::BITS) {
let msg =
"unsafe precondition(s) violated: i32::unchecked_shl cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(rhs); }
};
unsafe { intrinsics::unchecked_shl(self, rhs) }
}
/// Unbounded shift left. Computes `self << rhs`, without bounding the value of `rhs`.
///
/// If `rhs` is larger or equal to the number of bits in `self`,
/// the entire value is shifted out, and `0` is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1_i32.unbounded_shl(4), 0x10);"]
#[doc = "assert_eq!(0x1_i32.unbounded_shl(129), 0);"]
#[doc = "assert_eq!(0b101_i32.unbounded_shl(0), 0b101);"]
#[doc = "assert_eq!(0b101_i32.unbounded_shl(1), 0b1010);"]
#[doc = "assert_eq!(0b101_i32.unbounded_shl(2), 0b10100);"]
#[doc = "assert_eq!(42_i32.unbounded_shl(32), 0);"]
#[doc = "assert_eq!(42_i32.unbounded_shl(1).unbounded_shl(31), 0);"]
#[doc = "assert_eq!((-13_i32).unbounded_shl(32), 0);"]
#[doc = "assert_eq!((-13_i32).unbounded_shl(1).unbounded_shl(31), 0);"]
/// ```
#[stable(feature = "unbounded_shifts", since = "1.87.0")]
#[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unbounded_shl(self, rhs: u32) -> i32 {
if rhs < Self::BITS { unsafe { self.unchecked_shl(rhs) } } else { 0 }
}
/// Exact shift left. Computes `self << rhs` as long as it can be reversed losslessly.
///
/// Returns `None` if any bits that would be shifted out differ from the resulting sign bit
/// or if `rhs` >=
#[doc = "`i32::BITS`."]
/// Otherwise, returns `Some(self << rhs)`.
///
/// # Examples
///
/// ```
/// #![feature(exact_bitshifts)]
///
#[doc = "assert_eq!(0x1i32.shl_exact(4), Some(0x10));"]
#[doc =
"assert_eq!(0x1i32.shl_exact(i32::BITS - 2), Some(1 << i32::BITS - 2));"]
#[doc = "assert_eq!(0x1i32.shl_exact(i32::BITS - 1), None);"]
#[doc =
"assert_eq!((-0x2i32).shl_exact(i32::BITS - 2), Some(-0x2 << i32::BITS - 2));"]
#[doc = "assert_eq!((-0x2i32).shl_exact(i32::BITS - 1), None);"]
/// ```
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn shl_exact(self, rhs: u32) -> Option<i32> {
if rhs < self.leading_zeros() || rhs < self.leading_ones() {
Some(unsafe { self.unchecked_shl(rhs) })
} else { None }
}
/// Unchecked exact shift left. Computes `self << rhs`, assuming the operation can be
/// losslessly reversed and `rhs` cannot be larger than
#[doc = "`i32::BITS`."]
///
/// # Safety
///
/// This results in undefined behavior when `rhs >= self.leading_zeros() && rhs >=
/// self.leading_ones()` i.e. when
#[doc = "[`i32::shl_exact`]"]
/// would return `None`.
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_shl_exact(self, rhs: u32) -> i32 {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(zeros: u32, ones: u32, rhs: u32) {
if !(rhs < zeros || rhs < ones) {
let msg =
"unsafe precondition(s) violated: i32::unchecked_shl_exact cannot shift out bits that would change the value of the first bit\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_library_ub() {
precondition_check(self.leading_zeros(), self.leading_ones(),
rhs);
}
};
unsafe { self.unchecked_shl(rhs) }
}
/// Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
/// larger than or equal to the number of bits in `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10i32.checked_shr(4), Some(0x1));"]
#[doc = "assert_eq!(0x10i32.checked_shr(128), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
if rhs < Self::BITS {
Some(unsafe { self.unchecked_shr(rhs) })
} else { None }
}
/// Strict shift right. Computes `self >> rhs`, panicking if `rhs` is
/// larger than or equal to the number of bits in `self`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10i32.strict_shr(4), 0x1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0x10i32.strict_shr(128);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_shr(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_shr(rhs);
if b { imp::overflow_panic::shr() } else { a }
}
/// Unchecked shift right. Computes `self >> rhs`, assuming that
/// `rhs` is less than the number of bits in `self`.
///
/// # Safety
///
/// This results in undefined behavior if `rhs` is larger than
/// or equal to the number of bits in `self`,
/// i.e. when [`checked_shr`] would return `None`.
///
#[doc = "[`checked_shr`]: i32::checked_shr"]
#[stable(feature = "unchecked_shifts", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_shr(self, rhs: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(rhs: u32) {
if !(rhs < <i32>::BITS) {
let msg =
"unsafe precondition(s) violated: i32::unchecked_shr cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(rhs); }
};
unsafe { intrinsics::unchecked_shr(self, rhs) }
}
/// Unbounded shift right. Computes `self >> rhs`, without bounding the value of `rhs`.
///
/// If `rhs` is larger or equal to the number of bits in `self`,
/// the entire value is shifted out, which yields `0` for a positive number,
/// and `-1` for a negative number.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10_i32.unbounded_shr(4), 0x1);"]
#[doc = "assert_eq!(0x10_i32.unbounded_shr(129), 0);"]
#[doc = "assert_eq!(i32::MIN.unbounded_shr(129), -1);"]
#[doc = "assert_eq!(0b1010_i32.unbounded_shr(0), 0b1010);"]
#[doc = "assert_eq!(0b1010_i32.unbounded_shr(1), 0b101);"]
#[doc = "assert_eq!(0b1010_i32.unbounded_shr(2), 0b10);"]
#[doc = "assert_eq!(42_i32.unbounded_shr(32), 0);"]
#[doc = "assert_eq!(42_i32.unbounded_shr(1).unbounded_shr(31), 0);"]
#[doc = "assert_eq!((-13_i32).unbounded_shr(32), -1);"]
#[doc = "assert_eq!((-13_i32).unbounded_shr(1).unbounded_shr(31), -1);"]
/// ```
#[stable(feature = "unbounded_shifts", since = "1.87.0")]
#[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unbounded_shr(self, rhs: u32) -> i32 {
if rhs < Self::BITS {
unsafe { self.unchecked_shr(rhs) }
} else { unsafe { self.unchecked_shr(Self::BITS - 1) } }
}
/// Exact shift right. Computes `self >> rhs` as long as it can be reversed losslessly.
///
/// Returns `None` if any non-zero bits would be shifted out or if `rhs` >=
#[doc = "`i32::BITS`."]
/// Otherwise, returns `Some(self >> rhs)`.
///
/// # Examples
///
/// ```
/// #![feature(exact_bitshifts)]
///
#[doc = "assert_eq!(0x10i32.shr_exact(4), Some(0x1));"]
#[doc = "assert_eq!(0x10i32.shr_exact(5), None);"]
/// ```
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn shr_exact(self, rhs: u32) -> Option<i32> {
if rhs <= self.trailing_zeros() && rhs < <i32>::BITS {
Some(unsafe { self.unchecked_shr(rhs) })
} else { None }
}
/// Unchecked exact shift right. Computes `self >> rhs`, assuming the operation can be
/// losslessly reversed and `rhs` cannot be larger than
#[doc = "`i32::BITS`."]
///
/// # Safety
///
/// This results in undefined behavior when `rhs > self.trailing_zeros() || rhs >=
#[doc = "i32::BITS`"]
/// i.e. when
#[doc = "[`i32::shr_exact`]"]
/// would return `None`.
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_shr_exact(self, rhs: u32) -> i32 {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(zeros: u32, bits: u32, rhs: u32) {
if !(rhs <= zeros && rhs < bits) {
let msg =
"unsafe precondition(s) violated: i32::unchecked_shr_exact cannot shift out non-zero bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_library_ub() {
precondition_check(self.trailing_zeros(), <i32>::BITS, rhs);
}
};
unsafe { self.unchecked_shr(rhs) }
}
/// Checked absolute value. Computes `self.abs()`, returning `None` if
/// `self == MIN`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-5i32).checked_abs(), Some(5));"]
#[doc = "assert_eq!(i32::MIN.checked_abs(), None);"]
/// ```
#[stable(feature = "no_panic_abs", since = "1.13.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_abs(self) -> Option<Self> {
if self.is_negative() { self.checked_neg() } else { Some(self) }
}
/// Strict absolute value. Computes `self.abs()`, panicking if
/// `self == MIN`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-5i32).strict_abs(), 5);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i32::MIN.strict_abs();"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_abs(self) -> Self {
if self.is_negative() { self.strict_neg() } else { self }
}
/// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(8i32.checked_pow(2), Some(64));"]
#[doc = "assert_eq!(0_i32.checked_pow(0), Some(1));"]
#[doc = "assert_eq!(i32::MAX.checked_pow(2), None);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
let mut base = self;
let mut acc: Self = 1;
if intrinsics::is_val_statically_known(base) &&
base.unsigned_abs().is_power_of_two() {
let k = base.unsigned_abs().ilog2();
let shift =
match k.checked_mul(exp) { Some(x) => x, None => return None, };
return if base < 0 && (exp % 2) == 1 {
(-1 as Self).shl_exact(shift)
} else { (1 as Self).shl_exact(shift) }
}
if exp == 0 { return Some(1); }
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 {
acc =
match acc.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
exp /= 2;
base =
match base.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
return acc.checked_mul(base);
}
loop {
if (exp & 1) == 1 {
acc =
match acc.checked_mul(base) {
Some(x) => x,
None => return None,
};
if exp == 1 { return Some(acc); }
}
exp /= 2;
base =
match base.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
}
/// Strict exponentiation. Computes `self.pow(exp)`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(8i32.strict_pow(2), 64);"]
#[doc = "assert_eq!(0_i32.strict_pow(0), 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i32::MAX.strict_pow(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) {
Some(x) => x,
None => imp::overflow_panic::pow(),
}
}
/// Returns the integer square root of the number, rounded down.
///
/// This function returns the **principal (non-negative) square root**.
/// For a given number `n`, although both `x` and `-x` satisfy x<sup>2</sup> = n,
/// this function always returns the non-negative value.
///
/// Returns `None` if `self` is negative.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i32.checked_isqrt(), Some(3));"]
/// ```
#[stable(feature = "isqrt", since = "1.84.0")]
#[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_isqrt(self) -> Option<Self> {
if self < 0 {
None
} else {
let result = self.cast_unsigned().isqrt().cast_signed();
unsafe {
const MAX_RESULT: i32 =
<i32>::MAX.cast_unsigned().isqrt().cast_signed();
crate::hint::assert_unchecked(result <= MAX_RESULT);
}
Some(result)
}
}
/// Saturating integer addition. Computes `self + rhs`, saturating at the numeric
/// bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i32.saturating_add(1), 101);"]
#[doc = "assert_eq!(i32::MAX.saturating_add(100), i32::MAX);"]
#[doc = "assert_eq!(i32::MIN.saturating_add(-1), i32::MIN);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_add(self, rhs: Self) -> Self {
intrinsics::saturating_add(self, rhs)
}
/// Saturating addition with an unsigned integer. Computes `self + rhs`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i32.saturating_add_unsigned(2), 3);"]
#[doc = "assert_eq!(i32::MAX.saturating_add_unsigned(100), i32::MAX);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_add_unsigned(self, rhs: u32) -> Self {
match self.checked_add_unsigned(rhs) { Some(x) => x, None => Self::MAX, }
}
/// Saturating integer subtraction. Computes `self - rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i32.saturating_sub(127), -27);"]
#[doc = "assert_eq!(i32::MIN.saturating_sub(100), i32::MIN);"]
#[doc = "assert_eq!(i32::MAX.saturating_sub(-1), i32::MAX);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_sub(self, rhs: Self) -> Self {
intrinsics::saturating_sub(self, rhs)
}
/// Saturating subtraction with an unsigned integer. Computes `self - rhs`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i32.saturating_sub_unsigned(127), -27);"]
#[doc = "assert_eq!(i32::MIN.saturating_sub_unsigned(100), i32::MIN);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_sub_unsigned(self, rhs: u32) -> Self {
match self.checked_sub_unsigned(rhs) { Some(x) => x, None => Self::MIN, }
}
/// Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
/// instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i32.saturating_neg(), -100);"]
#[doc = "assert_eq!((-100i32).saturating_neg(), 100);"]
#[doc = "assert_eq!(i32::MIN.saturating_neg(), i32::MAX);"]
#[doc = "assert_eq!(i32::MAX.saturating_neg(), i32::MIN + 1);"]
/// ```
#[stable(feature = "saturating_neg", since = "1.45.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_neg(self) -> Self {
intrinsics::saturating_sub(0, self)
}
/// Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
/// MIN` instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i32.saturating_abs(), 100);"]
#[doc = "assert_eq!((-100i32).saturating_abs(), 100);"]
#[doc = "assert_eq!(i32::MIN.saturating_abs(), i32::MAX);"]
#[doc = "assert_eq!((i32::MIN + 1).saturating_abs(), i32::MAX);"]
/// ```
#[stable(feature = "saturating_neg", since = "1.45.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_abs(self) -> Self {
if self.is_negative() { self.saturating_neg() } else { self }
}
/// Saturating integer multiplication. Computes `self * rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i32.saturating_mul(12), 120);"]
#[doc = "assert_eq!(i32::MAX.saturating_mul(10), i32::MAX);"]
#[doc = "assert_eq!(i32::MIN.saturating_mul(10), i32::MIN);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_mul(self, rhs: Self) -> Self {
match self.checked_mul(rhs) {
Some(x) => x,
None => if (self < 0) == (rhs < 0) { Self::MAX } else { Self::MIN },
}
}
/// Saturating integer division. Computes `self / rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i32.saturating_div(2), 2);"]
#[doc = "assert_eq!(i32::MAX.saturating_div(-1), i32::MIN + 1);"]
#[doc = "assert_eq!(i32::MIN.saturating_div(-1), i32::MAX);"]
///
/// ```
#[stable(feature = "saturating_div", since = "1.58.0")]
#[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_div(self, rhs: Self) -> Self {
match self.overflowing_div(rhs) {
(result, false) => result,
(_result, true) => Self::MAX,
}
}
/// Saturating integer exponentiation. Computes `self.pow(exp)`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-4i32).saturating_pow(3), -64);"]
#[doc = "assert_eq!(0_i32.saturating_pow(0), 1);"]
#[doc = "assert_eq!(i32::MIN.saturating_pow(2), i32::MAX);"]
#[doc = "assert_eq!(i32::MIN.saturating_pow(3), i32::MIN);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) {
Some(x) => x,
None if self < 0 && exp % 2 == 1 => Self::MIN,
None => Self::MAX,
}
}
/// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
/// boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i32.wrapping_add(27), 127);"]
#[doc = "assert_eq!(i32::MAX.wrapping_add(2), i32::MIN + 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_add(self, rhs: Self) -> Self {
intrinsics::wrapping_add(self, rhs)
}
/// Wrapping (modular) addition with an unsigned integer. Computes
/// `self + rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i32.wrapping_add_unsigned(27), 127);"]
#[doc = "assert_eq!(i32::MAX.wrapping_add_unsigned(2), i32::MIN + 1);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_add_unsigned(self, rhs: u32) -> Self {
self.wrapping_add(rhs as Self)
}
/// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
/// boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0i32.wrapping_sub(127), -127);"]
#[doc = "assert_eq!((-2i32).wrapping_sub(i32::MAX), i32::MAX);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_sub(self, rhs: Self) -> Self {
intrinsics::wrapping_sub(self, rhs)
}
/// Wrapping (modular) subtraction with an unsigned integer. Computes
/// `self - rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0i32.wrapping_sub_unsigned(127), -127);"]
#[doc = "assert_eq!((-2i32).wrapping_sub_unsigned(u32::MAX), -1);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_sub_unsigned(self, rhs: u32) -> Self {
self.wrapping_sub(rhs as Self)
}
/// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
/// the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i32.wrapping_mul(12), 120);"]
/// assert_eq!(11i8.wrapping_mul(12), -124);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_mul(self, rhs: Self) -> Self {
intrinsics::wrapping_mul(self, rhs)
}
/// Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
/// boundary of the type.
///
/// The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
/// [`MIN`](Self::MIN) is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
/// that is too large to represent in the type. In such a case, this function returns [`MIN`](Self::MIN) itself.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i32.wrapping_div(10), 10);"]
/// assert_eq!((-128i8).wrapping_div(-1), -128);
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_div(self, rhs: Self) -> Self {
self.overflowing_div(rhs).0
}
/// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
/// wrapping around at the boundary of the type.
///
/// Wrapping will only occur in `MIN / -1` on a signed type (where [`MIN`](Self::MIN) is the negative minimal value
/// for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
/// type. In this case, this method returns [`MIN`](Self::MIN) itself.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i32.wrapping_div_euclid(10), 10);"]
/// assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
self.overflowing_div_euclid(rhs).0
}
/// Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
/// boundary of the type.
///
/// Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
/// invalid for `MIN / -1` on a signed type (where [`MIN`](Self::MIN) is the negative minimal value). In such a case,
/// this function returns `0`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i32.wrapping_rem(10), 0);"]
/// assert_eq!((-128i8).wrapping_rem(-1), 0);
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_rem(self, rhs: Self) -> Self {
self.overflowing_rem(rhs).0
}
/// Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
/// at the boundary of the type.
///
/// Wrapping will only occur in `MIN % -1` on a signed type (where [`MIN`](Self::MIN) is
/// the negative minimal value for the type). In this case, this method returns 0.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i32.wrapping_rem_euclid(10), 0);"]
/// assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
self.overflowing_rem_euclid(rhs).0
}
/// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
/// of the type.
///
/// The only case where such wrapping can occur is when one negates [`MIN`](Self::MIN) on a signed type (where [`MIN`](Self::MIN)
/// is the negative minimal value for the type); this is a positive value that is too large to represent
/// in the type. In such a case, this function returns [`MIN`](Self::MIN) itself.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i32.wrapping_neg(), -100);"]
#[doc = "assert_eq!((-100i32).wrapping_neg(), 100);"]
#[doc = "assert_eq!(i32::MIN.wrapping_neg(), i32::MIN);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_neg(self) -> Self { (0 as i32).wrapping_sub(self) }
/// Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
/// any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
///
/// Beware that, unlike most other `wrapping_*` methods on integers, this
/// does *not* give the same result as doing the shift in infinite precision
/// then truncating as needed. Instead, the behaviour of this method matches what shift instructions
/// do on many processors, and is what the `<<` operator does when overflow
/// checks are disabled, but numerically it's weird. Consider, instead,
/// using [`Self::unbounded_shl`] which has nicer behaviour.
///
/// Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
/// the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
/// The primitive integer types all implement a [`rotate_left`](Self::rotate_left) function,
/// which may be what you want instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-1_i32).wrapping_shl(7), -128);"]
#[doc = "assert_eq!(42_i32.wrapping_shl(32), 42);"]
#[doc = "assert_eq!(42_i32.wrapping_shl(1).wrapping_shl(31), 0);"]
#[doc = "assert_eq!((-1_i32).wrapping_shl(128), -1);"]
#[doc = "assert_eq!(5_i32.wrapping_shl(1025), 10);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_shl(self, rhs: u32) -> Self {
unsafe { self.unchecked_shl(rhs & (Self::BITS - 1)) }
}
/// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
/// removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
///
/// Beware that, unlike most other `wrapping_*` methods on integers, this
/// does *not* give the same result as doing the shift in infinite precision
/// then truncating as needed. Instead, the behaviour of this method matches what shift instructions
/// do on many processors, and is what the `>>` operator does when overflow
/// checks are disabled, but numerically it's weird. Consider, instead,
/// using [`Self::unbounded_shr`] which has nicer behaviour.
///
/// Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
/// to the range of the type, rather than the bits shifted out of the LHS being returned to the other
/// end. The primitive integer types all implement a [`rotate_right`](Self::rotate_right) function,
/// which may be what you want instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-128_i32).wrapping_shr(7), -1);"]
#[doc = "assert_eq!(42_i32.wrapping_shr(32), 42);"]
#[doc = "assert_eq!(42_i32.wrapping_shr(1).wrapping_shr(31), 0);"]
/// assert_eq!((-128_i16).wrapping_shr(64), -128);
#[doc = "assert_eq!(10_i32.wrapping_shr(1025), 5);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_shr(self, rhs: u32) -> Self {
unsafe { self.unchecked_shr(rhs & (Self::BITS - 1)) }
}
/// Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
/// the boundary of the type.
///
/// The only case where such wrapping can occur is when one takes the absolute value of the negative
/// minimal value for the type; this is a positive value that is too large to represent in the type. In
/// such a case, this function returns [`MIN`](Self::MIN) itself.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i32.wrapping_abs(), 100);"]
#[doc = "assert_eq!((-100i32).wrapping_abs(), 100);"]
#[doc = "assert_eq!(i32::MIN.wrapping_abs(), i32::MIN);"]
/// assert_eq!((-128i8).wrapping_abs() as u8, 128);
/// ```
#[stable(feature = "no_panic_abs", since = "1.13.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[allow(unused_attributes)]
#[inline]
pub const fn wrapping_abs(self) -> Self {
if self.is_negative() { self.wrapping_neg() } else { self }
}
/// Computes the absolute value of `self` without any wrapping
/// or panicking.
///
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i32.unsigned_abs(), 100u32);"]
#[doc = "assert_eq!((-100i32).unsigned_abs(), 100u32);"]
/// assert_eq!((-128i8).unsigned_abs(), 128u8);
/// ```
#[stable(feature = "unsigned_abs", since = "1.51.0")]
#[rustc_const_stable(feature = "unsigned_abs", since = "1.51.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unsigned_abs(self) -> u32 { self.wrapping_abs() as u32 }
/// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3i32.wrapping_pow(4), 81);"]
/// assert_eq!(3i8.wrapping_pow(5), -13);
/// assert_eq!(3i8.wrapping_pow(6), -39);
#[doc = "assert_eq!(0_i32.wrapping_pow(0), 1);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_pow(self, exp: u32) -> Self {
let (a, _) = self.overflowing_pow(exp);
a
}
/// Calculates `self` + `rhs`.
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would have
/// occurred then the wrapped value is returned (negative if overflowed
/// above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i32.overflowing_add(2), (7, false));"]
#[doc = "assert_eq!(i32::MAX.overflowing_add(1), (i32::MIN, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::add_with_overflow(self as i32, rhs as i32);
(a as Self, b)
}
/// Calculates `self` + `rhs` + `carry` and checks for overflow.
///
/// Performs "ternary addition" of two integer operands and a carry-in
/// bit, and returns a tuple of the sum along with a boolean indicating
/// whether an arithmetic overflow would occur. On overflow, the wrapped
/// value is returned.
///
/// This allows chaining together multiple additions to create a wider
/// addition, and can be useful for bignum addition. This method should
/// only be used for the most significant word; for the less significant
/// words the unsigned method
#[doc = "[`u32::carrying_add`]"]
/// should be used.
///
/// The output boolean returned by this method is *not* a carry flag,
/// and should *not* be added to a more significant word.
///
/// If overflow occurred, the wrapped value is returned (negative if overflowed
/// above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
///
/// If the input carry is false, this method is equivalent to
/// [`overflowing_add`](Self::overflowing_add).
///
/// # Examples
///
/// ```
/// #![feature(signed_bigint_helpers)]
/// // Only the most significant word is signed.
/// //
#[doc = "// 10 MAX (a = 10 \u{d7} 2^32 + 2^32 - 1)"]
#[doc = "// + -5 9 (b = -5 \u{d7} 2^32 + 9)"]
/// // ---------
#[doc = "// 6 8 (sum = 6 \u{d7} 2^32 + 8)"]
///
#[doc = "let (a1, a0): (i32, u32) = (10, u32::MAX);"]
#[doc = "let (b1, b0): (i32, u32) = (-5, 9);"]
/// let carry0 = false;
///
#[doc = "// u32::carrying_add for the less significant words"]
/// let (sum0, carry1) = a0.carrying_add(b0, carry0);
/// assert_eq!(carry1, true);
///
#[doc = "// i32::carrying_add for the most significant word"]
/// let (sum1, overflow) = a1.carrying_add(b1, carry1);
/// assert_eq!(overflow, false);
///
/// assert_eq!((sum1, sum0), (6, 8));
/// ```
#[unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
let (a, b) = self.overflowing_add(rhs);
let (c, d) = a.overflowing_add(carry as i32);
(c, b != d)
}
/// Calculates `self` + `rhs` with an unsigned `rhs`.
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i32.overflowing_add_unsigned(2), (3, false));"]
#[doc =
"assert_eq!((i32::MIN).overflowing_add_unsigned(u32::MAX), (i32::MAX, false));"]
#[doc =
"assert_eq!((i32::MAX - 2).overflowing_add_unsigned(3), (i32::MIN, true));"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_add_unsigned(self, rhs: u32) -> (Self, bool) {
let rhs = rhs as Self;
let (res, overflowed) = self.overflowing_add(rhs);
(res, overflowed ^ (rhs < 0))
}
/// Calculates `self` - `rhs`.
///
/// Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
/// would occur. If an overflow would have occurred then the wrapped value is returned
/// (negative if overflowed above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i32.overflowing_sub(2), (3, false));"]
#[doc = "assert_eq!(i32::MIN.overflowing_sub(1), (i32::MAX, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::sub_with_overflow(self as i32, rhs as i32);
(a as Self, b)
}
/// Calculates `self` − `rhs` − `borrow` and checks for
/// overflow.
///
/// Performs "ternary subtraction" by subtracting both an integer
/// operand and a borrow-in bit from `self`, and returns a tuple of the
/// difference along with a boolean indicating whether an arithmetic
/// overflow would occur. On overflow, the wrapped value is returned.
///
/// This allows chaining together multiple subtractions to create a
/// wider subtraction, and can be useful for bignum subtraction. This
/// method should only be used for the most significant word; for the
/// less significant words the unsigned method
#[doc = "[`u32::borrowing_sub`]"]
/// should be used.
///
/// The output boolean returned by this method is *not* a borrow flag,
/// and should *not* be subtracted from a more significant word.
///
/// If overflow occurred, the wrapped value is returned (negative if overflowed
/// above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
///
/// If the input borrow is false, this method is equivalent to
/// [`overflowing_sub`](Self::overflowing_sub).
///
/// # Examples
///
/// ```
/// #![feature(signed_bigint_helpers)]
/// // Only the most significant word is signed.
/// //
#[doc = "// 6 8 (a = 6 \u{d7} 2^32 + 8)"]
#[doc = "// - -5 9 (b = -5 \u{d7} 2^32 + 9)"]
/// // ---------
#[doc = "// 10 MAX (diff = 10 \u{d7} 2^32 + 2^32 - 1)"]
///
#[doc = "let (a1, a0): (i32, u32) = (6, 8);"]
#[doc = "let (b1, b0): (i32, u32) = (-5, 9);"]
/// let borrow0 = false;
///
#[doc = "// u32::borrowing_sub for the less significant words"]
/// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);
/// assert_eq!(borrow1, true);
///
#[doc = "// i32::borrowing_sub for the most significant word"]
/// let (diff1, overflow) = a1.borrowing_sub(b1, borrow1);
/// assert_eq!(overflow, false);
///
#[doc = "assert_eq!((diff1, diff0), (10, u32::MAX));"]
/// ```
#[unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
let (a, b) = self.overflowing_sub(rhs);
let (c, d) = a.overflowing_sub(borrow as i32);
(c, b != d)
}
/// Calculates `self` - `rhs` with an unsigned `rhs`.
///
/// Returns a tuple of the subtraction along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i32.overflowing_sub_unsigned(2), (-1, false));"]
#[doc =
"assert_eq!((i32::MAX).overflowing_sub_unsigned(u32::MAX), (i32::MIN, false));"]
#[doc =
"assert_eq!((i32::MIN + 2).overflowing_sub_unsigned(3), (i32::MAX, true));"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_sub_unsigned(self, rhs: u32) -> (Self, bool) {
let rhs = rhs as Self;
let (res, overflowed) = self.overflowing_sub(rhs);
(res, overflowed ^ (rhs < 0))
}
/// Calculates the multiplication of `self` and `rhs`.
///
/// Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
/// would occur. If an overflow would have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i32.overflowing_mul(2), (10, false));"]
/// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::mul_with_overflow(self as i32, rhs as i32);
(a as Self, b)
}
/// Calculates the "full multiplication" `self * rhs + carry`
/// without the possibility to overflow.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// Performs "long multiplication" which takes in an extra amount to add, and may return an
/// additional amount of overflow. This allows for chaining together multiple
/// multiplications to create "big integers" which represent larger values.
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why [`i32`] is used.
///
/// ```
/// #![feature(signed_bigint_helpers)]
/// assert_eq!(5i32.carrying_mul(-2, 0), (4294967286, -1));
/// assert_eq!(5i32.carrying_mul(-2, 10), (0, 0));
/// assert_eq!(1_000_000_000i32.carrying_mul(-10, 0), (2884901888, -3));
/// assert_eq!(1_000_000_000i32.carrying_mul(-10, 10), (2884901898, -3));
#[doc =
"assert_eq!(i32::MAX.carrying_mul(i32::MAX, i32::MAX), (i32::MAX.unsigned_abs() + 1, i32::MAX / 2));"]
/// ```
#[unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[rustc_const_unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_mul(self, rhs: Self, carry: Self) -> (u32, Self) {
Self::carrying_mul_add(self, rhs, carry, 0)
}
/// Calculates the "full multiplication" `self * rhs + carry + add`
/// without the possibility to overflow.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// Performs "long multiplication" which takes in an extra amount to add, and may return an
/// additional amount of overflow. This allows for chaining together multiple
/// multiplications to create "big integers" which represent larger values.
///
/// If you only need one `carry`, then you can use [`Self::carrying_mul`] instead.
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `i32` is used.
///
/// ```
/// #![feature(signed_bigint_helpers)]
/// assert_eq!(5i32.carrying_mul_add(-2, 0, 0), (4294967286, -1));
/// assert_eq!(5i32.carrying_mul_add(-2, 10, 10), (10, 0));
/// assert_eq!(1_000_000_000i32.carrying_mul_add(-10, 0, 0), (2884901888, -3));
/// assert_eq!(1_000_000_000i32.carrying_mul_add(-10, 10, 10), (2884901908, -3));
#[doc =
"assert_eq!(i32::MAX.carrying_mul_add(i32::MAX, i32::MAX, i32::MAX), (u32::MAX, i32::MAX / 2));"]
/// ```
#[unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[rustc_const_unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_mul_add(self, rhs: Self, carry: Self, add: Self)
-> (u32, Self) {
intrinsics::carrying_mul_add(self, rhs, carry, add)
}
/// Calculates the divisor when `self` is divided by `rhs`.
///
/// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
/// occur. If an overflow would occur then self is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i32.overflowing_div(2), (2, false));"]
#[doc = "assert_eq!(i32::MIN.overflowing_div(-1), (i32::MIN, true));"]
/// ```
#[inline]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_overflowing_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
if intrinsics::unlikely((self == Self::MIN) & (rhs == -1)) {
(self, true)
} else { (self / rhs, false) }
}
/// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
///
/// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
/// occur. If an overflow would occur then `self` is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i32.overflowing_div_euclid(2), (2, false));"]
#[doc = "assert_eq!(i32::MIN.overflowing_div_euclid(-1), (i32::MIN, true));"]
/// ```
#[inline]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
if intrinsics::unlikely((self == Self::MIN) & (rhs == -1)) {
(self, true)
} else { (self.div_euclid(rhs), false) }
}
/// Calculates the remainder when `self` is divided by `rhs`.
///
/// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
/// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i32.overflowing_rem(2), (1, false));"]
#[doc = "assert_eq!(i32::MIN.overflowing_rem(-1), (0, true));"]
/// ```
#[inline]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_overflowing_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
if intrinsics::unlikely(rhs == -1) {
(0, self == Self::MIN)
} else { (self % rhs, false) }
}
/// Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
///
/// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
/// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i32.overflowing_rem_euclid(2), (1, false));"]
#[doc = "assert_eq!(i32::MIN.overflowing_rem_euclid(-1), (0, true));"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
if intrinsics::unlikely(rhs == -1) {
(0, self == Self::MIN)
} else { (self.rem_euclid(rhs), false) }
}
/// Negates self, overflowing if this is equal to the minimum value.
///
/// Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
/// happened. If `self` is the minimum value (e.g., [`i32::MIN`] for values of type [`i32`]), then the
/// minimum value will be returned again and `true` will be returned for an overflow happening.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2i32.overflowing_neg(), (-2, false));"]
#[doc = "assert_eq!(i32::MIN.overflowing_neg(), (i32::MIN, true));"]
/// ```
#[inline]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[allow(unused_attributes)]
pub const fn overflowing_neg(self) -> (Self, bool) {
if intrinsics::unlikely(self == Self::MIN) {
(Self::MIN, true)
} else { (-self, false) }
}
/// Shifts self left by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
/// value was larger than or equal to the number of bits. If the shift value is too large, then value is
/// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1i32.overflowing_shl(4), (0x10, false));"]
/// assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));
#[doc = "assert_eq!(0x10i32.overflowing_shl(31), (0, false));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shl(rhs), rhs >= Self::BITS)
}
/// Shifts self right by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
/// value was larger than or equal to the number of bits. If the shift value is too large, then value is
/// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10i32.overflowing_shr(4), (0x1, false));"]
/// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shr(rhs), rhs >= Self::BITS)
}
/// Computes the absolute value of `self`.
///
/// Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
/// happened. If self is the minimum value
#[doc = "(e.g., [`i32::MIN`] for values of type [`i32`]),"]
/// then the minimum value will be returned again and true will be returned
/// for an overflow happening.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i32.overflowing_abs(), (10, false));"]
#[doc = "assert_eq!((-10i32).overflowing_abs(), (10, false));"]
#[doc = "assert_eq!((i32::MIN).overflowing_abs(), (i32::MIN, true));"]
/// ```
#[stable(feature = "no_panic_abs", since = "1.13.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_abs(self) -> (Self, bool) {
(self.wrapping_abs(), self == Self::MIN)
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// Returns a tuple of the exponentiation along with a bool indicating
/// whether an overflow happened.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3i32.overflowing_pow(4), (81, false));"]
#[doc = "assert_eq!(0_i32.overflowing_pow(0), (1, false));"]
/// assert_eq!(3i8.overflowing_pow(5), (-13, true));
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
let mut base = self;
let mut acc: Self = 1;
let mut overflow = false;
let mut tmp_overflow;
if intrinsics::is_val_statically_known(base) &&
base.unsigned_abs().is_power_of_two() {
let k = base.unsigned_abs().ilog2();
let Some(shift) = k.checked_mul(exp) else { return (0, true) };
let base: Self = if base < 0 && (exp % 2) != 0 { -1 } else { 1 };
return (base.unbounded_shl(shift), base.shl_exact(shift).is_none());
}
if exp == 0 { return (1, false); }
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 {
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
}
exp /= 2;
(base, tmp_overflow) = base.overflowing_mul(base);
overflow |= tmp_overflow;
}
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
return (acc, overflow);
}
loop {
if (exp & 1) == 1 {
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
if exp == 1 { return (acc, overflow); }
}
exp /= 2;
(base, tmp_overflow) = base.overflowing_mul(base);
overflow |= tmp_overflow;
}
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// # Examples
///
/// ```
#[doc = "let x: i32 = 2; // or any other integer type"]
///
/// assert_eq!(x.pow(5), 32);
#[doc = "assert_eq!(0_i32.pow(0), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn pow(self, exp: u32) -> Self {
if intrinsics::overflow_checks() {
self.strict_pow(exp)
} else { self.wrapping_pow(exp) }
}
/// Returns the integer square root of the number, rounded down.
///
/// This function returns the **principal (non-negative) square root**.
/// For a given number `n`, although both `x` and `-x` satisfy x<sup>2</sup> = n,
/// this function always returns the non-negative value.
///
/// # Panics
///
/// This function will panic if `self` is negative.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i32.isqrt(), 3);"]
/// ```
#[stable(feature = "isqrt", since = "1.84.0")]
#[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn isqrt(self) -> Self {
match self.checked_isqrt() {
Some(sqrt) => sqrt,
None => imp::int_sqrt::panic_for_negative_argument(),
}
}
/// Calculates the quotient of Euclidean division of `self` by `rhs`.
///
/// This computes the integer `q` such that `self = q * rhs + r`, with
/// `r = self.rem_euclid(rhs)` and `0 <= r < abs(rhs)`.
///
/// In other words, the result is `self / rhs` rounded to the integer `q`
/// such that `self >= q * rhs`.
/// If `self > 0`, this is equal to rounding towards zero (the default in Rust);
/// if `self < 0`, this is equal to rounding away from zero (towards +/- infinity).
/// If `rhs > 0`, this is equal to rounding towards -infinity;
/// if `rhs < 0`, this is equal to rounding towards +infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero or if `self` is [`Self::MIN`]
/// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
///
/// # Examples
///
/// ```
#[doc = "let a: i32 = 7; // or any other integer type"]
/// let b = 4;
///
/// assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
/// assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
/// assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
/// assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_euclid(self, rhs: Self) -> Self {
let q = self / rhs;
if self % rhs < 0 { return if rhs > 0 { q - 1 } else { q + 1 } }
q
}
/// Calculates the least nonnegative remainder of `self` when
/// divided by `rhs`.
///
/// This is done as if by the Euclidean division algorithm -- given
/// `r = self.rem_euclid(rhs)`, the result satisfies
/// `self = rhs * self.div_euclid(rhs) + r` and `0 <= r < abs(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero or if `self` is [`Self::MIN`] and
/// `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
///
/// # Examples
///
/// ```
#[doc = "let a: i32 = 7; // or any other integer type"]
/// let b = 4;
///
/// assert_eq!(a.rem_euclid(b), 3);
/// assert_eq!((-a).rem_euclid(b), 1);
/// assert_eq!(a.rem_euclid(-b), 3);
/// assert_eq!((-a).rem_euclid(-b), 1);
/// ```
///
/// This will panic:
/// ```should_panic
#[doc = "let _ = i32::MIN.rem_euclid(-1);"]
/// ```
#[doc(alias = "modulo", alias = "mod")]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn rem_euclid(self, rhs: Self) -> Self {
let r = self % rhs;
if r < 0 { r.wrapping_add(rhs.wrapping_abs()) } else { r }
}
/// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero or if `self` is [`Self::MIN`]
/// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "let a: i32 = 8;"]
/// let b = 3;
///
/// assert_eq!(a.div_floor(b), 2);
/// assert_eq!(a.div_floor(-b), -3);
/// assert_eq!((-a).div_floor(b), -3);
/// assert_eq!((-a).div_floor(-b), 2);
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_floor(self, rhs: Self) -> Self {
let d = self / rhs;
let r = self % rhs;
let correction = (self ^ rhs) >> (Self::BITS - 1);
if r != 0 { d + correction } else { d }
}
/// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero or if `self` is [`Self::MIN`]
/// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "let a: i32 = 8;"]
/// let b = 3;
///
/// assert_eq!(a.div_ceil(b), 3);
/// assert_eq!(a.div_ceil(-b), -2);
/// assert_eq!((-a).div_ceil(b), -2);
/// assert_eq!((-a).div_ceil(-b), 3);
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_ceil(self, rhs: Self) -> Self {
let d = self / rhs;
let r = self % rhs;
let correction = 1 + ((self ^ rhs) >> (Self::BITS - 1));
if r != 0 { d + correction } else { d }
}
/// If `rhs` is positive, calculates the smallest value greater than or
/// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
/// calculates the largest value less than or equal to `self` that is a
/// multiple of `rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// On overflow, this function will panic if overflow checks are enabled (default in debug
/// mode) and wrap if overflow checks are disabled (default in release mode).
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "assert_eq!(16_i32.next_multiple_of(8), 16);"]
#[doc = "assert_eq!(23_i32.next_multiple_of(8), 24);"]
#[doc = "assert_eq!(16_i32.next_multiple_of(-8), 16);"]
#[doc = "assert_eq!(23_i32.next_multiple_of(-8), 16);"]
#[doc = "assert_eq!((-16_i32).next_multiple_of(8), -16);"]
#[doc = "assert_eq!((-23_i32).next_multiple_of(8), -16);"]
#[doc = "assert_eq!((-16_i32).next_multiple_of(-8), -16);"]
#[doc = "assert_eq!((-23_i32).next_multiple_of(-8), -24);"]
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_multiple_of(self, rhs: Self) -> Self {
if rhs == -1 { return self; }
let r = self % rhs;
let m =
if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) { r + rhs } else { r };
if m == 0 { self } else { self + (rhs - m) }
}
/// If `rhs` is positive, calculates the smallest value greater than or
/// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
/// calculates the largest value less than or equal to `self` that is a
/// multiple of `rhs`. Returns `None` if `rhs` is zero or the operation
/// would result in overflow.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "assert_eq!(16_i32.checked_next_multiple_of(8), Some(16));"]
#[doc = "assert_eq!(23_i32.checked_next_multiple_of(8), Some(24));"]
#[doc = "assert_eq!(16_i32.checked_next_multiple_of(-8), Some(16));"]
#[doc = "assert_eq!(23_i32.checked_next_multiple_of(-8), Some(16));"]
#[doc = "assert_eq!((-16_i32).checked_next_multiple_of(8), Some(-16));"]
#[doc = "assert_eq!((-23_i32).checked_next_multiple_of(8), Some(-16));"]
#[doc = "assert_eq!((-16_i32).checked_next_multiple_of(-8), Some(-16));"]
#[doc = "assert_eq!((-23_i32).checked_next_multiple_of(-8), Some(-24));"]
#[doc = "assert_eq!(1_i32.checked_next_multiple_of(0), None);"]
#[doc = "assert_eq!(i32::MAX.checked_next_multiple_of(2), None);"]
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
if rhs == -1 { return Some(self); }
let r =
match self.checked_rem(rhs) { Some(x) => x, None => return None, };
let m =
if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) { r + rhs } else { r };
if m == 0 { Some(self) } else { self.checked_add(rhs - m) }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// This method might not be optimized owing to implementation details;
/// [`ilog2`][Self::ilog2] can produce results more efficiently for base 2,
/// and [`ilog10`](Self::ilog10) can produce results more efficiently for base 10.
///
/// # Panics
///
/// This function will panic if `self` is less than or equal to zero,
/// or if `base` is less than 2.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i32.ilog(5), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog(self, base: Self) -> u32 {
if !(base >= 2) {
{
crate::panicking::panic_fmt(format_args!("base of integer logarithm must be at least 2"));
}
};
if let Some(log) = self.checked_ilog(base) {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the base 2 logarithm of the number, rounded down.
///
/// # Panics
///
/// This function will panic if `self` is less than or equal to zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2i32.ilog2(), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog2(self) -> u32 {
if let Some(log) = self.checked_ilog2() {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// # Panics
///
/// This function will panic if `self` is less than or equal to zero.
///
/// # Example
///
/// ```
#[doc = "assert_eq!(10i32.ilog10(), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog10(self) -> u32 {
if let Some(log) = self.checked_ilog10() {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// Returns `None` if the number is negative or zero, or if the base is not at least 2.
///
/// This method might not be optimized owing to implementation details;
/// `checked_ilog2` can produce results more efficiently for base 2, and
/// `checked_ilog10` can produce results more efficiently for base 10.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i32.checked_ilog(5), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog(self, base: Self) -> Option<u32> {
if self <= 0 || base <= 1 {
None
} else { (self as u32).checked_ilog(base as u32) }
}
/// Returns the base 2 logarithm of the number, rounded down.
///
/// Returns `None` if the number is negative or zero.
///
/// Note that for non-negative numbers, this is equivalent to
/// [`highest_one`](Self::highest_one).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2i32.checked_ilog2(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog2(self) -> Option<u32> {
if self <= 0 {
None
} else {
let log =
(Self::BITS - 1) -
unsafe { intrinsics::ctlz_nonzero(self) as u32 };
Some(log)
}
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// Returns `None` if the number is negative or zero.
///
/// # Example
///
/// ```
#[doc = "assert_eq!(10i32.checked_ilog10(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog10(self) -> Option<u32> {
imp::int_log10::i32(self as i32)
}
/// Computes the absolute value of `self`.
///
/// # Overflow behavior
///
/// The absolute value of
#[doc = "`i32::MIN`"]
/// cannot be represented as an
#[doc = "`i32`,"]
/// and attempting to calculate it will cause an overflow. This means
/// that code in debug mode will trigger a panic on this case and
/// optimized code will return
#[doc = "`i32::MIN`"]
/// without a panic. If you do not want this behavior, consider
/// using [`unsigned_abs`](Self::unsigned_abs) instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i32.abs(), 10);"]
#[doc = "assert_eq!((-10i32).abs(), 10);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[allow(unused_attributes)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn abs(self) -> Self {
if self.is_negative() { -self } else { self }
}
/// Computes the absolute difference between `self` and `other`.
///
/// This function always returns the correct answer without overflow or
/// panics by returning an unsigned integer.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i32.abs_diff(80), 20u32);"]
#[doc = "assert_eq!(100i32.abs_diff(110), 10u32);"]
#[doc = "assert_eq!((-100i32).abs_diff(80), 180u32);"]
#[doc = "assert_eq!((-100i32).abs_diff(-120), 20u32);"]
#[doc = "assert_eq!(i32::MIN.abs_diff(i32::MAX), u32::MAX);"]
/// ```
#[stable(feature = "int_abs_diff", since = "1.60.0")]
#[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn abs_diff(self, other: Self) -> u32 {
if self < other {
(other as u32).wrapping_sub(self as u32)
} else { (self as u32).wrapping_sub(other as u32) }
}
/// Returns a number representing sign of `self`.
///
/// - `0` if the number is zero
/// - `1` if the number is positive
/// - `-1` if the number is negative
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i32.signum(), 1);"]
#[doc = "assert_eq!(0i32.signum(), 0);"]
#[doc = "assert_eq!((-10i32).signum(), -1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_sign", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn signum(self) -> Self {
crate::intrinsics::three_way_compare(self, 0) as Self
}
/// Returns `true` if `self` is positive and `false` if the number is zero or
/// negative.
///
/// # Examples
///
/// ```
#[doc = "assert!(10i32.is_positive());"]
#[doc = "assert!(!(-10i32).is_positive());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[inline(always)]
pub const fn is_positive(self) -> bool { self > 0 }
/// Returns `true` if `self` is negative and `false` if the number is zero or
/// positive.
///
/// # Examples
///
/// ```
#[doc = "assert!((-10i32).is_negative());"]
#[doc = "assert!(!10i32.is_negative());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[inline(always)]
pub const fn is_negative(self) -> bool { self < 0 }
/// Returns the memory representation of this integer as a byte array in
/// big-endian (network) byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12345678i32.to_be_bytes();"]
#[doc = "assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
self.to_be().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// little-endian byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12345678i32.to_le_bytes();"]
#[doc = "assert_eq!(bytes, [0x78, 0x56, 0x34, 0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
self.to_le().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code
/// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
/// instead.
///
#[doc = ""]
///
/// [`to_be_bytes`]: Self::to_be_bytes
/// [`to_le_bytes`]: Self::to_le_bytes
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12345678i32.to_ne_bytes();"]
/// assert_eq!(
/// bytes,
/// if cfg!(target_endian = "big") {
#[doc = " [0x12, 0x34, 0x56, 0x78]"]
/// } else {
#[doc = " [0x78, 0x56, 0x34, 0x12]"]
/// }
/// );
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
unsafe { mem::transmute(self) }
}
/// Creates an integer value from its representation as a byte array in
/// big endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = i32::from_be_bytes([0x12, 0x34, 0x56, 0x78]);"]
#[doc = "assert_eq!(value, 0x12345678);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_be_i32(input: &mut &[u8]) -> i32 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i32>());"]
/// *input = rest;
#[doc = " i32::from_be_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_be(Self::from_ne_bytes(bytes))
}
/// Creates an integer value from its representation as a byte array in
/// little endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = i32::from_le_bytes([0x78, 0x56, 0x34, 0x12]);"]
#[doc = "assert_eq!(value, 0x12345678);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_le_i32(input: &mut &[u8]) -> i32 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i32>());"]
/// *input = rest;
#[doc = " i32::from_le_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_le(Self::from_ne_bytes(bytes))
}
/// Creates an integer value from its memory representation as a byte
/// array in native endianness.
///
/// As the target platform's native endianness is used, portable code
/// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
/// appropriate instead.
///
/// [`from_be_bytes`]: Self::from_be_bytes
/// [`from_le_bytes`]: Self::from_le_bytes
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = i32::from_ne_bytes(if cfg!(target_endian = \"big\") {"]
#[doc = " [0x12, 0x34, 0x56, 0x78]"]
/// } else {
#[doc = " [0x78, 0x56, 0x34, 0x12]"]
/// });
#[doc = "assert_eq!(value, 0x12345678);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_ne_i32(input: &mut &[u8]) -> i32 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i32>());"]
/// *input = rest;
#[doc = " i32::from_ne_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use]
#[inline]
pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
unsafe { mem::transmute(bytes) }
}
/// New code should prefer to use
#[doc = "[`i32::MIN`] instead."]
///
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MIN` associated constant on this type")]
#[rustc_diagnostic_item = "i32_legacy_fn_min_value"]
pub const fn min_value() -> Self { Self::MIN }
/// New code should prefer to use
#[doc = "[`i32::MAX`] instead."]
///
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MAX` associated constant on this type")]
#[rustc_diagnostic_item = "i32_legacy_fn_max_value"]
pub const fn max_value() -> Self { Self::MAX }
/// Clamps this number to a symmetric range centred around zero.
///
/// The method clamps the number's magnitude (absolute value) to be at most `limit`.
///
/// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
/// explicit about the intent.
///
/// # Examples
///
/// ```
/// #![feature(clamp_magnitude)]
#[doc = "assert_eq!(120i32.clamp_magnitude(100), 100);"]
#[doc = "assert_eq!(-120i32.clamp_magnitude(100), -100);"]
#[doc = "assert_eq!(80i32.clamp_magnitude(100), 80);"]
#[doc = "assert_eq!(-80i32.clamp_magnitude(100), -80);"]
/// ```
#[must_use =
"this returns the clamped value and does not modify the original"]
#[unstable(feature = "clamp_magnitude", issue = "148519")]
#[inline]
pub fn clamp_magnitude(self, limit: u32) -> Self {
if let Ok(limit) = core::convert::TryInto::<i32>::try_into(limit) {
self.clamp(-limit, limit)
} else { self }
}
/// Truncate an integer to an integer of the same size or smaller, preserving the least
/// significant bits.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i8, 120i32.truncate());"]
#[doc = "assert_eq!(-120i8, (-120i32).truncate());"]
/// assert_eq!(120i8, 376i32.truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
/// instead of truncating.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i8, 120i32.saturating_truncate());"]
#[doc = "assert_eq!(-120i8, (-120i32).saturating_truncate());"]
/// assert_eq!(127i8, 376i32.saturating_truncate());
/// assert_eq!(-128i8, (-1000i32).saturating_truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn saturating_truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_saturating_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
/// is outside the bounds of the smaller type.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(Some(120i8), 120i32.checked_truncate());"]
#[doc = "assert_eq!(Some(-120i8), (-120i32).checked_truncate());"]
/// assert_eq!(None, 376i32.checked_truncate::<i8>());
/// assert_eq!(None, (-1000i32).checked_truncate::<i8>());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn checked_truncate<Target>(self) -> Option<Target> where
Self: [const] traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_checked_truncate(self)
}
/// Widen to an integer of the same size or larger, preserving its value.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i128, 120i8.widen());"]
#[doc = "assert_eq!(-120i128, (-120i8).widen());"]
/// ```
#[must_use =
"this returns the widened value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn widen<Target>(self) -> Target where Self: [const]
traits::WidenTarget<Target> {
traits::WidenTarget::internal_widen(self)
}
/// Converts `self` to the target integer type, saturating at the numeric
/// bounds instead of overflowing.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(i8::MAX, i32::MAX.saturating_cast());"]
#[doc = "assert_eq!(i8::MIN, i32::MIN.saturating_cast());"]
#[doc = "assert_eq!(42u8, 42i32.saturating_cast());"]
#[doc = "assert_eq!(0u8, (-42i32).saturating_cast());"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn saturating_cast<T: [const] BoundedCastFromInt<Self>>(self) -> T {
T::saturating_cast_from(self)
}
/// Converts `self` to the target integer type, wrapping around at the
/// boundary of the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(i32::MAX as i8, i32::MAX.wrapping_cast());"]
#[doc = "assert_eq!(i32::MIN as i8, i32::MIN.wrapping_cast());"]
#[doc = "assert_eq!(42u8, 42i32.wrapping_cast());"]
#[doc = "assert_eq!(u8::MAX - 41, (-42i32).wrapping_cast());"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn wrapping_cast<T: [const] BoundedCastFromInt<Self>>(self) -> T {
T::wrapping_cast_from(self)
}
/// Converts `self` to the target integer type, returning `None` if the value
/// is not representable by the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(Some(42u8), 42i32.checked_cast());"]
#[doc = "assert_eq!((-42i32).checked_cast::<u8>(), None);"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn checked_cast<T: [const] CheckedCastFromInt<Self>>(self)
-> Option<T> {
T::checked_cast_from(self)
}
/// Converts `self` to the target integer type, panicking if the value
/// is not representable by the target type.
///
/// # Panics
///
/// This function will panic if the value is not representable by the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(42u8, 42i32.strict_cast());"]
/// ```
///
/// The following will panic:
///
/// ```should_panic
/// #![feature(integer_casts)]
#[doc = "let _ = (-42i32).strict_cast::<u8>();"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
#[track_caller]
pub const fn strict_cast<T: [const] CheckedCastFromInt<Self>>(self) -> T {
T::strict_cast_from(self)
}
/// Converts `self` to the target integer type, assuming the value is
/// representable by the target type.
///
/// # Safety
///
/// This results in undefined behavior if the integer value of `self` is bigger than `T::MAX`,
/// or smaller than `T::MIN`, where `T` is the target type.
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const unsafe fn unchecked_cast<T: [const] CheckedCastFromInt<Self>>(self)
-> T {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(in_bounds: bool) {
if !in_bounds {
let msg =
"unsafe precondition(s) violated: i32::unchecked_cast must fit in the target type\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check({
let cast_val = self.checked_cast::<T>();
let ret = cast_val.is_some();
core::mem::forget(cast_val);
ret
});
}
};
unsafe { T::unchecked_cast_from(self) }
}int_impl! {
427Self = i32,
428 ActualT = i32,
429 UnsignedT = u32,
430 BITS = 32,
431 BITS_MINUS_ONE = 31,
432 Min = -2147483648,
433 Max = 2147483647,
434 rot = 8,
435 rot_op = "0x10000b3",
436 rot_result = "0xb301",
437 swap_op = "0x12345678",
438 swapped = "0x78563412",
439 reversed = "0x1e6a2c48",
440 le_bytes = "[0x78, 0x56, 0x34, 0x12]",
441 be_bytes = "[0x12, 0x34, 0x56, 0x78]",
442 to_xe_bytes_doc = "",
443 from_xe_bytes_doc = "",
444 bound_condition = "",
445 }446/// Calculates the midpoint (average) between `self` and `rhs`.
///
/// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
/// sufficiently-large signed integral type. This implies that the result is
/// always rounded towards zero and that no overflow will ever occur.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0i32.midpoint(4), 2);"]
#[doc = "assert_eq!((-1i32).midpoint(2), 0);"]
#[doc = "assert_eq!((-7i32).midpoint(0), -3);"]
#[doc = "assert_eq!(0i32.midpoint(-7), -3);"]
#[doc = "assert_eq!(0i32.midpoint(7), 3);"]
/// ```
#[stable(feature = "num_midpoint_signed", since = "1.87.0")]
#[rustc_const_stable(feature = "num_midpoint_signed", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[doc(alias = "average_floor")]
#[doc(alias = "average_ceil")]
#[doc(alias = "average")]
#[inline]
pub const fn midpoint(self, rhs: i32) -> i32 {
((self as i64 + rhs as i64) / 2) as i32
}midpoint_impl! { i32, i64, signed }447/// Widening multiplication. Computes `self * rhs`, widening to a larger integer.
///
/// The returned value is always exact and can never overflow.
///
/// Note that this method is semantically equivalent to [`carrying_mul`] with a
/// carry of zero, with the latter instead returning a tuple denoting the low and
/// high parts of the result. Consider using it instead if you need
/// interoperability with other big int helper functions, or if this method isn't
/// available for a given type.
///
/// [`carrying_mul`]: Self::carrying_mul
///
/// # Examples
///
/// ```
/// #![feature(widening_mul)]
///
#[doc = "assert_eq!(i32::MAX.widening_mul(0_i32), 0);"]
#[doc =
"assert_eq!(i32::MAX.widening_mul(i32::MAX), i32::MAX as i64 * i32::MAX as i64);"]
/// ```
#[unstable(feature = "widening_mul", issue = "152016")]
#[rustc_const_unstable(feature = "widening_mul", issue = "152016")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn widening_mul(self, rhs: Self) -> i64 { self as i64 * rhs as i64 }widening_mul_impl! { i32, i64 }448}
449450impl i64 {
451/// The smallest value that can be represented by this integer type
#[doc = "(−2<sup>63</sup>)."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i64::MIN, -9223372036854775808);"]
/// ```
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MIN: Self = !Self::MAX;
/// The largest value that can be represented by this integer type
#[doc = "(2<sup>63</sup> − 1)."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i64::MAX, 9223372036854775807);"]
/// ```
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MAX: Self = (<u64>::MAX >> 1) as Self;
/// The size of this integer type in bits.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i64::BITS, 64);"]
/// ```
#[stable(feature = "int_bits_const", since = "1.53.0")]
pub const BITS: u32 = <u64>::BITS;
/// Returns the number of ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 0b100_0000i64;"]
///
/// assert_eq!(n.count_ones(), 1);
/// ```
///
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[doc(alias = "popcount")]
#[doc(alias = "popcnt")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn count_ones(self) -> u32 { (self as u64).count_ones() }
/// Returns the number of zeros in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i64::MAX.count_zeros(), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn count_zeros(self) -> u32 { (!self).count_ones() }
/// Returns the number of leading zeros in the binary representation of `self`.
///
/// Depending on what you're doing with the value, you might also be interested in the
/// [`ilog2`] function which returns a consistent number, even if the type widens.
///
/// # Examples
///
/// ```
#[doc = "let n = -1i64;"]
///
/// assert_eq!(n.leading_zeros(), 0);
/// ```
#[doc = "[`ilog2`]: i64::ilog2"]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn leading_zeros(self) -> u32 { (self as u64).leading_zeros() }
/// Returns the number of trailing zeros in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = -4i64;"]
///
/// assert_eq!(n.trailing_zeros(), 2);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn trailing_zeros(self) -> u32 { (self as u64).trailing_zeros() }
/// Returns the number of leading ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = -1i64;"]
///
#[doc = "assert_eq!(n.leading_ones(), 64);"]
/// ```
#[stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn leading_ones(self) -> u32 { (self as u64).leading_ones() }
/// Returns the number of trailing ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 3i64;"]
///
/// assert_eq!(n.trailing_ones(), 2);
/// ```
#[stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn trailing_ones(self) -> u32 { (self as u64).trailing_ones() }
/// Returns `self` with only the most significant bit set, or `0` if
/// the input is `0`.
///
/// # Examples
///
/// ```
#[doc = "let n: i64 = 0b_01100100;"]
///
/// assert_eq!(n.isolate_highest_one(), 0b_01000000);
#[doc = "assert_eq!(0_i64.isolate_highest_one(), 0);"]
/// ```
#[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn isolate_highest_one(self) -> Self {
self &
(((1 as i64) << (<i64>::BITS - 1)).wrapping_shr(self.leading_zeros()))
}
/// Returns `self` with only the least significant bit set, or `0` if
/// the input is `0`.
///
/// # Examples
///
/// ```
#[doc = "let n: i64 = 0b_01100100;"]
///
/// assert_eq!(n.isolate_lowest_one(), 0b_00000100);
#[doc = "assert_eq!(0_i64.isolate_lowest_one(), 0);"]
/// ```
#[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn isolate_lowest_one(self) -> Self { self & self.wrapping_neg() }
/// Returns the index of the highest bit set to one in `self`, or `None`
/// if `self` is `0`.
///
/// Note that for non-negative numbers, this is equivalent to
/// [`checked_ilog2`](Self::checked_ilog2).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0b0_i64.highest_one(), None);"]
#[doc = "assert_eq!(0b1_i64.highest_one(), Some(0));"]
#[doc = "assert_eq!(0b1_0000_i64.highest_one(), Some(4));"]
#[doc = "assert_eq!(0b1_1111_i64.highest_one(), Some(4));"]
/// ```
#[stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn highest_one(self) -> Option<u32> { (self as u64).highest_one() }
/// Returns the index of the lowest bit set to one in `self`, or `None`
/// if `self` is `0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0b0_i64.lowest_one(), None);"]
#[doc = "assert_eq!(0b1_i64.lowest_one(), Some(0));"]
#[doc = "assert_eq!(0b1_0000_i64.lowest_one(), Some(4));"]
#[doc = "assert_eq!(0b1_1111_i64.lowest_one(), Some(0));"]
/// ```
#[stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn lowest_one(self) -> Option<u32> { (self as u64).lowest_one() }
/// Returns the bit pattern of `self` reinterpreted as an unsigned integer of the same size.
///
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
/// the same.
///
/// # Examples
///
/// ```
#[doc = "let n = -1i64;"]
///
#[doc = "assert_eq!(n.cast_unsigned(), u64::MAX);"]
/// ```
#[stable(feature = "integer_sign_cast", since = "1.87.0")]
#[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_unsigned(self) -> u64 { self as u64 }
/// Saturating conversion of `self` to an unsigned integer of the same size.
///
/// Negative values are clamped to `0`.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`checked_cast_unsigned`](Self::checked_cast_unsigned),
/// or [`strict_cast_unsigned`](Self::strict_cast_unsigned).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = i64::MIN;"]
///
#[doc = "assert_eq!(n.saturating_cast_unsigned(), 0u64);"]
#[doc = "assert_eq!(64i64.saturating_cast_unsigned(), 64u64);"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_cast_unsigned(self) -> u64 {
if self >= 0 { self.cast_unsigned() } else { 0 }
}
/// Checked conversion of `self` to an unsigned integer of the same size,
/// returning `None` if `self` is negative.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`saturating_cast_unsigned`](Self::saturating_cast_unsigned),
/// or [`strict_cast_unsigned`](Self::strict_cast_unsigned).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = i64::MIN;"]
///
#[doc = "assert_eq!(n.checked_cast_unsigned(), None);"]
#[doc = "assert_eq!(64i64.checked_cast_unsigned(), Some(64u64));"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn checked_cast_unsigned(self) -> Option<u64> {
if self >= 0 { Some(self.cast_unsigned()) } else { None }
}
/// Strict conversion of `self` to an unsigned integer of the same size,
/// which panics if `self` is negative.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`checked_cast_unsigned`](Self::checked_cast_unsigned),
/// or [`saturating_cast_unsigned`](Self::saturating_cast_unsigned).
///
/// # Examples
///
/// ```should_panic
/// #![feature(integer_cast_extras)]
#[doc = "let _ = i64::MIN.strict_cast_unsigned();"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_cast_unsigned(self) -> u64 {
match self.checked_cast_unsigned() {
Some(n) => n,
None => imp::overflow_panic::cast_integer(),
}
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `<<` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0xaa00000000006e1i64;"]
#[doc = "let m = 0x6e10aa;"]
///
#[doc = "assert_eq!(n.rotate_left(12), m);"]
#[doc = "assert_eq!(n.rotate_left(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn rotate_left(self, n: u32) -> Self {
(self as u64).rotate_left(n) as Self
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `>>` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x6e10aai64;"]
#[doc = "let m = 0xaa00000000006e1;"]
///
#[doc = "assert_eq!(n.rotate_right(12), m);"]
#[doc = "assert_eq!(n.rotate_right(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn rotate_right(self, n: u32) -> Self {
(self as u64).rotate_right(n) as Self
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1234567890123456i64;"]
///
/// let m = n.swap_bytes();
///
#[doc = "assert_eq!(m, 0x5634129078563412);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn swap_bytes(self) -> Self { (self as u64).swap_bytes() as Self }
/// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
/// second least-significant bit becomes second most-significant bit, etc.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1234567890123456i64;"]
/// let m = n.reverse_bits();
///
#[doc = "assert_eq!(m, 0x6a2c48091e6a2c48);"]
#[doc = "assert_eq!(0, 0i64.reverse_bits());"]
/// ```
#[stable(feature = "reverse_bits", since = "1.37.0")]
#[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn reverse_bits(self) -> Self {
(self as u64).reverse_bits() as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are swapped.
///
/// See also [from_be_bytes()](Self::from_be_bytes).
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai64;"]
///
/// if cfg!(target_endian = "big") {
#[doc = " assert_eq!(i64::from_be(n), n)"]
/// } else {
#[doc = " assert_eq!(i64::from_be(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn from_be(x: Self) -> Self { x.swap_bytes() }
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are swapped.
///
/// See also [from_le_bytes()](Self::from_le_bytes).
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai64;"]
///
/// if cfg!(target_endian = "little") {
#[doc = " assert_eq!(i64::from_le(n), n)"]
/// } else {
#[doc = " assert_eq!(i64::from_le(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn from_le(x: Self) -> Self { x }
/// Swaps bytes of `self` on little endian targets.
///
/// On big endian this is a no-op.
///
/// The returned value has the same type as `self`, and will be interpreted
/// as (a potentially different) value of a native-endian
#[doc = "`i64`."]
///
/// See [`to_be_bytes()`](Self::to_be_bytes) for a type-safe alternative.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai64;"]
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be(self) -> Self { self.swap_bytes() }
/// Swaps bytes of `self` on big endian targets.
///
/// On little endian this is a no-op.
///
/// The returned value has the same type as `self`, and will be interpreted
/// as (a potentially different) value of a native-endian
#[doc = "`i64`."]
///
/// See [`to_le_bytes()`](Self::to_le_bytes) for a type-safe alternative.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai64;"]
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le(self) -> Self { self }
/// Checked integer addition. Computes `self + rhs`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i64::MAX - 2).checked_add(1), Some(i64::MAX - 1));"]
#[doc = "assert_eq!((i64::MAX - 2).checked_add(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_add(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer addition. Computes `self + rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i64::MAX - 2).strict_add(1), i64::MAX - 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i64::MAX - 2).strict_add(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_add(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Unchecked integer addition. Computes `self + rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_add(y)` is semantically equivalent to calling
/// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_add`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self + rhs > i64::MAX` or `self + rhs < i64::MIN`,"]
/// i.e. when [`checked_add`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_add`]: i64::checked_add"]
#[doc = "[`wrapping_add`]: i64::wrapping_add"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i64, rhs: i64) {
if !!lhs.overflowing_add(rhs).1 {
let msg =
"unsafe precondition(s) violated: i64::unchecked_add cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_add(self, rhs) }
}
/// Checked addition with an unsigned integer. Computes `self + rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i64.checked_add_unsigned(2), Some(3));"]
#[doc = "assert_eq!((i64::MAX - 2).checked_add_unsigned(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add_unsigned(self, rhs: u64) -> Option<Self> {
let (a, b) = self.overflowing_add_unsigned(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict addition with an unsigned integer. Computes `self + rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i64.strict_add_unsigned(2), 3);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i64::MAX - 2).strict_add_unsigned(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add_unsigned(self, rhs: u64) -> Self {
let (a, b) = self.overflowing_add_unsigned(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Checked integer subtraction. Computes `self - rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i64::MIN + 2).checked_sub(1), Some(i64::MIN + 1));"]
#[doc = "assert_eq!((i64::MIN + 2).checked_sub(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_sub(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer subtraction. Computes `self - rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i64::MIN + 2).strict_sub(1), i64::MIN + 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i64::MIN + 2).strict_sub(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_sub(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
/// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_sub`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self - rhs > i64::MAX` or `self - rhs < i64::MIN`,"]
/// i.e. when [`checked_sub`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_sub`]: i64::checked_sub"]
#[doc = "[`wrapping_sub`]: i64::wrapping_sub"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i64, rhs: i64) {
if !!lhs.overflowing_sub(rhs).1 {
let msg =
"unsafe precondition(s) violated: i64::unchecked_sub cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_sub(self, rhs) }
}
/// Checked subtraction with an unsigned integer. Computes `self - rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i64.checked_sub_unsigned(2), Some(-1));"]
#[doc = "assert_eq!((i64::MIN + 2).checked_sub_unsigned(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub_unsigned(self, rhs: u64) -> Option<Self> {
let (a, b) = self.overflowing_sub_unsigned(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict subtraction with an unsigned integer. Computes `self - rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i64.strict_sub_unsigned(2), -1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i64::MIN + 2).strict_sub_unsigned(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub_unsigned(self, rhs: u64) -> Self {
let (a, b) = self.overflowing_sub_unsigned(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Checked integer multiplication. Computes `self * rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i64::MAX.checked_mul(1), Some(i64::MAX));"]
#[doc = "assert_eq!(i64::MAX.checked_mul(2), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer multiplication. Computes `self * rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i64::MAX.strict_mul(1), i64::MAX);"]
/// ```
///
/// The following panics because of overflow:
///
/// ``` should_panic
#[doc = "let _ = i64::MAX.strict_mul(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_mul(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_mul(rhs);
if b { imp::overflow_panic::mul() } else { a }
}
/// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
/// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_mul`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self * rhs > i64::MAX` or `self * rhs < i64::MIN`,"]
/// i.e. when [`checked_mul`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_mul`]: i64::checked_mul"]
#[doc = "[`wrapping_mul`]: i64::wrapping_mul"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i64, rhs: i64) {
if !!lhs.overflowing_mul(rhs).1 {
let msg =
"unsafe precondition(s) violated: i64::unchecked_mul cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_mul(self, rhs) }
}
/// Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
/// or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc =
"assert_eq!((i64::MIN + 1).checked_div(-1), Some(9223372036854775807));"]
#[doc = "assert_eq!(i64::MIN.checked_div(-1), None);"]
#[doc = "assert_eq!((1i64).checked_div(0), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1)))
{
None
} else { Some(unsafe { intrinsics::unchecked_div(self, rhs) }) }
}
/// Strict integer division. Computes `self / rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is when one divides `MIN / -1` on a signed type (where
/// [`MIN`](Self::MIN) is the negative minimal value for the type); the result of this is `-MIN`, a positive value
/// that is too large to represent in the type.
///
/// Note that this is equivalent to normal division: `MIN / -1` will also panic both in
/// debug and release builds.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i64::MIN + 1).strict_div(-1), 9223372036854775807);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i64::MIN.strict_div(-1);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1i64).strict_div(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_div(self, rhs: Self) -> Self { self / rhs }
/// Checked Euclidean division. Computes `self.div_euclid(rhs)`,
/// returning `None` if `rhs == 0` or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc =
"assert_eq!((i64::MIN + 1).checked_div_euclid(-1), Some(9223372036854775807));"]
#[doc = "assert_eq!(i64::MIN.checked_div_euclid(-1), None);"]
#[doc = "assert_eq!((1i64).checked_div_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) {
None
} else { Some(self.div_euclid(rhs)) }
}
/// Strict Euclidean division. Computes `self.div_euclid(rhs)`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is when one divides `MIN / -1` on a signed type (where
/// [`MIN`](Self::MIN) is the negative minimal value for the type); the result of this is `-MIN`, a positive value
/// that is too large to represent in the type.
///
/// Note that this is equivalent to `div_euclid`: `MIN.div_euclid(-1)` will also panic both
/// in debug and release builds.
///
/// # Examples
///
/// ```
#[doc =
"assert_eq!((i64::MIN + 1).strict_div_euclid(-1), 9223372036854775807);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i64::MIN.strict_div_euclid(-1);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1i64).strict_div_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_div_euclid(self, rhs: Self) -> Self {
self.div_euclid(rhs)
}
/// Checked integer division without remainder. Computes `self / rhs`,
/// returning `None` if `rhs == 0`, the division results in overflow,
/// or `self % rhs != 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc =
"assert_eq!((i64::MIN + 1).checked_div_exact(-1), Some(9223372036854775807));"]
#[doc = "assert_eq!((-5i64).checked_div_exact(2), None);"]
#[doc = "assert_eq!(i64::MIN.checked_div_exact(-1), None);"]
#[doc = "assert_eq!((1i64).checked_div_exact(0), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_exact(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1)))
{
None
} else {
unsafe {
if intrinsics::unlikely(intrinsics::unchecked_rem(self, rhs) != 0)
{
None
} else { Some(intrinsics::exact_div(self, rhs)) }
}
}
}
/// Integer division without remainder. Computes `self / rhs`, returning `None` if `self % rhs != 0`.
///
/// # Panics
///
/// This function will panic if `rhs == 0`.
///
/// ## Overflow behavior
///
/// On overflow, this function will panic if overflow checks are enabled (default in debug
/// mode) and wrap if overflow checks are disabled (default in release mode).
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64i64.div_exact(2), Some(32));"]
#[doc = "assert_eq!(64i64.div_exact(32), Some(2));"]
#[doc =
"assert_eq!((i64::MIN + 1).div_exact(-1), Some(9223372036854775807));"]
#[doc = "assert_eq!(65i64.div_exact(2), None);"]
/// ```
/// ```should_panic
/// #![feature(exact_div)]
#[doc = "let _ = 64i64.div_exact(0);"]
/// ```
/// ```should_panic
/// #![feature(exact_div)]
#[doc = "let _ = i64::MIN.div_exact(-1);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn div_exact(self, rhs: Self) -> Option<Self> {
if self % rhs != 0 { None } else { Some(self / rhs) }
}
/// Unchecked integer division without remainder. Computes `self / rhs`.
///
/// # Safety
///
/// This results in undefined behavior when `rhs == 0`, `self % rhs != 0`, or
#[doc = "`self == i64::MIN && rhs == -1`,"]
/// i.e. when [`checked_div_exact`](Self::checked_div_exact) would return `None`.
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_div_exact(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i64, rhs: i64) {
if !(rhs != 0 && lhs % rhs == 0 &&
(lhs != <i64>::MIN || rhs != -1)) {
let msg =
"unsafe precondition(s) violated: i64::unchecked_div_exact cannot overflow, divide by zero, or leave a remainder\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::exact_div(self, rhs) }
}
/// Checked integer remainder. Computes `self % rhs`, returning `None` if
/// `rhs == 0` or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i64.checked_rem(2), Some(1));"]
#[doc = "assert_eq!(5i64.checked_rem(0), None);"]
#[doc = "assert_eq!(i64::MIN.checked_rem(-1), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1)))
{
None
} else { Some(unsafe { intrinsics::unchecked_rem(self, rhs) }) }
}
/// Strict integer remainder. Computes `self % rhs`, panicking if
/// the division results in overflow.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is `x % y` for `MIN / -1` on a
/// signed type (where [`MIN`](Self::MIN) is the negative minimal value), which is invalid due to implementation artifacts.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i64.strict_rem(2), 1);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5i64.strict_rem(0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i64::MIN.strict_rem(-1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_rem(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_rem(rhs);
if b { imp::overflow_panic::rem() } else { a }
}
/// Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
/// if `rhs == 0` or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i64.checked_rem_euclid(2), Some(1));"]
#[doc = "assert_eq!(5i64.checked_rem_euclid(0), None);"]
#[doc = "assert_eq!(i64::MIN.checked_rem_euclid(-1), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) {
None
} else { Some(self.rem_euclid(rhs)) }
}
/// Strict Euclidean remainder. Computes `self.rem_euclid(rhs)`, panicking if
/// the division results in overflow.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is `x % y` for `MIN / -1` on a
/// signed type (where [`MIN`](Self::MIN) is the negative minimal value), which is invalid due to implementation artifacts.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i64.strict_rem_euclid(2), 1);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5i64.strict_rem_euclid(0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i64::MIN.strict_rem_euclid(-1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_rem_euclid(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_rem_euclid(rhs);
if b { imp::overflow_panic::rem() } else { a }
}
/// Checked negation. Computes `-self`, returning `None` if `self == MIN`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i64.checked_neg(), Some(-5));"]
#[doc = "assert_eq!(i64::MIN.checked_neg(), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_neg(self) -> Option<Self> {
let (a, b) = self.overflowing_neg();
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Unchecked negation. Computes `-self`, assuming overflow cannot occur.
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self == i64::MIN`,"]
/// i.e. when [`checked_neg`] would return `None`.
///
#[doc = "[`checked_neg`]: i64::checked_neg"]
#[stable(feature = "unchecked_neg", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_neg", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_neg(self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i64) {
if !!lhs.overflowing_neg().1 {
let msg =
"unsafe precondition(s) violated: i64::unchecked_neg cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self);
}
};
unsafe { intrinsics::unchecked_sub(0, self) }
}
/// Strict negation. Computes `-self`, panicking if `self == MIN`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i64.strict_neg(), -5);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i64::MIN.strict_neg();"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_neg(self) -> Self {
let (a, b) = self.overflowing_neg();
if b { imp::overflow_panic::neg() } else { a }
}
/// Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
/// than or equal to the number of bits in `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1i64.checked_shl(4), Some(0x10));"]
#[doc = "assert_eq!(0x1i64.checked_shl(129), None);"]
#[doc = "assert_eq!(0x10i64.checked_shl(63), Some(0));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
if rhs < Self::BITS {
Some(unsafe { self.unchecked_shl(rhs) })
} else { None }
}
/// Strict shift left. Computes `self << rhs`, panicking if `rhs` is larger
/// than or equal to the number of bits in `self`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1i64.strict_shl(4), 0x10);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0x1i64.strict_shl(129);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_shl(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_shl(rhs);
if b { imp::overflow_panic::shl() } else { a }
}
/// Unchecked shift left. Computes `self << rhs`, assuming that
/// `rhs` is less than the number of bits in `self`.
///
/// # Safety
///
/// This results in undefined behavior if `rhs` is larger than
/// or equal to the number of bits in `self`,
/// i.e. when [`checked_shl`] would return `None`.
///
#[doc = "[`checked_shl`]: i64::checked_shl"]
#[stable(feature = "unchecked_shifts", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_shl(self, rhs: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(rhs: u32) {
if !(rhs < <i64>::BITS) {
let msg =
"unsafe precondition(s) violated: i64::unchecked_shl cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(rhs); }
};
unsafe { intrinsics::unchecked_shl(self, rhs) }
}
/// Unbounded shift left. Computes `self << rhs`, without bounding the value of `rhs`.
///
/// If `rhs` is larger or equal to the number of bits in `self`,
/// the entire value is shifted out, and `0` is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1_i64.unbounded_shl(4), 0x10);"]
#[doc = "assert_eq!(0x1_i64.unbounded_shl(129), 0);"]
#[doc = "assert_eq!(0b101_i64.unbounded_shl(0), 0b101);"]
#[doc = "assert_eq!(0b101_i64.unbounded_shl(1), 0b1010);"]
#[doc = "assert_eq!(0b101_i64.unbounded_shl(2), 0b10100);"]
#[doc = "assert_eq!(42_i64.unbounded_shl(64), 0);"]
#[doc = "assert_eq!(42_i64.unbounded_shl(1).unbounded_shl(63), 0);"]
#[doc = "assert_eq!((-13_i64).unbounded_shl(64), 0);"]
#[doc = "assert_eq!((-13_i64).unbounded_shl(1).unbounded_shl(63), 0);"]
/// ```
#[stable(feature = "unbounded_shifts", since = "1.87.0")]
#[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unbounded_shl(self, rhs: u32) -> i64 {
if rhs < Self::BITS { unsafe { self.unchecked_shl(rhs) } } else { 0 }
}
/// Exact shift left. Computes `self << rhs` as long as it can be reversed losslessly.
///
/// Returns `None` if any bits that would be shifted out differ from the resulting sign bit
/// or if `rhs` >=
#[doc = "`i64::BITS`."]
/// Otherwise, returns `Some(self << rhs)`.
///
/// # Examples
///
/// ```
/// #![feature(exact_bitshifts)]
///
#[doc = "assert_eq!(0x1i64.shl_exact(4), Some(0x10));"]
#[doc =
"assert_eq!(0x1i64.shl_exact(i64::BITS - 2), Some(1 << i64::BITS - 2));"]
#[doc = "assert_eq!(0x1i64.shl_exact(i64::BITS - 1), None);"]
#[doc =
"assert_eq!((-0x2i64).shl_exact(i64::BITS - 2), Some(-0x2 << i64::BITS - 2));"]
#[doc = "assert_eq!((-0x2i64).shl_exact(i64::BITS - 1), None);"]
/// ```
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn shl_exact(self, rhs: u32) -> Option<i64> {
if rhs < self.leading_zeros() || rhs < self.leading_ones() {
Some(unsafe { self.unchecked_shl(rhs) })
} else { None }
}
/// Unchecked exact shift left. Computes `self << rhs`, assuming the operation can be
/// losslessly reversed and `rhs` cannot be larger than
#[doc = "`i64::BITS`."]
///
/// # Safety
///
/// This results in undefined behavior when `rhs >= self.leading_zeros() && rhs >=
/// self.leading_ones()` i.e. when
#[doc = "[`i64::shl_exact`]"]
/// would return `None`.
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_shl_exact(self, rhs: u32) -> i64 {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(zeros: u32, ones: u32, rhs: u32) {
if !(rhs < zeros || rhs < ones) {
let msg =
"unsafe precondition(s) violated: i64::unchecked_shl_exact cannot shift out bits that would change the value of the first bit\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_library_ub() {
precondition_check(self.leading_zeros(), self.leading_ones(),
rhs);
}
};
unsafe { self.unchecked_shl(rhs) }
}
/// Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
/// larger than or equal to the number of bits in `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10i64.checked_shr(4), Some(0x1));"]
#[doc = "assert_eq!(0x10i64.checked_shr(128), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
if rhs < Self::BITS {
Some(unsafe { self.unchecked_shr(rhs) })
} else { None }
}
/// Strict shift right. Computes `self >> rhs`, panicking if `rhs` is
/// larger than or equal to the number of bits in `self`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10i64.strict_shr(4), 0x1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0x10i64.strict_shr(128);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_shr(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_shr(rhs);
if b { imp::overflow_panic::shr() } else { a }
}
/// Unchecked shift right. Computes `self >> rhs`, assuming that
/// `rhs` is less than the number of bits in `self`.
///
/// # Safety
///
/// This results in undefined behavior if `rhs` is larger than
/// or equal to the number of bits in `self`,
/// i.e. when [`checked_shr`] would return `None`.
///
#[doc = "[`checked_shr`]: i64::checked_shr"]
#[stable(feature = "unchecked_shifts", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_shr(self, rhs: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(rhs: u32) {
if !(rhs < <i64>::BITS) {
let msg =
"unsafe precondition(s) violated: i64::unchecked_shr cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(rhs); }
};
unsafe { intrinsics::unchecked_shr(self, rhs) }
}
/// Unbounded shift right. Computes `self >> rhs`, without bounding the value of `rhs`.
///
/// If `rhs` is larger or equal to the number of bits in `self`,
/// the entire value is shifted out, which yields `0` for a positive number,
/// and `-1` for a negative number.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10_i64.unbounded_shr(4), 0x1);"]
#[doc = "assert_eq!(0x10_i64.unbounded_shr(129), 0);"]
#[doc = "assert_eq!(i64::MIN.unbounded_shr(129), -1);"]
#[doc = "assert_eq!(0b1010_i64.unbounded_shr(0), 0b1010);"]
#[doc = "assert_eq!(0b1010_i64.unbounded_shr(1), 0b101);"]
#[doc = "assert_eq!(0b1010_i64.unbounded_shr(2), 0b10);"]
#[doc = "assert_eq!(42_i64.unbounded_shr(64), 0);"]
#[doc = "assert_eq!(42_i64.unbounded_shr(1).unbounded_shr(63), 0);"]
#[doc = "assert_eq!((-13_i64).unbounded_shr(64), -1);"]
#[doc = "assert_eq!((-13_i64).unbounded_shr(1).unbounded_shr(63), -1);"]
/// ```
#[stable(feature = "unbounded_shifts", since = "1.87.0")]
#[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unbounded_shr(self, rhs: u32) -> i64 {
if rhs < Self::BITS {
unsafe { self.unchecked_shr(rhs) }
} else { unsafe { self.unchecked_shr(Self::BITS - 1) } }
}
/// Exact shift right. Computes `self >> rhs` as long as it can be reversed losslessly.
///
/// Returns `None` if any non-zero bits would be shifted out or if `rhs` >=
#[doc = "`i64::BITS`."]
/// Otherwise, returns `Some(self >> rhs)`.
///
/// # Examples
///
/// ```
/// #![feature(exact_bitshifts)]
///
#[doc = "assert_eq!(0x10i64.shr_exact(4), Some(0x1));"]
#[doc = "assert_eq!(0x10i64.shr_exact(5), None);"]
/// ```
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn shr_exact(self, rhs: u32) -> Option<i64> {
if rhs <= self.trailing_zeros() && rhs < <i64>::BITS {
Some(unsafe { self.unchecked_shr(rhs) })
} else { None }
}
/// Unchecked exact shift right. Computes `self >> rhs`, assuming the operation can be
/// losslessly reversed and `rhs` cannot be larger than
#[doc = "`i64::BITS`."]
///
/// # Safety
///
/// This results in undefined behavior when `rhs > self.trailing_zeros() || rhs >=
#[doc = "i64::BITS`"]
/// i.e. when
#[doc = "[`i64::shr_exact`]"]
/// would return `None`.
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_shr_exact(self, rhs: u32) -> i64 {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(zeros: u32, bits: u32, rhs: u32) {
if !(rhs <= zeros && rhs < bits) {
let msg =
"unsafe precondition(s) violated: i64::unchecked_shr_exact cannot shift out non-zero bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_library_ub() {
precondition_check(self.trailing_zeros(), <i64>::BITS, rhs);
}
};
unsafe { self.unchecked_shr(rhs) }
}
/// Checked absolute value. Computes `self.abs()`, returning `None` if
/// `self == MIN`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-5i64).checked_abs(), Some(5));"]
#[doc = "assert_eq!(i64::MIN.checked_abs(), None);"]
/// ```
#[stable(feature = "no_panic_abs", since = "1.13.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_abs(self) -> Option<Self> {
if self.is_negative() { self.checked_neg() } else { Some(self) }
}
/// Strict absolute value. Computes `self.abs()`, panicking if
/// `self == MIN`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-5i64).strict_abs(), 5);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i64::MIN.strict_abs();"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_abs(self) -> Self {
if self.is_negative() { self.strict_neg() } else { self }
}
/// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(8i64.checked_pow(2), Some(64));"]
#[doc = "assert_eq!(0_i64.checked_pow(0), Some(1));"]
#[doc = "assert_eq!(i64::MAX.checked_pow(2), None);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
let mut base = self;
let mut acc: Self = 1;
if intrinsics::is_val_statically_known(base) &&
base.unsigned_abs().is_power_of_two() {
let k = base.unsigned_abs().ilog2();
let shift =
match k.checked_mul(exp) { Some(x) => x, None => return None, };
return if base < 0 && (exp % 2) == 1 {
(-1 as Self).shl_exact(shift)
} else { (1 as Self).shl_exact(shift) }
}
if exp == 0 { return Some(1); }
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 {
acc =
match acc.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
exp /= 2;
base =
match base.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
return acc.checked_mul(base);
}
loop {
if (exp & 1) == 1 {
acc =
match acc.checked_mul(base) {
Some(x) => x,
None => return None,
};
if exp == 1 { return Some(acc); }
}
exp /= 2;
base =
match base.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
}
/// Strict exponentiation. Computes `self.pow(exp)`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(8i64.strict_pow(2), 64);"]
#[doc = "assert_eq!(0_i64.strict_pow(0), 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i64::MAX.strict_pow(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) {
Some(x) => x,
None => imp::overflow_panic::pow(),
}
}
/// Returns the integer square root of the number, rounded down.
///
/// This function returns the **principal (non-negative) square root**.
/// For a given number `n`, although both `x` and `-x` satisfy x<sup>2</sup> = n,
/// this function always returns the non-negative value.
///
/// Returns `None` if `self` is negative.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i64.checked_isqrt(), Some(3));"]
/// ```
#[stable(feature = "isqrt", since = "1.84.0")]
#[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_isqrt(self) -> Option<Self> {
if self < 0 {
None
} else {
let result = self.cast_unsigned().isqrt().cast_signed();
unsafe {
const MAX_RESULT: i64 =
<i64>::MAX.cast_unsigned().isqrt().cast_signed();
crate::hint::assert_unchecked(result <= MAX_RESULT);
}
Some(result)
}
}
/// Saturating integer addition. Computes `self + rhs`, saturating at the numeric
/// bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i64.saturating_add(1), 101);"]
#[doc = "assert_eq!(i64::MAX.saturating_add(100), i64::MAX);"]
#[doc = "assert_eq!(i64::MIN.saturating_add(-1), i64::MIN);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_add(self, rhs: Self) -> Self {
intrinsics::saturating_add(self, rhs)
}
/// Saturating addition with an unsigned integer. Computes `self + rhs`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i64.saturating_add_unsigned(2), 3);"]
#[doc = "assert_eq!(i64::MAX.saturating_add_unsigned(100), i64::MAX);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_add_unsigned(self, rhs: u64) -> Self {
match self.checked_add_unsigned(rhs) { Some(x) => x, None => Self::MAX, }
}
/// Saturating integer subtraction. Computes `self - rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i64.saturating_sub(127), -27);"]
#[doc = "assert_eq!(i64::MIN.saturating_sub(100), i64::MIN);"]
#[doc = "assert_eq!(i64::MAX.saturating_sub(-1), i64::MAX);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_sub(self, rhs: Self) -> Self {
intrinsics::saturating_sub(self, rhs)
}
/// Saturating subtraction with an unsigned integer. Computes `self - rhs`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i64.saturating_sub_unsigned(127), -27);"]
#[doc = "assert_eq!(i64::MIN.saturating_sub_unsigned(100), i64::MIN);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_sub_unsigned(self, rhs: u64) -> Self {
match self.checked_sub_unsigned(rhs) { Some(x) => x, None => Self::MIN, }
}
/// Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
/// instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i64.saturating_neg(), -100);"]
#[doc = "assert_eq!((-100i64).saturating_neg(), 100);"]
#[doc = "assert_eq!(i64::MIN.saturating_neg(), i64::MAX);"]
#[doc = "assert_eq!(i64::MAX.saturating_neg(), i64::MIN + 1);"]
/// ```
#[stable(feature = "saturating_neg", since = "1.45.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_neg(self) -> Self {
intrinsics::saturating_sub(0, self)
}
/// Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
/// MIN` instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i64.saturating_abs(), 100);"]
#[doc = "assert_eq!((-100i64).saturating_abs(), 100);"]
#[doc = "assert_eq!(i64::MIN.saturating_abs(), i64::MAX);"]
#[doc = "assert_eq!((i64::MIN + 1).saturating_abs(), i64::MAX);"]
/// ```
#[stable(feature = "saturating_neg", since = "1.45.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_abs(self) -> Self {
if self.is_negative() { self.saturating_neg() } else { self }
}
/// Saturating integer multiplication. Computes `self * rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i64.saturating_mul(12), 120);"]
#[doc = "assert_eq!(i64::MAX.saturating_mul(10), i64::MAX);"]
#[doc = "assert_eq!(i64::MIN.saturating_mul(10), i64::MIN);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_mul(self, rhs: Self) -> Self {
match self.checked_mul(rhs) {
Some(x) => x,
None => if (self < 0) == (rhs < 0) { Self::MAX } else { Self::MIN },
}
}
/// Saturating integer division. Computes `self / rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i64.saturating_div(2), 2);"]
#[doc = "assert_eq!(i64::MAX.saturating_div(-1), i64::MIN + 1);"]
#[doc = "assert_eq!(i64::MIN.saturating_div(-1), i64::MAX);"]
///
/// ```
#[stable(feature = "saturating_div", since = "1.58.0")]
#[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_div(self, rhs: Self) -> Self {
match self.overflowing_div(rhs) {
(result, false) => result,
(_result, true) => Self::MAX,
}
}
/// Saturating integer exponentiation. Computes `self.pow(exp)`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-4i64).saturating_pow(3), -64);"]
#[doc = "assert_eq!(0_i64.saturating_pow(0), 1);"]
#[doc = "assert_eq!(i64::MIN.saturating_pow(2), i64::MAX);"]
#[doc = "assert_eq!(i64::MIN.saturating_pow(3), i64::MIN);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) {
Some(x) => x,
None if self < 0 && exp % 2 == 1 => Self::MIN,
None => Self::MAX,
}
}
/// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
/// boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i64.wrapping_add(27), 127);"]
#[doc = "assert_eq!(i64::MAX.wrapping_add(2), i64::MIN + 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_add(self, rhs: Self) -> Self {
intrinsics::wrapping_add(self, rhs)
}
/// Wrapping (modular) addition with an unsigned integer. Computes
/// `self + rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i64.wrapping_add_unsigned(27), 127);"]
#[doc = "assert_eq!(i64::MAX.wrapping_add_unsigned(2), i64::MIN + 1);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_add_unsigned(self, rhs: u64) -> Self {
self.wrapping_add(rhs as Self)
}
/// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
/// boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0i64.wrapping_sub(127), -127);"]
#[doc = "assert_eq!((-2i64).wrapping_sub(i64::MAX), i64::MAX);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_sub(self, rhs: Self) -> Self {
intrinsics::wrapping_sub(self, rhs)
}
/// Wrapping (modular) subtraction with an unsigned integer. Computes
/// `self - rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0i64.wrapping_sub_unsigned(127), -127);"]
#[doc = "assert_eq!((-2i64).wrapping_sub_unsigned(u64::MAX), -1);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_sub_unsigned(self, rhs: u64) -> Self {
self.wrapping_sub(rhs as Self)
}
/// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
/// the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i64.wrapping_mul(12), 120);"]
/// assert_eq!(11i8.wrapping_mul(12), -124);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_mul(self, rhs: Self) -> Self {
intrinsics::wrapping_mul(self, rhs)
}
/// Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
/// boundary of the type.
///
/// The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
/// [`MIN`](Self::MIN) is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
/// that is too large to represent in the type. In such a case, this function returns [`MIN`](Self::MIN) itself.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i64.wrapping_div(10), 10);"]
/// assert_eq!((-128i8).wrapping_div(-1), -128);
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_div(self, rhs: Self) -> Self {
self.overflowing_div(rhs).0
}
/// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
/// wrapping around at the boundary of the type.
///
/// Wrapping will only occur in `MIN / -1` on a signed type (where [`MIN`](Self::MIN) is the negative minimal value
/// for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
/// type. In this case, this method returns [`MIN`](Self::MIN) itself.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i64.wrapping_div_euclid(10), 10);"]
/// assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
self.overflowing_div_euclid(rhs).0
}
/// Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
/// boundary of the type.
///
/// Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
/// invalid for `MIN / -1` on a signed type (where [`MIN`](Self::MIN) is the negative minimal value). In such a case,
/// this function returns `0`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i64.wrapping_rem(10), 0);"]
/// assert_eq!((-128i8).wrapping_rem(-1), 0);
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_rem(self, rhs: Self) -> Self {
self.overflowing_rem(rhs).0
}
/// Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
/// at the boundary of the type.
///
/// Wrapping will only occur in `MIN % -1` on a signed type (where [`MIN`](Self::MIN) is
/// the negative minimal value for the type). In this case, this method returns 0.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i64.wrapping_rem_euclid(10), 0);"]
/// assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
self.overflowing_rem_euclid(rhs).0
}
/// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
/// of the type.
///
/// The only case where such wrapping can occur is when one negates [`MIN`](Self::MIN) on a signed type (where [`MIN`](Self::MIN)
/// is the negative minimal value for the type); this is a positive value that is too large to represent
/// in the type. In such a case, this function returns [`MIN`](Self::MIN) itself.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i64.wrapping_neg(), -100);"]
#[doc = "assert_eq!((-100i64).wrapping_neg(), 100);"]
#[doc = "assert_eq!(i64::MIN.wrapping_neg(), i64::MIN);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_neg(self) -> Self { (0 as i64).wrapping_sub(self) }
/// Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
/// any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
///
/// Beware that, unlike most other `wrapping_*` methods on integers, this
/// does *not* give the same result as doing the shift in infinite precision
/// then truncating as needed. Instead, the behaviour of this method matches what shift instructions
/// do on many processors, and is what the `<<` operator does when overflow
/// checks are disabled, but numerically it's weird. Consider, instead,
/// using [`Self::unbounded_shl`] which has nicer behaviour.
///
/// Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
/// the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
/// The primitive integer types all implement a [`rotate_left`](Self::rotate_left) function,
/// which may be what you want instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-1_i64).wrapping_shl(7), -128);"]
#[doc = "assert_eq!(42_i64.wrapping_shl(64), 42);"]
#[doc = "assert_eq!(42_i64.wrapping_shl(1).wrapping_shl(63), 0);"]
#[doc = "assert_eq!((-1_i64).wrapping_shl(128), -1);"]
#[doc = "assert_eq!(5_i64.wrapping_shl(1025), 10);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_shl(self, rhs: u32) -> Self {
unsafe { self.unchecked_shl(rhs & (Self::BITS - 1)) }
}
/// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
/// removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
///
/// Beware that, unlike most other `wrapping_*` methods on integers, this
/// does *not* give the same result as doing the shift in infinite precision
/// then truncating as needed. Instead, the behaviour of this method matches what shift instructions
/// do on many processors, and is what the `>>` operator does when overflow
/// checks are disabled, but numerically it's weird. Consider, instead,
/// using [`Self::unbounded_shr`] which has nicer behaviour.
///
/// Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
/// to the range of the type, rather than the bits shifted out of the LHS being returned to the other
/// end. The primitive integer types all implement a [`rotate_right`](Self::rotate_right) function,
/// which may be what you want instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-128_i64).wrapping_shr(7), -1);"]
#[doc = "assert_eq!(42_i64.wrapping_shr(64), 42);"]
#[doc = "assert_eq!(42_i64.wrapping_shr(1).wrapping_shr(63), 0);"]
/// assert_eq!((-128_i16).wrapping_shr(64), -128);
#[doc = "assert_eq!(10_i64.wrapping_shr(1025), 5);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_shr(self, rhs: u32) -> Self {
unsafe { self.unchecked_shr(rhs & (Self::BITS - 1)) }
}
/// Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
/// the boundary of the type.
///
/// The only case where such wrapping can occur is when one takes the absolute value of the negative
/// minimal value for the type; this is a positive value that is too large to represent in the type. In
/// such a case, this function returns [`MIN`](Self::MIN) itself.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i64.wrapping_abs(), 100);"]
#[doc = "assert_eq!((-100i64).wrapping_abs(), 100);"]
#[doc = "assert_eq!(i64::MIN.wrapping_abs(), i64::MIN);"]
/// assert_eq!((-128i8).wrapping_abs() as u8, 128);
/// ```
#[stable(feature = "no_panic_abs", since = "1.13.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[allow(unused_attributes)]
#[inline]
pub const fn wrapping_abs(self) -> Self {
if self.is_negative() { self.wrapping_neg() } else { self }
}
/// Computes the absolute value of `self` without any wrapping
/// or panicking.
///
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i64.unsigned_abs(), 100u64);"]
#[doc = "assert_eq!((-100i64).unsigned_abs(), 100u64);"]
/// assert_eq!((-128i8).unsigned_abs(), 128u8);
/// ```
#[stable(feature = "unsigned_abs", since = "1.51.0")]
#[rustc_const_stable(feature = "unsigned_abs", since = "1.51.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unsigned_abs(self) -> u64 { self.wrapping_abs() as u64 }
/// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3i64.wrapping_pow(4), 81);"]
/// assert_eq!(3i8.wrapping_pow(5), -13);
/// assert_eq!(3i8.wrapping_pow(6), -39);
#[doc = "assert_eq!(0_i64.wrapping_pow(0), 1);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_pow(self, exp: u32) -> Self {
let (a, _) = self.overflowing_pow(exp);
a
}
/// Calculates `self` + `rhs`.
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would have
/// occurred then the wrapped value is returned (negative if overflowed
/// above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i64.overflowing_add(2), (7, false));"]
#[doc = "assert_eq!(i64::MAX.overflowing_add(1), (i64::MIN, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::add_with_overflow(self as i64, rhs as i64);
(a as Self, b)
}
/// Calculates `self` + `rhs` + `carry` and checks for overflow.
///
/// Performs "ternary addition" of two integer operands and a carry-in
/// bit, and returns a tuple of the sum along with a boolean indicating
/// whether an arithmetic overflow would occur. On overflow, the wrapped
/// value is returned.
///
/// This allows chaining together multiple additions to create a wider
/// addition, and can be useful for bignum addition. This method should
/// only be used for the most significant word; for the less significant
/// words the unsigned method
#[doc = "[`u64::carrying_add`]"]
/// should be used.
///
/// The output boolean returned by this method is *not* a carry flag,
/// and should *not* be added to a more significant word.
///
/// If overflow occurred, the wrapped value is returned (negative if overflowed
/// above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
///
/// If the input carry is false, this method is equivalent to
/// [`overflowing_add`](Self::overflowing_add).
///
/// # Examples
///
/// ```
/// #![feature(signed_bigint_helpers)]
/// // Only the most significant word is signed.
/// //
#[doc = "// 10 MAX (a = 10 \u{d7} 2^64 + 2^64 - 1)"]
#[doc = "// + -5 9 (b = -5 \u{d7} 2^64 + 9)"]
/// // ---------
#[doc = "// 6 8 (sum = 6 \u{d7} 2^64 + 8)"]
///
#[doc = "let (a1, a0): (i64, u64) = (10, u64::MAX);"]
#[doc = "let (b1, b0): (i64, u64) = (-5, 9);"]
/// let carry0 = false;
///
#[doc = "// u64::carrying_add for the less significant words"]
/// let (sum0, carry1) = a0.carrying_add(b0, carry0);
/// assert_eq!(carry1, true);
///
#[doc = "// i64::carrying_add for the most significant word"]
/// let (sum1, overflow) = a1.carrying_add(b1, carry1);
/// assert_eq!(overflow, false);
///
/// assert_eq!((sum1, sum0), (6, 8));
/// ```
#[unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
let (a, b) = self.overflowing_add(rhs);
let (c, d) = a.overflowing_add(carry as i64);
(c, b != d)
}
/// Calculates `self` + `rhs` with an unsigned `rhs`.
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i64.overflowing_add_unsigned(2), (3, false));"]
#[doc =
"assert_eq!((i64::MIN).overflowing_add_unsigned(u64::MAX), (i64::MAX, false));"]
#[doc =
"assert_eq!((i64::MAX - 2).overflowing_add_unsigned(3), (i64::MIN, true));"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_add_unsigned(self, rhs: u64) -> (Self, bool) {
let rhs = rhs as Self;
let (res, overflowed) = self.overflowing_add(rhs);
(res, overflowed ^ (rhs < 0))
}
/// Calculates `self` - `rhs`.
///
/// Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
/// would occur. If an overflow would have occurred then the wrapped value is returned
/// (negative if overflowed above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i64.overflowing_sub(2), (3, false));"]
#[doc = "assert_eq!(i64::MIN.overflowing_sub(1), (i64::MAX, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::sub_with_overflow(self as i64, rhs as i64);
(a as Self, b)
}
/// Calculates `self` − `rhs` − `borrow` and checks for
/// overflow.
///
/// Performs "ternary subtraction" by subtracting both an integer
/// operand and a borrow-in bit from `self`, and returns a tuple of the
/// difference along with a boolean indicating whether an arithmetic
/// overflow would occur. On overflow, the wrapped value is returned.
///
/// This allows chaining together multiple subtractions to create a
/// wider subtraction, and can be useful for bignum subtraction. This
/// method should only be used for the most significant word; for the
/// less significant words the unsigned method
#[doc = "[`u64::borrowing_sub`]"]
/// should be used.
///
/// The output boolean returned by this method is *not* a borrow flag,
/// and should *not* be subtracted from a more significant word.
///
/// If overflow occurred, the wrapped value is returned (negative if overflowed
/// above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
///
/// If the input borrow is false, this method is equivalent to
/// [`overflowing_sub`](Self::overflowing_sub).
///
/// # Examples
///
/// ```
/// #![feature(signed_bigint_helpers)]
/// // Only the most significant word is signed.
/// //
#[doc = "// 6 8 (a = 6 \u{d7} 2^64 + 8)"]
#[doc = "// - -5 9 (b = -5 \u{d7} 2^64 + 9)"]
/// // ---------
#[doc = "// 10 MAX (diff = 10 \u{d7} 2^64 + 2^64 - 1)"]
///
#[doc = "let (a1, a0): (i64, u64) = (6, 8);"]
#[doc = "let (b1, b0): (i64, u64) = (-5, 9);"]
/// let borrow0 = false;
///
#[doc = "// u64::borrowing_sub for the less significant words"]
/// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);
/// assert_eq!(borrow1, true);
///
#[doc = "// i64::borrowing_sub for the most significant word"]
/// let (diff1, overflow) = a1.borrowing_sub(b1, borrow1);
/// assert_eq!(overflow, false);
///
#[doc = "assert_eq!((diff1, diff0), (10, u64::MAX));"]
/// ```
#[unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
let (a, b) = self.overflowing_sub(rhs);
let (c, d) = a.overflowing_sub(borrow as i64);
(c, b != d)
}
/// Calculates `self` - `rhs` with an unsigned `rhs`.
///
/// Returns a tuple of the subtraction along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i64.overflowing_sub_unsigned(2), (-1, false));"]
#[doc =
"assert_eq!((i64::MAX).overflowing_sub_unsigned(u64::MAX), (i64::MIN, false));"]
#[doc =
"assert_eq!((i64::MIN + 2).overflowing_sub_unsigned(3), (i64::MAX, true));"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_sub_unsigned(self, rhs: u64) -> (Self, bool) {
let rhs = rhs as Self;
let (res, overflowed) = self.overflowing_sub(rhs);
(res, overflowed ^ (rhs < 0))
}
/// Calculates the multiplication of `self` and `rhs`.
///
/// Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
/// would occur. If an overflow would have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i64.overflowing_mul(2), (10, false));"]
/// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::mul_with_overflow(self as i64, rhs as i64);
(a as Self, b)
}
/// Calculates the "full multiplication" `self * rhs + carry`
/// without the possibility to overflow.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// Performs "long multiplication" which takes in an extra amount to add, and may return an
/// additional amount of overflow. This allows for chaining together multiple
/// multiplications to create "big integers" which represent larger values.
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why [`i32`] is used.
///
/// ```
/// #![feature(signed_bigint_helpers)]
/// assert_eq!(5i32.carrying_mul(-2, 0), (4294967286, -1));
/// assert_eq!(5i32.carrying_mul(-2, 10), (0, 0));
/// assert_eq!(1_000_000_000i32.carrying_mul(-10, 0), (2884901888, -3));
/// assert_eq!(1_000_000_000i32.carrying_mul(-10, 10), (2884901898, -3));
#[doc =
"assert_eq!(i64::MAX.carrying_mul(i64::MAX, i64::MAX), (i64::MAX.unsigned_abs() + 1, i64::MAX / 2));"]
/// ```
#[unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[rustc_const_unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_mul(self, rhs: Self, carry: Self) -> (u64, Self) {
Self::carrying_mul_add(self, rhs, carry, 0)
}
/// Calculates the "full multiplication" `self * rhs + carry + add`
/// without the possibility to overflow.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// Performs "long multiplication" which takes in an extra amount to add, and may return an
/// additional amount of overflow. This allows for chaining together multiple
/// multiplications to create "big integers" which represent larger values.
///
/// If you only need one `carry`, then you can use [`Self::carrying_mul`] instead.
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `i32` is used.
///
/// ```
/// #![feature(signed_bigint_helpers)]
/// assert_eq!(5i32.carrying_mul_add(-2, 0, 0), (4294967286, -1));
/// assert_eq!(5i32.carrying_mul_add(-2, 10, 10), (10, 0));
/// assert_eq!(1_000_000_000i32.carrying_mul_add(-10, 0, 0), (2884901888, -3));
/// assert_eq!(1_000_000_000i32.carrying_mul_add(-10, 10, 10), (2884901908, -3));
#[doc =
"assert_eq!(i64::MAX.carrying_mul_add(i64::MAX, i64::MAX, i64::MAX), (u64::MAX, i64::MAX / 2));"]
/// ```
#[unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[rustc_const_unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_mul_add(self, rhs: Self, carry: Self, add: Self)
-> (u64, Self) {
intrinsics::carrying_mul_add(self, rhs, carry, add)
}
/// Calculates the divisor when `self` is divided by `rhs`.
///
/// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
/// occur. If an overflow would occur then self is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i64.overflowing_div(2), (2, false));"]
#[doc = "assert_eq!(i64::MIN.overflowing_div(-1), (i64::MIN, true));"]
/// ```
#[inline]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_overflowing_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
if intrinsics::unlikely((self == Self::MIN) & (rhs == -1)) {
(self, true)
} else { (self / rhs, false) }
}
/// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
///
/// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
/// occur. If an overflow would occur then `self` is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i64.overflowing_div_euclid(2), (2, false));"]
#[doc = "assert_eq!(i64::MIN.overflowing_div_euclid(-1), (i64::MIN, true));"]
/// ```
#[inline]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
if intrinsics::unlikely((self == Self::MIN) & (rhs == -1)) {
(self, true)
} else { (self.div_euclid(rhs), false) }
}
/// Calculates the remainder when `self` is divided by `rhs`.
///
/// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
/// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i64.overflowing_rem(2), (1, false));"]
#[doc = "assert_eq!(i64::MIN.overflowing_rem(-1), (0, true));"]
/// ```
#[inline]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_overflowing_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
if intrinsics::unlikely(rhs == -1) {
(0, self == Self::MIN)
} else { (self % rhs, false) }
}
/// Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
///
/// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
/// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i64.overflowing_rem_euclid(2), (1, false));"]
#[doc = "assert_eq!(i64::MIN.overflowing_rem_euclid(-1), (0, true));"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
if intrinsics::unlikely(rhs == -1) {
(0, self == Self::MIN)
} else { (self.rem_euclid(rhs), false) }
}
/// Negates self, overflowing if this is equal to the minimum value.
///
/// Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
/// happened. If `self` is the minimum value (e.g., [`i32::MIN`] for values of type [`i32`]), then the
/// minimum value will be returned again and `true` will be returned for an overflow happening.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2i64.overflowing_neg(), (-2, false));"]
#[doc = "assert_eq!(i64::MIN.overflowing_neg(), (i64::MIN, true));"]
/// ```
#[inline]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[allow(unused_attributes)]
pub const fn overflowing_neg(self) -> (Self, bool) {
if intrinsics::unlikely(self == Self::MIN) {
(Self::MIN, true)
} else { (-self, false) }
}
/// Shifts self left by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
/// value was larger than or equal to the number of bits. If the shift value is too large, then value is
/// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1i64.overflowing_shl(4), (0x10, false));"]
/// assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));
#[doc = "assert_eq!(0x10i64.overflowing_shl(63), (0, false));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shl(rhs), rhs >= Self::BITS)
}
/// Shifts self right by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
/// value was larger than or equal to the number of bits. If the shift value is too large, then value is
/// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10i64.overflowing_shr(4), (0x1, false));"]
/// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shr(rhs), rhs >= Self::BITS)
}
/// Computes the absolute value of `self`.
///
/// Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
/// happened. If self is the minimum value
#[doc = "(e.g., [`i64::MIN`] for values of type [`i64`]),"]
/// then the minimum value will be returned again and true will be returned
/// for an overflow happening.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i64.overflowing_abs(), (10, false));"]
#[doc = "assert_eq!((-10i64).overflowing_abs(), (10, false));"]
#[doc = "assert_eq!((i64::MIN).overflowing_abs(), (i64::MIN, true));"]
/// ```
#[stable(feature = "no_panic_abs", since = "1.13.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_abs(self) -> (Self, bool) {
(self.wrapping_abs(), self == Self::MIN)
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// Returns a tuple of the exponentiation along with a bool indicating
/// whether an overflow happened.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3i64.overflowing_pow(4), (81, false));"]
#[doc = "assert_eq!(0_i64.overflowing_pow(0), (1, false));"]
/// assert_eq!(3i8.overflowing_pow(5), (-13, true));
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
let mut base = self;
let mut acc: Self = 1;
let mut overflow = false;
let mut tmp_overflow;
if intrinsics::is_val_statically_known(base) &&
base.unsigned_abs().is_power_of_two() {
let k = base.unsigned_abs().ilog2();
let Some(shift) = k.checked_mul(exp) else { return (0, true) };
let base: Self = if base < 0 && (exp % 2) != 0 { -1 } else { 1 };
return (base.unbounded_shl(shift), base.shl_exact(shift).is_none());
}
if exp == 0 { return (1, false); }
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 {
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
}
exp /= 2;
(base, tmp_overflow) = base.overflowing_mul(base);
overflow |= tmp_overflow;
}
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
return (acc, overflow);
}
loop {
if (exp & 1) == 1 {
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
if exp == 1 { return (acc, overflow); }
}
exp /= 2;
(base, tmp_overflow) = base.overflowing_mul(base);
overflow |= tmp_overflow;
}
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// # Examples
///
/// ```
#[doc = "let x: i64 = 2; // or any other integer type"]
///
/// assert_eq!(x.pow(5), 32);
#[doc = "assert_eq!(0_i64.pow(0), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn pow(self, exp: u32) -> Self {
if intrinsics::overflow_checks() {
self.strict_pow(exp)
} else { self.wrapping_pow(exp) }
}
/// Returns the integer square root of the number, rounded down.
///
/// This function returns the **principal (non-negative) square root**.
/// For a given number `n`, although both `x` and `-x` satisfy x<sup>2</sup> = n,
/// this function always returns the non-negative value.
///
/// # Panics
///
/// This function will panic if `self` is negative.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i64.isqrt(), 3);"]
/// ```
#[stable(feature = "isqrt", since = "1.84.0")]
#[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn isqrt(self) -> Self {
match self.checked_isqrt() {
Some(sqrt) => sqrt,
None => imp::int_sqrt::panic_for_negative_argument(),
}
}
/// Calculates the quotient of Euclidean division of `self` by `rhs`.
///
/// This computes the integer `q` such that `self = q * rhs + r`, with
/// `r = self.rem_euclid(rhs)` and `0 <= r < abs(rhs)`.
///
/// In other words, the result is `self / rhs` rounded to the integer `q`
/// such that `self >= q * rhs`.
/// If `self > 0`, this is equal to rounding towards zero (the default in Rust);
/// if `self < 0`, this is equal to rounding away from zero (towards +/- infinity).
/// If `rhs > 0`, this is equal to rounding towards -infinity;
/// if `rhs < 0`, this is equal to rounding towards +infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero or if `self` is [`Self::MIN`]
/// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
///
/// # Examples
///
/// ```
#[doc = "let a: i64 = 7; // or any other integer type"]
/// let b = 4;
///
/// assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
/// assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
/// assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
/// assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_euclid(self, rhs: Self) -> Self {
let q = self / rhs;
if self % rhs < 0 { return if rhs > 0 { q - 1 } else { q + 1 } }
q
}
/// Calculates the least nonnegative remainder of `self` when
/// divided by `rhs`.
///
/// This is done as if by the Euclidean division algorithm -- given
/// `r = self.rem_euclid(rhs)`, the result satisfies
/// `self = rhs * self.div_euclid(rhs) + r` and `0 <= r < abs(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero or if `self` is [`Self::MIN`] and
/// `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
///
/// # Examples
///
/// ```
#[doc = "let a: i64 = 7; // or any other integer type"]
/// let b = 4;
///
/// assert_eq!(a.rem_euclid(b), 3);
/// assert_eq!((-a).rem_euclid(b), 1);
/// assert_eq!(a.rem_euclid(-b), 3);
/// assert_eq!((-a).rem_euclid(-b), 1);
/// ```
///
/// This will panic:
/// ```should_panic
#[doc = "let _ = i64::MIN.rem_euclid(-1);"]
/// ```
#[doc(alias = "modulo", alias = "mod")]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn rem_euclid(self, rhs: Self) -> Self {
let r = self % rhs;
if r < 0 { r.wrapping_add(rhs.wrapping_abs()) } else { r }
}
/// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero or if `self` is [`Self::MIN`]
/// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "let a: i64 = 8;"]
/// let b = 3;
///
/// assert_eq!(a.div_floor(b), 2);
/// assert_eq!(a.div_floor(-b), -3);
/// assert_eq!((-a).div_floor(b), -3);
/// assert_eq!((-a).div_floor(-b), 2);
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_floor(self, rhs: Self) -> Self {
let d = self / rhs;
let r = self % rhs;
let correction = (self ^ rhs) >> (Self::BITS - 1);
if r != 0 { d + correction } else { d }
}
/// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero or if `self` is [`Self::MIN`]
/// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "let a: i64 = 8;"]
/// let b = 3;
///
/// assert_eq!(a.div_ceil(b), 3);
/// assert_eq!(a.div_ceil(-b), -2);
/// assert_eq!((-a).div_ceil(b), -2);
/// assert_eq!((-a).div_ceil(-b), 3);
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_ceil(self, rhs: Self) -> Self {
let d = self / rhs;
let r = self % rhs;
let correction = 1 + ((self ^ rhs) >> (Self::BITS - 1));
if r != 0 { d + correction } else { d }
}
/// If `rhs` is positive, calculates the smallest value greater than or
/// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
/// calculates the largest value less than or equal to `self` that is a
/// multiple of `rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// On overflow, this function will panic if overflow checks are enabled (default in debug
/// mode) and wrap if overflow checks are disabled (default in release mode).
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "assert_eq!(16_i64.next_multiple_of(8), 16);"]
#[doc = "assert_eq!(23_i64.next_multiple_of(8), 24);"]
#[doc = "assert_eq!(16_i64.next_multiple_of(-8), 16);"]
#[doc = "assert_eq!(23_i64.next_multiple_of(-8), 16);"]
#[doc = "assert_eq!((-16_i64).next_multiple_of(8), -16);"]
#[doc = "assert_eq!((-23_i64).next_multiple_of(8), -16);"]
#[doc = "assert_eq!((-16_i64).next_multiple_of(-8), -16);"]
#[doc = "assert_eq!((-23_i64).next_multiple_of(-8), -24);"]
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_multiple_of(self, rhs: Self) -> Self {
if rhs == -1 { return self; }
let r = self % rhs;
let m =
if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) { r + rhs } else { r };
if m == 0 { self } else { self + (rhs - m) }
}
/// If `rhs` is positive, calculates the smallest value greater than or
/// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
/// calculates the largest value less than or equal to `self` that is a
/// multiple of `rhs`. Returns `None` if `rhs` is zero or the operation
/// would result in overflow.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "assert_eq!(16_i64.checked_next_multiple_of(8), Some(16));"]
#[doc = "assert_eq!(23_i64.checked_next_multiple_of(8), Some(24));"]
#[doc = "assert_eq!(16_i64.checked_next_multiple_of(-8), Some(16));"]
#[doc = "assert_eq!(23_i64.checked_next_multiple_of(-8), Some(16));"]
#[doc = "assert_eq!((-16_i64).checked_next_multiple_of(8), Some(-16));"]
#[doc = "assert_eq!((-23_i64).checked_next_multiple_of(8), Some(-16));"]
#[doc = "assert_eq!((-16_i64).checked_next_multiple_of(-8), Some(-16));"]
#[doc = "assert_eq!((-23_i64).checked_next_multiple_of(-8), Some(-24));"]
#[doc = "assert_eq!(1_i64.checked_next_multiple_of(0), None);"]
#[doc = "assert_eq!(i64::MAX.checked_next_multiple_of(2), None);"]
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
if rhs == -1 { return Some(self); }
let r =
match self.checked_rem(rhs) { Some(x) => x, None => return None, };
let m =
if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) { r + rhs } else { r };
if m == 0 { Some(self) } else { self.checked_add(rhs - m) }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// This method might not be optimized owing to implementation details;
/// [`ilog2`][Self::ilog2] can produce results more efficiently for base 2,
/// and [`ilog10`](Self::ilog10) can produce results more efficiently for base 10.
///
/// # Panics
///
/// This function will panic if `self` is less than or equal to zero,
/// or if `base` is less than 2.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i64.ilog(5), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog(self, base: Self) -> u32 {
if !(base >= 2) {
{
crate::panicking::panic_fmt(format_args!("base of integer logarithm must be at least 2"));
}
};
if let Some(log) = self.checked_ilog(base) {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the base 2 logarithm of the number, rounded down.
///
/// # Panics
///
/// This function will panic if `self` is less than or equal to zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2i64.ilog2(), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog2(self) -> u32 {
if let Some(log) = self.checked_ilog2() {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// # Panics
///
/// This function will panic if `self` is less than or equal to zero.
///
/// # Example
///
/// ```
#[doc = "assert_eq!(10i64.ilog10(), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog10(self) -> u32 {
if let Some(log) = self.checked_ilog10() {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// Returns `None` if the number is negative or zero, or if the base is not at least 2.
///
/// This method might not be optimized owing to implementation details;
/// `checked_ilog2` can produce results more efficiently for base 2, and
/// `checked_ilog10` can produce results more efficiently for base 10.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i64.checked_ilog(5), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog(self, base: Self) -> Option<u32> {
if self <= 0 || base <= 1 {
None
} else { (self as u64).checked_ilog(base as u64) }
}
/// Returns the base 2 logarithm of the number, rounded down.
///
/// Returns `None` if the number is negative or zero.
///
/// Note that for non-negative numbers, this is equivalent to
/// [`highest_one`](Self::highest_one).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2i64.checked_ilog2(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog2(self) -> Option<u32> {
if self <= 0 {
None
} else {
let log =
(Self::BITS - 1) -
unsafe { intrinsics::ctlz_nonzero(self) as u32 };
Some(log)
}
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// Returns `None` if the number is negative or zero.
///
/// # Example
///
/// ```
#[doc = "assert_eq!(10i64.checked_ilog10(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog10(self) -> Option<u32> {
imp::int_log10::i64(self as i64)
}
/// Computes the absolute value of `self`.
///
/// # Overflow behavior
///
/// The absolute value of
#[doc = "`i64::MIN`"]
/// cannot be represented as an
#[doc = "`i64`,"]
/// and attempting to calculate it will cause an overflow. This means
/// that code in debug mode will trigger a panic on this case and
/// optimized code will return
#[doc = "`i64::MIN`"]
/// without a panic. If you do not want this behavior, consider
/// using [`unsigned_abs`](Self::unsigned_abs) instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i64.abs(), 10);"]
#[doc = "assert_eq!((-10i64).abs(), 10);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[allow(unused_attributes)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn abs(self) -> Self {
if self.is_negative() { -self } else { self }
}
/// Computes the absolute difference between `self` and `other`.
///
/// This function always returns the correct answer without overflow or
/// panics by returning an unsigned integer.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i64.abs_diff(80), 20u64);"]
#[doc = "assert_eq!(100i64.abs_diff(110), 10u64);"]
#[doc = "assert_eq!((-100i64).abs_diff(80), 180u64);"]
#[doc = "assert_eq!((-100i64).abs_diff(-120), 20u64);"]
#[doc = "assert_eq!(i64::MIN.abs_diff(i64::MAX), u64::MAX);"]
/// ```
#[stable(feature = "int_abs_diff", since = "1.60.0")]
#[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn abs_diff(self, other: Self) -> u64 {
if self < other {
(other as u64).wrapping_sub(self as u64)
} else { (self as u64).wrapping_sub(other as u64) }
}
/// Returns a number representing sign of `self`.
///
/// - `0` if the number is zero
/// - `1` if the number is positive
/// - `-1` if the number is negative
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i64.signum(), 1);"]
#[doc = "assert_eq!(0i64.signum(), 0);"]
#[doc = "assert_eq!((-10i64).signum(), -1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_sign", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn signum(self) -> Self {
crate::intrinsics::three_way_compare(self, 0) as Self
}
/// Returns `true` if `self` is positive and `false` if the number is zero or
/// negative.
///
/// # Examples
///
/// ```
#[doc = "assert!(10i64.is_positive());"]
#[doc = "assert!(!(-10i64).is_positive());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[inline(always)]
pub const fn is_positive(self) -> bool { self > 0 }
/// Returns `true` if `self` is negative and `false` if the number is zero or
/// positive.
///
/// # Examples
///
/// ```
#[doc = "assert!((-10i64).is_negative());"]
#[doc = "assert!(!10i64.is_negative());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[inline(always)]
pub const fn is_negative(self) -> bool { self < 0 }
/// Returns the memory representation of this integer as a byte array in
/// big-endian (network) byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234567890123456i64.to_be_bytes();"]
#[doc =
"assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
self.to_be().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// little-endian byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234567890123456i64.to_le_bytes();"]
#[doc =
"assert_eq!(bytes, [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
self.to_le().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code
/// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
/// instead.
///
#[doc = ""]
///
/// [`to_be_bytes`]: Self::to_be_bytes
/// [`to_le_bytes`]: Self::to_le_bytes
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234567890123456i64.to_ne_bytes();"]
/// assert_eq!(
/// bytes,
/// if cfg!(target_endian = "big") {
#[doc = " [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]"]
/// } else {
#[doc = " [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]"]
/// }
/// );
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
unsafe { mem::transmute(self) }
}
/// Creates an integer value from its representation as a byte array in
/// big endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc =
"let value = i64::from_be_bytes([0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]);"]
#[doc = "assert_eq!(value, 0x1234567890123456);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_be_i64(input: &mut &[u8]) -> i64 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i64>());"]
/// *input = rest;
#[doc = " i64::from_be_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_be(Self::from_ne_bytes(bytes))
}
/// Creates an integer value from its representation as a byte array in
/// little endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc =
"let value = i64::from_le_bytes([0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);"]
#[doc = "assert_eq!(value, 0x1234567890123456);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_le_i64(input: &mut &[u8]) -> i64 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i64>());"]
/// *input = rest;
#[doc = " i64::from_le_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_le(Self::from_ne_bytes(bytes))
}
/// Creates an integer value from its memory representation as a byte
/// array in native endianness.
///
/// As the target platform's native endianness is used, portable code
/// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
/// appropriate instead.
///
/// [`from_be_bytes`]: Self::from_be_bytes
/// [`from_le_bytes`]: Self::from_le_bytes
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = i64::from_ne_bytes(if cfg!(target_endian = \"big\") {"]
#[doc = " [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]"]
/// } else {
#[doc = " [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]"]
/// });
#[doc = "assert_eq!(value, 0x1234567890123456);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_ne_i64(input: &mut &[u8]) -> i64 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i64>());"]
/// *input = rest;
#[doc = " i64::from_ne_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use]
#[inline]
pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
unsafe { mem::transmute(bytes) }
}
/// New code should prefer to use
#[doc = "[`i64::MIN`] instead."]
///
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MIN` associated constant on this type")]
#[rustc_diagnostic_item = "i64_legacy_fn_min_value"]
pub const fn min_value() -> Self { Self::MIN }
/// New code should prefer to use
#[doc = "[`i64::MAX`] instead."]
///
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MAX` associated constant on this type")]
#[rustc_diagnostic_item = "i64_legacy_fn_max_value"]
pub const fn max_value() -> Self { Self::MAX }
/// Clamps this number to a symmetric range centred around zero.
///
/// The method clamps the number's magnitude (absolute value) to be at most `limit`.
///
/// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
/// explicit about the intent.
///
/// # Examples
///
/// ```
/// #![feature(clamp_magnitude)]
#[doc = "assert_eq!(120i64.clamp_magnitude(100), 100);"]
#[doc = "assert_eq!(-120i64.clamp_magnitude(100), -100);"]
#[doc = "assert_eq!(80i64.clamp_magnitude(100), 80);"]
#[doc = "assert_eq!(-80i64.clamp_magnitude(100), -80);"]
/// ```
#[must_use =
"this returns the clamped value and does not modify the original"]
#[unstable(feature = "clamp_magnitude", issue = "148519")]
#[inline]
pub fn clamp_magnitude(self, limit: u64) -> Self {
if let Ok(limit) = core::convert::TryInto::<i64>::try_into(limit) {
self.clamp(-limit, limit)
} else { self }
}
/// Truncate an integer to an integer of the same size or smaller, preserving the least
/// significant bits.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i8, 120i64.truncate());"]
#[doc = "assert_eq!(-120i8, (-120i64).truncate());"]
/// assert_eq!(120i8, 376i32.truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
/// instead of truncating.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i8, 120i64.saturating_truncate());"]
#[doc = "assert_eq!(-120i8, (-120i64).saturating_truncate());"]
/// assert_eq!(127i8, 376i32.saturating_truncate());
/// assert_eq!(-128i8, (-1000i32).saturating_truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn saturating_truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_saturating_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
/// is outside the bounds of the smaller type.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(Some(120i8), 120i64.checked_truncate());"]
#[doc = "assert_eq!(Some(-120i8), (-120i64).checked_truncate());"]
/// assert_eq!(None, 376i32.checked_truncate::<i8>());
/// assert_eq!(None, (-1000i32).checked_truncate::<i8>());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn checked_truncate<Target>(self) -> Option<Target> where
Self: [const] traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_checked_truncate(self)
}
/// Widen to an integer of the same size or larger, preserving its value.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i128, 120i8.widen());"]
#[doc = "assert_eq!(-120i128, (-120i8).widen());"]
/// ```
#[must_use =
"this returns the widened value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn widen<Target>(self) -> Target where Self: [const]
traits::WidenTarget<Target> {
traits::WidenTarget::internal_widen(self)
}
/// Converts `self` to the target integer type, saturating at the numeric
/// bounds instead of overflowing.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(i8::MAX, i64::MAX.saturating_cast());"]
#[doc = "assert_eq!(i8::MIN, i64::MIN.saturating_cast());"]
#[doc = "assert_eq!(42u8, 42i64.saturating_cast());"]
#[doc = "assert_eq!(0u8, (-42i64).saturating_cast());"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn saturating_cast<T: [const] BoundedCastFromInt<Self>>(self) -> T {
T::saturating_cast_from(self)
}
/// Converts `self` to the target integer type, wrapping around at the
/// boundary of the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(i64::MAX as i8, i64::MAX.wrapping_cast());"]
#[doc = "assert_eq!(i64::MIN as i8, i64::MIN.wrapping_cast());"]
#[doc = "assert_eq!(42u8, 42i64.wrapping_cast());"]
#[doc = "assert_eq!(u8::MAX - 41, (-42i64).wrapping_cast());"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn wrapping_cast<T: [const] BoundedCastFromInt<Self>>(self) -> T {
T::wrapping_cast_from(self)
}
/// Converts `self` to the target integer type, returning `None` if the value
/// is not representable by the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(Some(42u8), 42i64.checked_cast());"]
#[doc = "assert_eq!((-42i64).checked_cast::<u8>(), None);"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn checked_cast<T: [const] CheckedCastFromInt<Self>>(self)
-> Option<T> {
T::checked_cast_from(self)
}
/// Converts `self` to the target integer type, panicking if the value
/// is not representable by the target type.
///
/// # Panics
///
/// This function will panic if the value is not representable by the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(42u8, 42i64.strict_cast());"]
/// ```
///
/// The following will panic:
///
/// ```should_panic
/// #![feature(integer_casts)]
#[doc = "let _ = (-42i64).strict_cast::<u8>();"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
#[track_caller]
pub const fn strict_cast<T: [const] CheckedCastFromInt<Self>>(self) -> T {
T::strict_cast_from(self)
}
/// Converts `self` to the target integer type, assuming the value is
/// representable by the target type.
///
/// # Safety
///
/// This results in undefined behavior if the integer value of `self` is bigger than `T::MAX`,
/// or smaller than `T::MIN`, where `T` is the target type.
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const unsafe fn unchecked_cast<T: [const] CheckedCastFromInt<Self>>(self)
-> T {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(in_bounds: bool) {
if !in_bounds {
let msg =
"unsafe precondition(s) violated: i64::unchecked_cast must fit in the target type\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check({
let cast_val = self.checked_cast::<T>();
let ret = cast_val.is_some();
core::mem::forget(cast_val);
ret
});
}
};
unsafe { T::unchecked_cast_from(self) }
}int_impl! {
452Self = i64,
453 ActualT = i64,
454 UnsignedT = u64,
455 BITS = 64,
456 BITS_MINUS_ONE = 63,
457 Min = -9223372036854775808,
458 Max = 9223372036854775807,
459 rot = 12,
460 rot_op = "0xaa00000000006e1",
461 rot_result = "0x6e10aa",
462 swap_op = "0x1234567890123456",
463 swapped = "0x5634129078563412",
464 reversed = "0x6a2c48091e6a2c48",
465 le_bytes = "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
466 be_bytes = "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
467 to_xe_bytes_doc = "",
468 from_xe_bytes_doc = "",
469 bound_condition = "",
470 }471/// Calculates the midpoint (average) between `self` and `rhs`.
///
/// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
/// sufficiently-large signed integral type. This implies that the result is
/// always rounded towards zero and that no overflow will ever occur.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0i64.midpoint(4), 2);"]
#[doc = "assert_eq!((-1i64).midpoint(2), 0);"]
#[doc = "assert_eq!((-7i64).midpoint(0), -3);"]
#[doc = "assert_eq!(0i64.midpoint(-7), -3);"]
#[doc = "assert_eq!(0i64.midpoint(7), 3);"]
/// ```
#[stable(feature = "num_midpoint_signed", since = "1.87.0")]
#[rustc_const_stable(feature = "num_midpoint_signed", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[doc(alias = "average_floor")]
#[doc(alias = "average_ceil")]
#[doc(alias = "average")]
#[inline]
pub const fn midpoint(self, rhs: Self) -> Self {
let t = ((self ^ rhs) >> 1) + (self & rhs);
t + (if t < 0 { 1 } else { 0 } & (self ^ rhs))
}midpoint_impl! { i64, signed }472/// Widening multiplication. Computes `self * rhs`, widening to a larger integer.
///
/// The returned value is always exact and can never overflow.
///
/// Note that this method is semantically equivalent to [`carrying_mul`] with a
/// carry of zero, with the latter instead returning a tuple denoting the low and
/// high parts of the result. Consider using it instead if you need
/// interoperability with other big int helper functions, or if this method isn't
/// available for a given type.
///
/// [`carrying_mul`]: Self::carrying_mul
///
/// # Examples
///
/// ```
/// #![feature(widening_mul)]
///
#[doc = "assert_eq!(i64::MAX.widening_mul(0_i64), 0);"]
#[doc =
"assert_eq!(i64::MAX.widening_mul(i64::MAX), i64::MAX as i128 * i64::MAX as i128);"]
/// ```
#[unstable(feature = "widening_mul", issue = "152016")]
#[rustc_const_unstable(feature = "widening_mul", issue = "152016")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn widening_mul(self, rhs: Self) -> i128 {
self as i128 * rhs as i128
}widening_mul_impl! { i64, i128 }473}
474475impl i128 {
476/// The smallest value that can be represented by this integer type
#[doc = "(−2<sup>127</sup>)."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i128::MIN, -170141183460469231731687303715884105728);"]
/// ```
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MIN: Self = !Self::MAX;
/// The largest value that can be represented by this integer type
#[doc = "(2<sup>127</sup> − 1)."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i128::MAX, 170141183460469231731687303715884105727);"]
/// ```
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MAX: Self = (<u128>::MAX >> 1) as Self;
/// The size of this integer type in bits.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i128::BITS, 128);"]
/// ```
#[stable(feature = "int_bits_const", since = "1.53.0")]
pub const BITS: u32 = <u128>::BITS;
/// Returns the number of ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 0b100_0000i128;"]
///
/// assert_eq!(n.count_ones(), 1);
/// ```
///
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[doc(alias = "popcount")]
#[doc(alias = "popcnt")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn count_ones(self) -> u32 { (self as u128).count_ones() }
/// Returns the number of zeros in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i128::MAX.count_zeros(), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn count_zeros(self) -> u32 { (!self).count_ones() }
/// Returns the number of leading zeros in the binary representation of `self`.
///
/// Depending on what you're doing with the value, you might also be interested in the
/// [`ilog2`] function which returns a consistent number, even if the type widens.
///
/// # Examples
///
/// ```
#[doc = "let n = -1i128;"]
///
/// assert_eq!(n.leading_zeros(), 0);
/// ```
#[doc = "[`ilog2`]: i128::ilog2"]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn leading_zeros(self) -> u32 { (self as u128).leading_zeros() }
/// Returns the number of trailing zeros in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = -4i128;"]
///
/// assert_eq!(n.trailing_zeros(), 2);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn trailing_zeros(self) -> u32 { (self as u128).trailing_zeros() }
/// Returns the number of leading ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = -1i128;"]
///
#[doc = "assert_eq!(n.leading_ones(), 128);"]
/// ```
#[stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn leading_ones(self) -> u32 { (self as u128).leading_ones() }
/// Returns the number of trailing ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 3i128;"]
///
/// assert_eq!(n.trailing_ones(), 2);
/// ```
#[stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn trailing_ones(self) -> u32 { (self as u128).trailing_ones() }
/// Returns `self` with only the most significant bit set, or `0` if
/// the input is `0`.
///
/// # Examples
///
/// ```
#[doc = "let n: i128 = 0b_01100100;"]
///
/// assert_eq!(n.isolate_highest_one(), 0b_01000000);
#[doc = "assert_eq!(0_i128.isolate_highest_one(), 0);"]
/// ```
#[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn isolate_highest_one(self) -> Self {
self &
(((1 as i128) <<
(<i128>::BITS - 1)).wrapping_shr(self.leading_zeros()))
}
/// Returns `self` with only the least significant bit set, or `0` if
/// the input is `0`.
///
/// # Examples
///
/// ```
#[doc = "let n: i128 = 0b_01100100;"]
///
/// assert_eq!(n.isolate_lowest_one(), 0b_00000100);
#[doc = "assert_eq!(0_i128.isolate_lowest_one(), 0);"]
/// ```
#[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn isolate_lowest_one(self) -> Self { self & self.wrapping_neg() }
/// Returns the index of the highest bit set to one in `self`, or `None`
/// if `self` is `0`.
///
/// Note that for non-negative numbers, this is equivalent to
/// [`checked_ilog2`](Self::checked_ilog2).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0b0_i128.highest_one(), None);"]
#[doc = "assert_eq!(0b1_i128.highest_one(), Some(0));"]
#[doc = "assert_eq!(0b1_0000_i128.highest_one(), Some(4));"]
#[doc = "assert_eq!(0b1_1111_i128.highest_one(), Some(4));"]
/// ```
#[stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn highest_one(self) -> Option<u32> { (self as u128).highest_one() }
/// Returns the index of the lowest bit set to one in `self`, or `None`
/// if `self` is `0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0b0_i128.lowest_one(), None);"]
#[doc = "assert_eq!(0b1_i128.lowest_one(), Some(0));"]
#[doc = "assert_eq!(0b1_0000_i128.lowest_one(), Some(4));"]
#[doc = "assert_eq!(0b1_1111_i128.lowest_one(), Some(0));"]
/// ```
#[stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn lowest_one(self) -> Option<u32> { (self as u128).lowest_one() }
/// Returns the bit pattern of `self` reinterpreted as an unsigned integer of the same size.
///
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
/// the same.
///
/// # Examples
///
/// ```
#[doc = "let n = -1i128;"]
///
#[doc = "assert_eq!(n.cast_unsigned(), u128::MAX);"]
/// ```
#[stable(feature = "integer_sign_cast", since = "1.87.0")]
#[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_unsigned(self) -> u128 { self as u128 }
/// Saturating conversion of `self` to an unsigned integer of the same size.
///
/// Negative values are clamped to `0`.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`checked_cast_unsigned`](Self::checked_cast_unsigned),
/// or [`strict_cast_unsigned`](Self::strict_cast_unsigned).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = i128::MIN;"]
///
#[doc = "assert_eq!(n.saturating_cast_unsigned(), 0u128);"]
#[doc = "assert_eq!(64i128.saturating_cast_unsigned(), 64u128);"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_cast_unsigned(self) -> u128 {
if self >= 0 { self.cast_unsigned() } else { 0 }
}
/// Checked conversion of `self` to an unsigned integer of the same size,
/// returning `None` if `self` is negative.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`saturating_cast_unsigned`](Self::saturating_cast_unsigned),
/// or [`strict_cast_unsigned`](Self::strict_cast_unsigned).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = i128::MIN;"]
///
#[doc = "assert_eq!(n.checked_cast_unsigned(), None);"]
#[doc = "assert_eq!(64i128.checked_cast_unsigned(), Some(64u128));"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn checked_cast_unsigned(self) -> Option<u128> {
if self >= 0 { Some(self.cast_unsigned()) } else { None }
}
/// Strict conversion of `self` to an unsigned integer of the same size,
/// which panics if `self` is negative.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`checked_cast_unsigned`](Self::checked_cast_unsigned),
/// or [`saturating_cast_unsigned`](Self::saturating_cast_unsigned).
///
/// # Examples
///
/// ```should_panic
/// #![feature(integer_cast_extras)]
#[doc = "let _ = i128::MIN.strict_cast_unsigned();"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_cast_unsigned(self) -> u128 {
match self.checked_cast_unsigned() {
Some(n) => n,
None => imp::overflow_panic::cast_integer(),
}
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `<<` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x13f40000000000000000000000004f76i128;"]
#[doc = "let m = 0x4f7613f4;"]
///
#[doc = "assert_eq!(n.rotate_left(16), m);"]
#[doc = "assert_eq!(n.rotate_left(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn rotate_left(self, n: u32) -> Self {
(self as u128).rotate_left(n) as Self
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `>>` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x4f7613f4i128;"]
#[doc = "let m = 0x13f40000000000000000000000004f76;"]
///
#[doc = "assert_eq!(n.rotate_right(16), m);"]
#[doc = "assert_eq!(n.rotate_right(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn rotate_right(self, n: u32) -> Self {
(self as u128).rotate_right(n) as Self
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x12345678901234567890123456789012i128;"]
///
/// let m = n.swap_bytes();
///
#[doc = "assert_eq!(m, 0x12907856341290785634129078563412);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn swap_bytes(self) -> Self { (self as u128).swap_bytes() as Self }
/// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
/// second least-significant bit becomes second most-significant bit, etc.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x12345678901234567890123456789012i128;"]
/// let m = n.reverse_bits();
///
#[doc = "assert_eq!(m, 0x48091e6a2c48091e6a2c48091e6a2c48);"]
#[doc = "assert_eq!(0, 0i128.reverse_bits());"]
/// ```
#[stable(feature = "reverse_bits", since = "1.37.0")]
#[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn reverse_bits(self) -> Self {
(self as u128).reverse_bits() as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are swapped.
///
/// See also [from_be_bytes()](Self::from_be_bytes).
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai128;"]
///
/// if cfg!(target_endian = "big") {
#[doc = " assert_eq!(i128::from_be(n), n)"]
/// } else {
#[doc = " assert_eq!(i128::from_be(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn from_be(x: Self) -> Self { x.swap_bytes() }
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are swapped.
///
/// See also [from_le_bytes()](Self::from_le_bytes).
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai128;"]
///
/// if cfg!(target_endian = "little") {
#[doc = " assert_eq!(i128::from_le(n), n)"]
/// } else {
#[doc = " assert_eq!(i128::from_le(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn from_le(x: Self) -> Self { x }
/// Swaps bytes of `self` on little endian targets.
///
/// On big endian this is a no-op.
///
/// The returned value has the same type as `self`, and will be interpreted
/// as (a potentially different) value of a native-endian
#[doc = "`i128`."]
///
/// See [`to_be_bytes()`](Self::to_be_bytes) for a type-safe alternative.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai128;"]
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be(self) -> Self { self.swap_bytes() }
/// Swaps bytes of `self` on big endian targets.
///
/// On little endian this is a no-op.
///
/// The returned value has the same type as `self`, and will be interpreted
/// as (a potentially different) value of a native-endian
#[doc = "`i128`."]
///
/// See [`to_le_bytes()`](Self::to_le_bytes) for a type-safe alternative.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai128;"]
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le(self) -> Self { self }
/// Checked integer addition. Computes `self + rhs`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i128::MAX - 2).checked_add(1), Some(i128::MAX - 1));"]
#[doc = "assert_eq!((i128::MAX - 2).checked_add(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_add(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer addition. Computes `self + rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i128::MAX - 2).strict_add(1), i128::MAX - 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i128::MAX - 2).strict_add(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_add(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Unchecked integer addition. Computes `self + rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_add(y)` is semantically equivalent to calling
/// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_add`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self + rhs > i128::MAX` or `self + rhs < i128::MIN`,"]
/// i.e. when [`checked_add`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_add`]: i128::checked_add"]
#[doc = "[`wrapping_add`]: i128::wrapping_add"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i128, rhs: i128) {
if !!lhs.overflowing_add(rhs).1 {
let msg =
"unsafe precondition(s) violated: i128::unchecked_add cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_add(self, rhs) }
}
/// Checked addition with an unsigned integer. Computes `self + rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i128.checked_add_unsigned(2), Some(3));"]
#[doc = "assert_eq!((i128::MAX - 2).checked_add_unsigned(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add_unsigned(self, rhs: u128) -> Option<Self> {
let (a, b) = self.overflowing_add_unsigned(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict addition with an unsigned integer. Computes `self + rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i128.strict_add_unsigned(2), 3);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i128::MAX - 2).strict_add_unsigned(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add_unsigned(self, rhs: u128) -> Self {
let (a, b) = self.overflowing_add_unsigned(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Checked integer subtraction. Computes `self - rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i128::MIN + 2).checked_sub(1), Some(i128::MIN + 1));"]
#[doc = "assert_eq!((i128::MIN + 2).checked_sub(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_sub(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer subtraction. Computes `self - rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i128::MIN + 2).strict_sub(1), i128::MIN + 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i128::MIN + 2).strict_sub(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_sub(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
/// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_sub`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self - rhs > i128::MAX` or `self - rhs < i128::MIN`,"]
/// i.e. when [`checked_sub`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_sub`]: i128::checked_sub"]
#[doc = "[`wrapping_sub`]: i128::wrapping_sub"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i128, rhs: i128) {
if !!lhs.overflowing_sub(rhs).1 {
let msg =
"unsafe precondition(s) violated: i128::unchecked_sub cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_sub(self, rhs) }
}
/// Checked subtraction with an unsigned integer. Computes `self - rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i128.checked_sub_unsigned(2), Some(-1));"]
#[doc = "assert_eq!((i128::MIN + 2).checked_sub_unsigned(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub_unsigned(self, rhs: u128) -> Option<Self> {
let (a, b) = self.overflowing_sub_unsigned(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict subtraction with an unsigned integer. Computes `self - rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i128.strict_sub_unsigned(2), -1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i128::MIN + 2).strict_sub_unsigned(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub_unsigned(self, rhs: u128) -> Self {
let (a, b) = self.overflowing_sub_unsigned(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Checked integer multiplication. Computes `self * rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i128::MAX.checked_mul(1), Some(i128::MAX));"]
#[doc = "assert_eq!(i128::MAX.checked_mul(2), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer multiplication. Computes `self * rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i128::MAX.strict_mul(1), i128::MAX);"]
/// ```
///
/// The following panics because of overflow:
///
/// ``` should_panic
#[doc = "let _ = i128::MAX.strict_mul(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_mul(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_mul(rhs);
if b { imp::overflow_panic::mul() } else { a }
}
/// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
/// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_mul`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self * rhs > i128::MAX` or `self * rhs < i128::MIN`,"]
/// i.e. when [`checked_mul`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_mul`]: i128::checked_mul"]
#[doc = "[`wrapping_mul`]: i128::wrapping_mul"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i128, rhs: i128) {
if !!lhs.overflowing_mul(rhs).1 {
let msg =
"unsafe precondition(s) violated: i128::unchecked_mul cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_mul(self, rhs) }
}
/// Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
/// or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc =
"assert_eq!((i128::MIN + 1).checked_div(-1), Some(170141183460469231731687303715884105727));"]
#[doc = "assert_eq!(i128::MIN.checked_div(-1), None);"]
#[doc = "assert_eq!((1i128).checked_div(0), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1)))
{
None
} else { Some(unsafe { intrinsics::unchecked_div(self, rhs) }) }
}
/// Strict integer division. Computes `self / rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is when one divides `MIN / -1` on a signed type (where
/// [`MIN`](Self::MIN) is the negative minimal value for the type); the result of this is `-MIN`, a positive value
/// that is too large to represent in the type.
///
/// Note that this is equivalent to normal division: `MIN / -1` will also panic both in
/// debug and release builds.
///
/// # Examples
///
/// ```
#[doc =
"assert_eq!((i128::MIN + 1).strict_div(-1), 170141183460469231731687303715884105727);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i128::MIN.strict_div(-1);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1i128).strict_div(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_div(self, rhs: Self) -> Self { self / rhs }
/// Checked Euclidean division. Computes `self.div_euclid(rhs)`,
/// returning `None` if `rhs == 0` or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc =
"assert_eq!((i128::MIN + 1).checked_div_euclid(-1), Some(170141183460469231731687303715884105727));"]
#[doc = "assert_eq!(i128::MIN.checked_div_euclid(-1), None);"]
#[doc = "assert_eq!((1i128).checked_div_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) {
None
} else { Some(self.div_euclid(rhs)) }
}
/// Strict Euclidean division. Computes `self.div_euclid(rhs)`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is when one divides `MIN / -1` on a signed type (where
/// [`MIN`](Self::MIN) is the negative minimal value for the type); the result of this is `-MIN`, a positive value
/// that is too large to represent in the type.
///
/// Note that this is equivalent to `div_euclid`: `MIN.div_euclid(-1)` will also panic both
/// in debug and release builds.
///
/// # Examples
///
/// ```
#[doc =
"assert_eq!((i128::MIN + 1).strict_div_euclid(-1), 170141183460469231731687303715884105727);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i128::MIN.strict_div_euclid(-1);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1i128).strict_div_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_div_euclid(self, rhs: Self) -> Self {
self.div_euclid(rhs)
}
/// Checked integer division without remainder. Computes `self / rhs`,
/// returning `None` if `rhs == 0`, the division results in overflow,
/// or `self % rhs != 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc =
"assert_eq!((i128::MIN + 1).checked_div_exact(-1), Some(170141183460469231731687303715884105727));"]
#[doc = "assert_eq!((-5i128).checked_div_exact(2), None);"]
#[doc = "assert_eq!(i128::MIN.checked_div_exact(-1), None);"]
#[doc = "assert_eq!((1i128).checked_div_exact(0), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_exact(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1)))
{
None
} else {
unsafe {
if intrinsics::unlikely(intrinsics::unchecked_rem(self, rhs) != 0)
{
None
} else { Some(intrinsics::exact_div(self, rhs)) }
}
}
}
/// Integer division without remainder. Computes `self / rhs`, returning `None` if `self % rhs != 0`.
///
/// # Panics
///
/// This function will panic if `rhs == 0`.
///
/// ## Overflow behavior
///
/// On overflow, this function will panic if overflow checks are enabled (default in debug
/// mode) and wrap if overflow checks are disabled (default in release mode).
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64i128.div_exact(2), Some(32));"]
#[doc = "assert_eq!(64i128.div_exact(32), Some(2));"]
#[doc =
"assert_eq!((i128::MIN + 1).div_exact(-1), Some(170141183460469231731687303715884105727));"]
#[doc = "assert_eq!(65i128.div_exact(2), None);"]
/// ```
/// ```should_panic
/// #![feature(exact_div)]
#[doc = "let _ = 64i128.div_exact(0);"]
/// ```
/// ```should_panic
/// #![feature(exact_div)]
#[doc = "let _ = i128::MIN.div_exact(-1);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn div_exact(self, rhs: Self) -> Option<Self> {
if self % rhs != 0 { None } else { Some(self / rhs) }
}
/// Unchecked integer division without remainder. Computes `self / rhs`.
///
/// # Safety
///
/// This results in undefined behavior when `rhs == 0`, `self % rhs != 0`, or
#[doc = "`self == i128::MIN && rhs == -1`,"]
/// i.e. when [`checked_div_exact`](Self::checked_div_exact) would return `None`.
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_div_exact(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i128, rhs: i128) {
if !(rhs != 0 && lhs % rhs == 0 &&
(lhs != <i128>::MIN || rhs != -1)) {
let msg =
"unsafe precondition(s) violated: i128::unchecked_div_exact cannot overflow, divide by zero, or leave a remainder\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::exact_div(self, rhs) }
}
/// Checked integer remainder. Computes `self % rhs`, returning `None` if
/// `rhs == 0` or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i128.checked_rem(2), Some(1));"]
#[doc = "assert_eq!(5i128.checked_rem(0), None);"]
#[doc = "assert_eq!(i128::MIN.checked_rem(-1), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1)))
{
None
} else { Some(unsafe { intrinsics::unchecked_rem(self, rhs) }) }
}
/// Strict integer remainder. Computes `self % rhs`, panicking if
/// the division results in overflow.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is `x % y` for `MIN / -1` on a
/// signed type (where [`MIN`](Self::MIN) is the negative minimal value), which is invalid due to implementation artifacts.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i128.strict_rem(2), 1);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5i128.strict_rem(0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i128::MIN.strict_rem(-1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_rem(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_rem(rhs);
if b { imp::overflow_panic::rem() } else { a }
}
/// Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
/// if `rhs == 0` or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i128.checked_rem_euclid(2), Some(1));"]
#[doc = "assert_eq!(5i128.checked_rem_euclid(0), None);"]
#[doc = "assert_eq!(i128::MIN.checked_rem_euclid(-1), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) {
None
} else { Some(self.rem_euclid(rhs)) }
}
/// Strict Euclidean remainder. Computes `self.rem_euclid(rhs)`, panicking if
/// the division results in overflow.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is `x % y` for `MIN / -1` on a
/// signed type (where [`MIN`](Self::MIN) is the negative minimal value), which is invalid due to implementation artifacts.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i128.strict_rem_euclid(2), 1);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5i128.strict_rem_euclid(0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i128::MIN.strict_rem_euclid(-1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_rem_euclid(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_rem_euclid(rhs);
if b { imp::overflow_panic::rem() } else { a }
}
/// Checked negation. Computes `-self`, returning `None` if `self == MIN`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i128.checked_neg(), Some(-5));"]
#[doc = "assert_eq!(i128::MIN.checked_neg(), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_neg(self) -> Option<Self> {
let (a, b) = self.overflowing_neg();
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Unchecked negation. Computes `-self`, assuming overflow cannot occur.
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self == i128::MIN`,"]
/// i.e. when [`checked_neg`] would return `None`.
///
#[doc = "[`checked_neg`]: i128::checked_neg"]
#[stable(feature = "unchecked_neg", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_neg", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_neg(self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i128) {
if !!lhs.overflowing_neg().1 {
let msg =
"unsafe precondition(s) violated: i128::unchecked_neg cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self);
}
};
unsafe { intrinsics::unchecked_sub(0, self) }
}
/// Strict negation. Computes `-self`, panicking if `self == MIN`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i128.strict_neg(), -5);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i128::MIN.strict_neg();"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_neg(self) -> Self {
let (a, b) = self.overflowing_neg();
if b { imp::overflow_panic::neg() } else { a }
}
/// Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
/// than or equal to the number of bits in `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1i128.checked_shl(4), Some(0x10));"]
#[doc = "assert_eq!(0x1i128.checked_shl(129), None);"]
#[doc = "assert_eq!(0x10i128.checked_shl(127), Some(0));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
if rhs < Self::BITS {
Some(unsafe { self.unchecked_shl(rhs) })
} else { None }
}
/// Strict shift left. Computes `self << rhs`, panicking if `rhs` is larger
/// than or equal to the number of bits in `self`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1i128.strict_shl(4), 0x10);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0x1i128.strict_shl(129);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_shl(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_shl(rhs);
if b { imp::overflow_panic::shl() } else { a }
}
/// Unchecked shift left. Computes `self << rhs`, assuming that
/// `rhs` is less than the number of bits in `self`.
///
/// # Safety
///
/// This results in undefined behavior if `rhs` is larger than
/// or equal to the number of bits in `self`,
/// i.e. when [`checked_shl`] would return `None`.
///
#[doc = "[`checked_shl`]: i128::checked_shl"]
#[stable(feature = "unchecked_shifts", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_shl(self, rhs: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(rhs: u32) {
if !(rhs < <i128>::BITS) {
let msg =
"unsafe precondition(s) violated: i128::unchecked_shl cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(rhs); }
};
unsafe { intrinsics::unchecked_shl(self, rhs) }
}
/// Unbounded shift left. Computes `self << rhs`, without bounding the value of `rhs`.
///
/// If `rhs` is larger or equal to the number of bits in `self`,
/// the entire value is shifted out, and `0` is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1_i128.unbounded_shl(4), 0x10);"]
#[doc = "assert_eq!(0x1_i128.unbounded_shl(129), 0);"]
#[doc = "assert_eq!(0b101_i128.unbounded_shl(0), 0b101);"]
#[doc = "assert_eq!(0b101_i128.unbounded_shl(1), 0b1010);"]
#[doc = "assert_eq!(0b101_i128.unbounded_shl(2), 0b10100);"]
#[doc = "assert_eq!(42_i128.unbounded_shl(128), 0);"]
#[doc = "assert_eq!(42_i128.unbounded_shl(1).unbounded_shl(127), 0);"]
#[doc = "assert_eq!((-13_i128).unbounded_shl(128), 0);"]
#[doc = "assert_eq!((-13_i128).unbounded_shl(1).unbounded_shl(127), 0);"]
/// ```
#[stable(feature = "unbounded_shifts", since = "1.87.0")]
#[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unbounded_shl(self, rhs: u32) -> i128 {
if rhs < Self::BITS { unsafe { self.unchecked_shl(rhs) } } else { 0 }
}
/// Exact shift left. Computes `self << rhs` as long as it can be reversed losslessly.
///
/// Returns `None` if any bits that would be shifted out differ from the resulting sign bit
/// or if `rhs` >=
#[doc = "`i128::BITS`."]
/// Otherwise, returns `Some(self << rhs)`.
///
/// # Examples
///
/// ```
/// #![feature(exact_bitshifts)]
///
#[doc = "assert_eq!(0x1i128.shl_exact(4), Some(0x10));"]
#[doc =
"assert_eq!(0x1i128.shl_exact(i128::BITS - 2), Some(1 << i128::BITS - 2));"]
#[doc = "assert_eq!(0x1i128.shl_exact(i128::BITS - 1), None);"]
#[doc =
"assert_eq!((-0x2i128).shl_exact(i128::BITS - 2), Some(-0x2 << i128::BITS - 2));"]
#[doc = "assert_eq!((-0x2i128).shl_exact(i128::BITS - 1), None);"]
/// ```
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn shl_exact(self, rhs: u32) -> Option<i128> {
if rhs < self.leading_zeros() || rhs < self.leading_ones() {
Some(unsafe { self.unchecked_shl(rhs) })
} else { None }
}
/// Unchecked exact shift left. Computes `self << rhs`, assuming the operation can be
/// losslessly reversed and `rhs` cannot be larger than
#[doc = "`i128::BITS`."]
///
/// # Safety
///
/// This results in undefined behavior when `rhs >= self.leading_zeros() && rhs >=
/// self.leading_ones()` i.e. when
#[doc = "[`i128::shl_exact`]"]
/// would return `None`.
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_shl_exact(self, rhs: u32) -> i128 {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(zeros: u32, ones: u32, rhs: u32) {
if !(rhs < zeros || rhs < ones) {
let msg =
"unsafe precondition(s) violated: i128::unchecked_shl_exact cannot shift out bits that would change the value of the first bit\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_library_ub() {
precondition_check(self.leading_zeros(), self.leading_ones(),
rhs);
}
};
unsafe { self.unchecked_shl(rhs) }
}
/// Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
/// larger than or equal to the number of bits in `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10i128.checked_shr(4), Some(0x1));"]
#[doc = "assert_eq!(0x10i128.checked_shr(128), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
if rhs < Self::BITS {
Some(unsafe { self.unchecked_shr(rhs) })
} else { None }
}
/// Strict shift right. Computes `self >> rhs`, panicking if `rhs` is
/// larger than or equal to the number of bits in `self`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10i128.strict_shr(4), 0x1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0x10i128.strict_shr(128);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_shr(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_shr(rhs);
if b { imp::overflow_panic::shr() } else { a }
}
/// Unchecked shift right. Computes `self >> rhs`, assuming that
/// `rhs` is less than the number of bits in `self`.
///
/// # Safety
///
/// This results in undefined behavior if `rhs` is larger than
/// or equal to the number of bits in `self`,
/// i.e. when [`checked_shr`] would return `None`.
///
#[doc = "[`checked_shr`]: i128::checked_shr"]
#[stable(feature = "unchecked_shifts", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_shr(self, rhs: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(rhs: u32) {
if !(rhs < <i128>::BITS) {
let msg =
"unsafe precondition(s) violated: i128::unchecked_shr cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(rhs); }
};
unsafe { intrinsics::unchecked_shr(self, rhs) }
}
/// Unbounded shift right. Computes `self >> rhs`, without bounding the value of `rhs`.
///
/// If `rhs` is larger or equal to the number of bits in `self`,
/// the entire value is shifted out, which yields `0` for a positive number,
/// and `-1` for a negative number.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10_i128.unbounded_shr(4), 0x1);"]
#[doc = "assert_eq!(0x10_i128.unbounded_shr(129), 0);"]
#[doc = "assert_eq!(i128::MIN.unbounded_shr(129), -1);"]
#[doc = "assert_eq!(0b1010_i128.unbounded_shr(0), 0b1010);"]
#[doc = "assert_eq!(0b1010_i128.unbounded_shr(1), 0b101);"]
#[doc = "assert_eq!(0b1010_i128.unbounded_shr(2), 0b10);"]
#[doc = "assert_eq!(42_i128.unbounded_shr(128), 0);"]
#[doc = "assert_eq!(42_i128.unbounded_shr(1).unbounded_shr(127), 0);"]
#[doc = "assert_eq!((-13_i128).unbounded_shr(128), -1);"]
#[doc = "assert_eq!((-13_i128).unbounded_shr(1).unbounded_shr(127), -1);"]
/// ```
#[stable(feature = "unbounded_shifts", since = "1.87.0")]
#[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unbounded_shr(self, rhs: u32) -> i128 {
if rhs < Self::BITS {
unsafe { self.unchecked_shr(rhs) }
} else { unsafe { self.unchecked_shr(Self::BITS - 1) } }
}
/// Exact shift right. Computes `self >> rhs` as long as it can be reversed losslessly.
///
/// Returns `None` if any non-zero bits would be shifted out or if `rhs` >=
#[doc = "`i128::BITS`."]
/// Otherwise, returns `Some(self >> rhs)`.
///
/// # Examples
///
/// ```
/// #![feature(exact_bitshifts)]
///
#[doc = "assert_eq!(0x10i128.shr_exact(4), Some(0x1));"]
#[doc = "assert_eq!(0x10i128.shr_exact(5), None);"]
/// ```
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn shr_exact(self, rhs: u32) -> Option<i128> {
if rhs <= self.trailing_zeros() && rhs < <i128>::BITS {
Some(unsafe { self.unchecked_shr(rhs) })
} else { None }
}
/// Unchecked exact shift right. Computes `self >> rhs`, assuming the operation can be
/// losslessly reversed and `rhs` cannot be larger than
#[doc = "`i128::BITS`."]
///
/// # Safety
///
/// This results in undefined behavior when `rhs > self.trailing_zeros() || rhs >=
#[doc = "i128::BITS`"]
/// i.e. when
#[doc = "[`i128::shr_exact`]"]
/// would return `None`.
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_shr_exact(self, rhs: u32) -> i128 {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(zeros: u32, bits: u32, rhs: u32) {
if !(rhs <= zeros && rhs < bits) {
let msg =
"unsafe precondition(s) violated: i128::unchecked_shr_exact cannot shift out non-zero bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_library_ub() {
precondition_check(self.trailing_zeros(), <i128>::BITS, rhs);
}
};
unsafe { self.unchecked_shr(rhs) }
}
/// Checked absolute value. Computes `self.abs()`, returning `None` if
/// `self == MIN`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-5i128).checked_abs(), Some(5));"]
#[doc = "assert_eq!(i128::MIN.checked_abs(), None);"]
/// ```
#[stable(feature = "no_panic_abs", since = "1.13.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_abs(self) -> Option<Self> {
if self.is_negative() { self.checked_neg() } else { Some(self) }
}
/// Strict absolute value. Computes `self.abs()`, panicking if
/// `self == MIN`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-5i128).strict_abs(), 5);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i128::MIN.strict_abs();"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_abs(self) -> Self {
if self.is_negative() { self.strict_neg() } else { self }
}
/// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(8i128.checked_pow(2), Some(64));"]
#[doc = "assert_eq!(0_i128.checked_pow(0), Some(1));"]
#[doc = "assert_eq!(i128::MAX.checked_pow(2), None);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
let mut base = self;
let mut acc: Self = 1;
if intrinsics::is_val_statically_known(base) &&
base.unsigned_abs().is_power_of_two() {
let k = base.unsigned_abs().ilog2();
let shift =
match k.checked_mul(exp) { Some(x) => x, None => return None, };
return if base < 0 && (exp % 2) == 1 {
(-1 as Self).shl_exact(shift)
} else { (1 as Self).shl_exact(shift) }
}
if exp == 0 { return Some(1); }
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 {
acc =
match acc.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
exp /= 2;
base =
match base.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
return acc.checked_mul(base);
}
loop {
if (exp & 1) == 1 {
acc =
match acc.checked_mul(base) {
Some(x) => x,
None => return None,
};
if exp == 1 { return Some(acc); }
}
exp /= 2;
base =
match base.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
}
/// Strict exponentiation. Computes `self.pow(exp)`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(8i128.strict_pow(2), 64);"]
#[doc = "assert_eq!(0_i128.strict_pow(0), 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = i128::MAX.strict_pow(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) {
Some(x) => x,
None => imp::overflow_panic::pow(),
}
}
/// Returns the integer square root of the number, rounded down.
///
/// This function returns the **principal (non-negative) square root**.
/// For a given number `n`, although both `x` and `-x` satisfy x<sup>2</sup> = n,
/// this function always returns the non-negative value.
///
/// Returns `None` if `self` is negative.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i128.checked_isqrt(), Some(3));"]
/// ```
#[stable(feature = "isqrt", since = "1.84.0")]
#[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_isqrt(self) -> Option<Self> {
if self < 0 {
None
} else {
let result = self.cast_unsigned().isqrt().cast_signed();
unsafe {
const MAX_RESULT: i128 =
<i128>::MAX.cast_unsigned().isqrt().cast_signed();
crate::hint::assert_unchecked(result <= MAX_RESULT);
}
Some(result)
}
}
/// Saturating integer addition. Computes `self + rhs`, saturating at the numeric
/// bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i128.saturating_add(1), 101);"]
#[doc = "assert_eq!(i128::MAX.saturating_add(100), i128::MAX);"]
#[doc = "assert_eq!(i128::MIN.saturating_add(-1), i128::MIN);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_add(self, rhs: Self) -> Self {
intrinsics::saturating_add(self, rhs)
}
/// Saturating addition with an unsigned integer. Computes `self + rhs`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i128.saturating_add_unsigned(2), 3);"]
#[doc = "assert_eq!(i128::MAX.saturating_add_unsigned(100), i128::MAX);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_add_unsigned(self, rhs: u128) -> Self {
match self.checked_add_unsigned(rhs) { Some(x) => x, None => Self::MAX, }
}
/// Saturating integer subtraction. Computes `self - rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i128.saturating_sub(127), -27);"]
#[doc = "assert_eq!(i128::MIN.saturating_sub(100), i128::MIN);"]
#[doc = "assert_eq!(i128::MAX.saturating_sub(-1), i128::MAX);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_sub(self, rhs: Self) -> Self {
intrinsics::saturating_sub(self, rhs)
}
/// Saturating subtraction with an unsigned integer. Computes `self - rhs`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i128.saturating_sub_unsigned(127), -27);"]
#[doc = "assert_eq!(i128::MIN.saturating_sub_unsigned(100), i128::MIN);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_sub_unsigned(self, rhs: u128) -> Self {
match self.checked_sub_unsigned(rhs) { Some(x) => x, None => Self::MIN, }
}
/// Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
/// instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i128.saturating_neg(), -100);"]
#[doc = "assert_eq!((-100i128).saturating_neg(), 100);"]
#[doc = "assert_eq!(i128::MIN.saturating_neg(), i128::MAX);"]
#[doc = "assert_eq!(i128::MAX.saturating_neg(), i128::MIN + 1);"]
/// ```
#[stable(feature = "saturating_neg", since = "1.45.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_neg(self) -> Self {
intrinsics::saturating_sub(0, self)
}
/// Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
/// MIN` instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i128.saturating_abs(), 100);"]
#[doc = "assert_eq!((-100i128).saturating_abs(), 100);"]
#[doc = "assert_eq!(i128::MIN.saturating_abs(), i128::MAX);"]
#[doc = "assert_eq!((i128::MIN + 1).saturating_abs(), i128::MAX);"]
/// ```
#[stable(feature = "saturating_neg", since = "1.45.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_abs(self) -> Self {
if self.is_negative() { self.saturating_neg() } else { self }
}
/// Saturating integer multiplication. Computes `self * rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i128.saturating_mul(12), 120);"]
#[doc = "assert_eq!(i128::MAX.saturating_mul(10), i128::MAX);"]
#[doc = "assert_eq!(i128::MIN.saturating_mul(10), i128::MIN);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_mul(self, rhs: Self) -> Self {
match self.checked_mul(rhs) {
Some(x) => x,
None => if (self < 0) == (rhs < 0) { Self::MAX } else { Self::MIN },
}
}
/// Saturating integer division. Computes `self / rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i128.saturating_div(2), 2);"]
#[doc = "assert_eq!(i128::MAX.saturating_div(-1), i128::MIN + 1);"]
#[doc = "assert_eq!(i128::MIN.saturating_div(-1), i128::MAX);"]
///
/// ```
#[stable(feature = "saturating_div", since = "1.58.0")]
#[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_div(self, rhs: Self) -> Self {
match self.overflowing_div(rhs) {
(result, false) => result,
(_result, true) => Self::MAX,
}
}
/// Saturating integer exponentiation. Computes `self.pow(exp)`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-4i128).saturating_pow(3), -64);"]
#[doc = "assert_eq!(0_i128.saturating_pow(0), 1);"]
#[doc = "assert_eq!(i128::MIN.saturating_pow(2), i128::MAX);"]
#[doc = "assert_eq!(i128::MIN.saturating_pow(3), i128::MIN);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) {
Some(x) => x,
None if self < 0 && exp % 2 == 1 => Self::MIN,
None => Self::MAX,
}
}
/// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
/// boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i128.wrapping_add(27), 127);"]
#[doc = "assert_eq!(i128::MAX.wrapping_add(2), i128::MIN + 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_add(self, rhs: Self) -> Self {
intrinsics::wrapping_add(self, rhs)
}
/// Wrapping (modular) addition with an unsigned integer. Computes
/// `self + rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i128.wrapping_add_unsigned(27), 127);"]
#[doc = "assert_eq!(i128::MAX.wrapping_add_unsigned(2), i128::MIN + 1);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_add_unsigned(self, rhs: u128) -> Self {
self.wrapping_add(rhs as Self)
}
/// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
/// boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0i128.wrapping_sub(127), -127);"]
#[doc = "assert_eq!((-2i128).wrapping_sub(i128::MAX), i128::MAX);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_sub(self, rhs: Self) -> Self {
intrinsics::wrapping_sub(self, rhs)
}
/// Wrapping (modular) subtraction with an unsigned integer. Computes
/// `self - rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0i128.wrapping_sub_unsigned(127), -127);"]
#[doc = "assert_eq!((-2i128).wrapping_sub_unsigned(u128::MAX), -1);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_sub_unsigned(self, rhs: u128) -> Self {
self.wrapping_sub(rhs as Self)
}
/// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
/// the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i128.wrapping_mul(12), 120);"]
/// assert_eq!(11i8.wrapping_mul(12), -124);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_mul(self, rhs: Self) -> Self {
intrinsics::wrapping_mul(self, rhs)
}
/// Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
/// boundary of the type.
///
/// The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
/// [`MIN`](Self::MIN) is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
/// that is too large to represent in the type. In such a case, this function returns [`MIN`](Self::MIN) itself.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i128.wrapping_div(10), 10);"]
/// assert_eq!((-128i8).wrapping_div(-1), -128);
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_div(self, rhs: Self) -> Self {
self.overflowing_div(rhs).0
}
/// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
/// wrapping around at the boundary of the type.
///
/// Wrapping will only occur in `MIN / -1` on a signed type (where [`MIN`](Self::MIN) is the negative minimal value
/// for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
/// type. In this case, this method returns [`MIN`](Self::MIN) itself.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i128.wrapping_div_euclid(10), 10);"]
/// assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
self.overflowing_div_euclid(rhs).0
}
/// Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
/// boundary of the type.
///
/// Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
/// invalid for `MIN / -1` on a signed type (where [`MIN`](Self::MIN) is the negative minimal value). In such a case,
/// this function returns `0`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i128.wrapping_rem(10), 0);"]
/// assert_eq!((-128i8).wrapping_rem(-1), 0);
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_rem(self, rhs: Self) -> Self {
self.overflowing_rem(rhs).0
}
/// Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
/// at the boundary of the type.
///
/// Wrapping will only occur in `MIN % -1` on a signed type (where [`MIN`](Self::MIN) is
/// the negative minimal value for the type). In this case, this method returns 0.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i128.wrapping_rem_euclid(10), 0);"]
/// assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
self.overflowing_rem_euclid(rhs).0
}
/// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
/// of the type.
///
/// The only case where such wrapping can occur is when one negates [`MIN`](Self::MIN) on a signed type (where [`MIN`](Self::MIN)
/// is the negative minimal value for the type); this is a positive value that is too large to represent
/// in the type. In such a case, this function returns [`MIN`](Self::MIN) itself.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i128.wrapping_neg(), -100);"]
#[doc = "assert_eq!((-100i128).wrapping_neg(), 100);"]
#[doc = "assert_eq!(i128::MIN.wrapping_neg(), i128::MIN);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_neg(self) -> Self { (0 as i128).wrapping_sub(self) }
/// Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
/// any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
///
/// Beware that, unlike most other `wrapping_*` methods on integers, this
/// does *not* give the same result as doing the shift in infinite precision
/// then truncating as needed. Instead, the behaviour of this method matches what shift instructions
/// do on many processors, and is what the `<<` operator does when overflow
/// checks are disabled, but numerically it's weird. Consider, instead,
/// using [`Self::unbounded_shl`] which has nicer behaviour.
///
/// Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
/// the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
/// The primitive integer types all implement a [`rotate_left`](Self::rotate_left) function,
/// which may be what you want instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-1_i128).wrapping_shl(7), -128);"]
#[doc = "assert_eq!(42_i128.wrapping_shl(128), 42);"]
#[doc = "assert_eq!(42_i128.wrapping_shl(1).wrapping_shl(127), 0);"]
#[doc = "assert_eq!((-1_i128).wrapping_shl(128), -1);"]
#[doc = "assert_eq!(5_i128.wrapping_shl(1025), 10);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_shl(self, rhs: u32) -> Self {
unsafe { self.unchecked_shl(rhs & (Self::BITS - 1)) }
}
/// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
/// removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
///
/// Beware that, unlike most other `wrapping_*` methods on integers, this
/// does *not* give the same result as doing the shift in infinite precision
/// then truncating as needed. Instead, the behaviour of this method matches what shift instructions
/// do on many processors, and is what the `>>` operator does when overflow
/// checks are disabled, but numerically it's weird. Consider, instead,
/// using [`Self::unbounded_shr`] which has nicer behaviour.
///
/// Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
/// to the range of the type, rather than the bits shifted out of the LHS being returned to the other
/// end. The primitive integer types all implement a [`rotate_right`](Self::rotate_right) function,
/// which may be what you want instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-128_i128).wrapping_shr(7), -1);"]
#[doc = "assert_eq!(42_i128.wrapping_shr(128), 42);"]
#[doc = "assert_eq!(42_i128.wrapping_shr(1).wrapping_shr(127), 0);"]
/// assert_eq!((-128_i16).wrapping_shr(64), -128);
#[doc = "assert_eq!(10_i128.wrapping_shr(1025), 5);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_shr(self, rhs: u32) -> Self {
unsafe { self.unchecked_shr(rhs & (Self::BITS - 1)) }
}
/// Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
/// the boundary of the type.
///
/// The only case where such wrapping can occur is when one takes the absolute value of the negative
/// minimal value for the type; this is a positive value that is too large to represent in the type. In
/// such a case, this function returns [`MIN`](Self::MIN) itself.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i128.wrapping_abs(), 100);"]
#[doc = "assert_eq!((-100i128).wrapping_abs(), 100);"]
#[doc = "assert_eq!(i128::MIN.wrapping_abs(), i128::MIN);"]
/// assert_eq!((-128i8).wrapping_abs() as u8, 128);
/// ```
#[stable(feature = "no_panic_abs", since = "1.13.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[allow(unused_attributes)]
#[inline]
pub const fn wrapping_abs(self) -> Self {
if self.is_negative() { self.wrapping_neg() } else { self }
}
/// Computes the absolute value of `self` without any wrapping
/// or panicking.
///
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i128.unsigned_abs(), 100u128);"]
#[doc = "assert_eq!((-100i128).unsigned_abs(), 100u128);"]
/// assert_eq!((-128i8).unsigned_abs(), 128u8);
/// ```
#[stable(feature = "unsigned_abs", since = "1.51.0")]
#[rustc_const_stable(feature = "unsigned_abs", since = "1.51.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unsigned_abs(self) -> u128 { self.wrapping_abs() as u128 }
/// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3i128.wrapping_pow(4), 81);"]
/// assert_eq!(3i8.wrapping_pow(5), -13);
/// assert_eq!(3i8.wrapping_pow(6), -39);
#[doc = "assert_eq!(0_i128.wrapping_pow(0), 1);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_pow(self, exp: u32) -> Self {
let (a, _) = self.overflowing_pow(exp);
a
}
/// Calculates `self` + `rhs`.
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would have
/// occurred then the wrapped value is returned (negative if overflowed
/// above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i128.overflowing_add(2), (7, false));"]
#[doc = "assert_eq!(i128::MAX.overflowing_add(1), (i128::MIN, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::add_with_overflow(self as i128, rhs as i128);
(a as Self, b)
}
/// Calculates `self` + `rhs` + `carry` and checks for overflow.
///
/// Performs "ternary addition" of two integer operands and a carry-in
/// bit, and returns a tuple of the sum along with a boolean indicating
/// whether an arithmetic overflow would occur. On overflow, the wrapped
/// value is returned.
///
/// This allows chaining together multiple additions to create a wider
/// addition, and can be useful for bignum addition. This method should
/// only be used for the most significant word; for the less significant
/// words the unsigned method
#[doc = "[`u128::carrying_add`]"]
/// should be used.
///
/// The output boolean returned by this method is *not* a carry flag,
/// and should *not* be added to a more significant word.
///
/// If overflow occurred, the wrapped value is returned (negative if overflowed
/// above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
///
/// If the input carry is false, this method is equivalent to
/// [`overflowing_add`](Self::overflowing_add).
///
/// # Examples
///
/// ```
/// #![feature(signed_bigint_helpers)]
/// // Only the most significant word is signed.
/// //
#[doc = "// 10 MAX (a = 10 \u{d7} 2^128 + 2^128 - 1)"]
#[doc = "// + -5 9 (b = -5 \u{d7} 2^128 + 9)"]
/// // ---------
#[doc = "// 6 8 (sum = 6 \u{d7} 2^128 + 8)"]
///
#[doc = "let (a1, a0): (i128, u128) = (10, u128::MAX);"]
#[doc = "let (b1, b0): (i128, u128) = (-5, 9);"]
/// let carry0 = false;
///
#[doc = "// u128::carrying_add for the less significant words"]
/// let (sum0, carry1) = a0.carrying_add(b0, carry0);
/// assert_eq!(carry1, true);
///
#[doc = "// i128::carrying_add for the most significant word"]
/// let (sum1, overflow) = a1.carrying_add(b1, carry1);
/// assert_eq!(overflow, false);
///
/// assert_eq!((sum1, sum0), (6, 8));
/// ```
#[unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
let (a, b) = self.overflowing_add(rhs);
let (c, d) = a.overflowing_add(carry as i128);
(c, b != d)
}
/// Calculates `self` + `rhs` with an unsigned `rhs`.
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i128.overflowing_add_unsigned(2), (3, false));"]
#[doc =
"assert_eq!((i128::MIN).overflowing_add_unsigned(u128::MAX), (i128::MAX, false));"]
#[doc =
"assert_eq!((i128::MAX - 2).overflowing_add_unsigned(3), (i128::MIN, true));"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_add_unsigned(self, rhs: u128) -> (Self, bool) {
let rhs = rhs as Self;
let (res, overflowed) = self.overflowing_add(rhs);
(res, overflowed ^ (rhs < 0))
}
/// Calculates `self` - `rhs`.
///
/// Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
/// would occur. If an overflow would have occurred then the wrapped value is returned
/// (negative if overflowed above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i128.overflowing_sub(2), (3, false));"]
#[doc = "assert_eq!(i128::MIN.overflowing_sub(1), (i128::MAX, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::sub_with_overflow(self as i128, rhs as i128);
(a as Self, b)
}
/// Calculates `self` − `rhs` − `borrow` and checks for
/// overflow.
///
/// Performs "ternary subtraction" by subtracting both an integer
/// operand and a borrow-in bit from `self`, and returns a tuple of the
/// difference along with a boolean indicating whether an arithmetic
/// overflow would occur. On overflow, the wrapped value is returned.
///
/// This allows chaining together multiple subtractions to create a
/// wider subtraction, and can be useful for bignum subtraction. This
/// method should only be used for the most significant word; for the
/// less significant words the unsigned method
#[doc = "[`u128::borrowing_sub`]"]
/// should be used.
///
/// The output boolean returned by this method is *not* a borrow flag,
/// and should *not* be subtracted from a more significant word.
///
/// If overflow occurred, the wrapped value is returned (negative if overflowed
/// above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
///
/// If the input borrow is false, this method is equivalent to
/// [`overflowing_sub`](Self::overflowing_sub).
///
/// # Examples
///
/// ```
/// #![feature(signed_bigint_helpers)]
/// // Only the most significant word is signed.
/// //
#[doc = "// 6 8 (a = 6 \u{d7} 2^128 + 8)"]
#[doc = "// - -5 9 (b = -5 \u{d7} 2^128 + 9)"]
/// // ---------
#[doc = "// 10 MAX (diff = 10 \u{d7} 2^128 + 2^128 - 1)"]
///
#[doc = "let (a1, a0): (i128, u128) = (6, 8);"]
#[doc = "let (b1, b0): (i128, u128) = (-5, 9);"]
/// let borrow0 = false;
///
#[doc = "// u128::borrowing_sub for the less significant words"]
/// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);
/// assert_eq!(borrow1, true);
///
#[doc = "// i128::borrowing_sub for the most significant word"]
/// let (diff1, overflow) = a1.borrowing_sub(b1, borrow1);
/// assert_eq!(overflow, false);
///
#[doc = "assert_eq!((diff1, diff0), (10, u128::MAX));"]
/// ```
#[unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
let (a, b) = self.overflowing_sub(rhs);
let (c, d) = a.overflowing_sub(borrow as i128);
(c, b != d)
}
/// Calculates `self` - `rhs` with an unsigned `rhs`.
///
/// Returns a tuple of the subtraction along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i128.overflowing_sub_unsigned(2), (-1, false));"]
#[doc =
"assert_eq!((i128::MAX).overflowing_sub_unsigned(u128::MAX), (i128::MIN, false));"]
#[doc =
"assert_eq!((i128::MIN + 2).overflowing_sub_unsigned(3), (i128::MAX, true));"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_sub_unsigned(self, rhs: u128) -> (Self, bool) {
let rhs = rhs as Self;
let (res, overflowed) = self.overflowing_sub(rhs);
(res, overflowed ^ (rhs < 0))
}
/// Calculates the multiplication of `self` and `rhs`.
///
/// Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
/// would occur. If an overflow would have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i128.overflowing_mul(2), (10, false));"]
/// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::mul_with_overflow(self as i128, rhs as i128);
(a as Self, b)
}
/// Calculates the "full multiplication" `self * rhs + carry`
/// without the possibility to overflow.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// Performs "long multiplication" which takes in an extra amount to add, and may return an
/// additional amount of overflow. This allows for chaining together multiple
/// multiplications to create "big integers" which represent larger values.
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why [`i32`] is used.
///
/// ```
/// #![feature(signed_bigint_helpers)]
/// assert_eq!(5i32.carrying_mul(-2, 0), (4294967286, -1));
/// assert_eq!(5i32.carrying_mul(-2, 10), (0, 0));
/// assert_eq!(1_000_000_000i32.carrying_mul(-10, 0), (2884901888, -3));
/// assert_eq!(1_000_000_000i32.carrying_mul(-10, 10), (2884901898, -3));
#[doc =
"assert_eq!(i128::MAX.carrying_mul(i128::MAX, i128::MAX), (i128::MAX.unsigned_abs() + 1, i128::MAX / 2));"]
/// ```
#[unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[rustc_const_unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_mul(self, rhs: Self, carry: Self) -> (u128, Self) {
Self::carrying_mul_add(self, rhs, carry, 0)
}
/// Calculates the "full multiplication" `self * rhs + carry + add`
/// without the possibility to overflow.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// Performs "long multiplication" which takes in an extra amount to add, and may return an
/// additional amount of overflow. This allows for chaining together multiple
/// multiplications to create "big integers" which represent larger values.
///
/// If you only need one `carry`, then you can use [`Self::carrying_mul`] instead.
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `i32` is used.
///
/// ```
/// #![feature(signed_bigint_helpers)]
/// assert_eq!(5i32.carrying_mul_add(-2, 0, 0), (4294967286, -1));
/// assert_eq!(5i32.carrying_mul_add(-2, 10, 10), (10, 0));
/// assert_eq!(1_000_000_000i32.carrying_mul_add(-10, 0, 0), (2884901888, -3));
/// assert_eq!(1_000_000_000i32.carrying_mul_add(-10, 10, 10), (2884901908, -3));
#[doc =
"assert_eq!(i128::MAX.carrying_mul_add(i128::MAX, i128::MAX, i128::MAX), (u128::MAX, i128::MAX / 2));"]
/// ```
#[unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[rustc_const_unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_mul_add(self, rhs: Self, carry: Self, add: Self)
-> (u128, Self) {
intrinsics::carrying_mul_add(self, rhs, carry, add)
}
/// Calculates the divisor when `self` is divided by `rhs`.
///
/// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
/// occur. If an overflow would occur then self is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i128.overflowing_div(2), (2, false));"]
#[doc = "assert_eq!(i128::MIN.overflowing_div(-1), (i128::MIN, true));"]
/// ```
#[inline]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_overflowing_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
if intrinsics::unlikely((self == Self::MIN) & (rhs == -1)) {
(self, true)
} else { (self / rhs, false) }
}
/// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
///
/// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
/// occur. If an overflow would occur then `self` is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i128.overflowing_div_euclid(2), (2, false));"]
#[doc =
"assert_eq!(i128::MIN.overflowing_div_euclid(-1), (i128::MIN, true));"]
/// ```
#[inline]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
if intrinsics::unlikely((self == Self::MIN) & (rhs == -1)) {
(self, true)
} else { (self.div_euclid(rhs), false) }
}
/// Calculates the remainder when `self` is divided by `rhs`.
///
/// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
/// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i128.overflowing_rem(2), (1, false));"]
#[doc = "assert_eq!(i128::MIN.overflowing_rem(-1), (0, true));"]
/// ```
#[inline]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_overflowing_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
if intrinsics::unlikely(rhs == -1) {
(0, self == Self::MIN)
} else { (self % rhs, false) }
}
/// Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
///
/// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
/// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i128.overflowing_rem_euclid(2), (1, false));"]
#[doc = "assert_eq!(i128::MIN.overflowing_rem_euclid(-1), (0, true));"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
if intrinsics::unlikely(rhs == -1) {
(0, self == Self::MIN)
} else { (self.rem_euclid(rhs), false) }
}
/// Negates self, overflowing if this is equal to the minimum value.
///
/// Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
/// happened. If `self` is the minimum value (e.g., [`i32::MIN`] for values of type [`i32`]), then the
/// minimum value will be returned again and `true` will be returned for an overflow happening.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2i128.overflowing_neg(), (-2, false));"]
#[doc = "assert_eq!(i128::MIN.overflowing_neg(), (i128::MIN, true));"]
/// ```
#[inline]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[allow(unused_attributes)]
pub const fn overflowing_neg(self) -> (Self, bool) {
if intrinsics::unlikely(self == Self::MIN) {
(Self::MIN, true)
} else { (-self, false) }
}
/// Shifts self left by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
/// value was larger than or equal to the number of bits. If the shift value is too large, then value is
/// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1i128.overflowing_shl(4), (0x10, false));"]
/// assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));
#[doc = "assert_eq!(0x10i128.overflowing_shl(127), (0, false));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shl(rhs), rhs >= Self::BITS)
}
/// Shifts self right by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
/// value was larger than or equal to the number of bits. If the shift value is too large, then value is
/// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10i128.overflowing_shr(4), (0x1, false));"]
/// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shr(rhs), rhs >= Self::BITS)
}
/// Computes the absolute value of `self`.
///
/// Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
/// happened. If self is the minimum value
#[doc = "(e.g., [`i128::MIN`] for values of type [`i128`]),"]
/// then the minimum value will be returned again and true will be returned
/// for an overflow happening.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i128.overflowing_abs(), (10, false));"]
#[doc = "assert_eq!((-10i128).overflowing_abs(), (10, false));"]
#[doc = "assert_eq!((i128::MIN).overflowing_abs(), (i128::MIN, true));"]
/// ```
#[stable(feature = "no_panic_abs", since = "1.13.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_abs(self) -> (Self, bool) {
(self.wrapping_abs(), self == Self::MIN)
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// Returns a tuple of the exponentiation along with a bool indicating
/// whether an overflow happened.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3i128.overflowing_pow(4), (81, false));"]
#[doc = "assert_eq!(0_i128.overflowing_pow(0), (1, false));"]
/// assert_eq!(3i8.overflowing_pow(5), (-13, true));
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
let mut base = self;
let mut acc: Self = 1;
let mut overflow = false;
let mut tmp_overflow;
if intrinsics::is_val_statically_known(base) &&
base.unsigned_abs().is_power_of_two() {
let k = base.unsigned_abs().ilog2();
let Some(shift) = k.checked_mul(exp) else { return (0, true) };
let base: Self = if base < 0 && (exp % 2) != 0 { -1 } else { 1 };
return (base.unbounded_shl(shift), base.shl_exact(shift).is_none());
}
if exp == 0 { return (1, false); }
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 {
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
}
exp /= 2;
(base, tmp_overflow) = base.overflowing_mul(base);
overflow |= tmp_overflow;
}
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
return (acc, overflow);
}
loop {
if (exp & 1) == 1 {
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
if exp == 1 { return (acc, overflow); }
}
exp /= 2;
(base, tmp_overflow) = base.overflowing_mul(base);
overflow |= tmp_overflow;
}
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// # Examples
///
/// ```
#[doc = "let x: i128 = 2; // or any other integer type"]
///
/// assert_eq!(x.pow(5), 32);
#[doc = "assert_eq!(0_i128.pow(0), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn pow(self, exp: u32) -> Self {
if intrinsics::overflow_checks() {
self.strict_pow(exp)
} else { self.wrapping_pow(exp) }
}
/// Returns the integer square root of the number, rounded down.
///
/// This function returns the **principal (non-negative) square root**.
/// For a given number `n`, although both `x` and `-x` satisfy x<sup>2</sup> = n,
/// this function always returns the non-negative value.
///
/// # Panics
///
/// This function will panic if `self` is negative.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i128.isqrt(), 3);"]
/// ```
#[stable(feature = "isqrt", since = "1.84.0")]
#[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn isqrt(self) -> Self {
match self.checked_isqrt() {
Some(sqrt) => sqrt,
None => imp::int_sqrt::panic_for_negative_argument(),
}
}
/// Calculates the quotient of Euclidean division of `self` by `rhs`.
///
/// This computes the integer `q` such that `self = q * rhs + r`, with
/// `r = self.rem_euclid(rhs)` and `0 <= r < abs(rhs)`.
///
/// In other words, the result is `self / rhs` rounded to the integer `q`
/// such that `self >= q * rhs`.
/// If `self > 0`, this is equal to rounding towards zero (the default in Rust);
/// if `self < 0`, this is equal to rounding away from zero (towards +/- infinity).
/// If `rhs > 0`, this is equal to rounding towards -infinity;
/// if `rhs < 0`, this is equal to rounding towards +infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero or if `self` is [`Self::MIN`]
/// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
///
/// # Examples
///
/// ```
#[doc = "let a: i128 = 7; // or any other integer type"]
/// let b = 4;
///
/// assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
/// assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
/// assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
/// assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_euclid(self, rhs: Self) -> Self {
let q = self / rhs;
if self % rhs < 0 { return if rhs > 0 { q - 1 } else { q + 1 } }
q
}
/// Calculates the least nonnegative remainder of `self` when
/// divided by `rhs`.
///
/// This is done as if by the Euclidean division algorithm -- given
/// `r = self.rem_euclid(rhs)`, the result satisfies
/// `self = rhs * self.div_euclid(rhs) + r` and `0 <= r < abs(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero or if `self` is [`Self::MIN`] and
/// `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
///
/// # Examples
///
/// ```
#[doc = "let a: i128 = 7; // or any other integer type"]
/// let b = 4;
///
/// assert_eq!(a.rem_euclid(b), 3);
/// assert_eq!((-a).rem_euclid(b), 1);
/// assert_eq!(a.rem_euclid(-b), 3);
/// assert_eq!((-a).rem_euclid(-b), 1);
/// ```
///
/// This will panic:
/// ```should_panic
#[doc = "let _ = i128::MIN.rem_euclid(-1);"]
/// ```
#[doc(alias = "modulo", alias = "mod")]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn rem_euclid(self, rhs: Self) -> Self {
let r = self % rhs;
if r < 0 { r.wrapping_add(rhs.wrapping_abs()) } else { r }
}
/// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero or if `self` is [`Self::MIN`]
/// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "let a: i128 = 8;"]
/// let b = 3;
///
/// assert_eq!(a.div_floor(b), 2);
/// assert_eq!(a.div_floor(-b), -3);
/// assert_eq!((-a).div_floor(b), -3);
/// assert_eq!((-a).div_floor(-b), 2);
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_floor(self, rhs: Self) -> Self {
let d = self / rhs;
let r = self % rhs;
let correction = (self ^ rhs) >> (Self::BITS - 1);
if r != 0 { d + correction } else { d }
}
/// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero or if `self` is [`Self::MIN`]
/// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "let a: i128 = 8;"]
/// let b = 3;
///
/// assert_eq!(a.div_ceil(b), 3);
/// assert_eq!(a.div_ceil(-b), -2);
/// assert_eq!((-a).div_ceil(b), -2);
/// assert_eq!((-a).div_ceil(-b), 3);
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_ceil(self, rhs: Self) -> Self {
let d = self / rhs;
let r = self % rhs;
let correction = 1 + ((self ^ rhs) >> (Self::BITS - 1));
if r != 0 { d + correction } else { d }
}
/// If `rhs` is positive, calculates the smallest value greater than or
/// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
/// calculates the largest value less than or equal to `self` that is a
/// multiple of `rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// On overflow, this function will panic if overflow checks are enabled (default in debug
/// mode) and wrap if overflow checks are disabled (default in release mode).
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "assert_eq!(16_i128.next_multiple_of(8), 16);"]
#[doc = "assert_eq!(23_i128.next_multiple_of(8), 24);"]
#[doc = "assert_eq!(16_i128.next_multiple_of(-8), 16);"]
#[doc = "assert_eq!(23_i128.next_multiple_of(-8), 16);"]
#[doc = "assert_eq!((-16_i128).next_multiple_of(8), -16);"]
#[doc = "assert_eq!((-23_i128).next_multiple_of(8), -16);"]
#[doc = "assert_eq!((-16_i128).next_multiple_of(-8), -16);"]
#[doc = "assert_eq!((-23_i128).next_multiple_of(-8), -24);"]
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_multiple_of(self, rhs: Self) -> Self {
if rhs == -1 { return self; }
let r = self % rhs;
let m =
if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) { r + rhs } else { r };
if m == 0 { self } else { self + (rhs - m) }
}
/// If `rhs` is positive, calculates the smallest value greater than or
/// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
/// calculates the largest value less than or equal to `self` that is a
/// multiple of `rhs`. Returns `None` if `rhs` is zero or the operation
/// would result in overflow.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "assert_eq!(16_i128.checked_next_multiple_of(8), Some(16));"]
#[doc = "assert_eq!(23_i128.checked_next_multiple_of(8), Some(24));"]
#[doc = "assert_eq!(16_i128.checked_next_multiple_of(-8), Some(16));"]
#[doc = "assert_eq!(23_i128.checked_next_multiple_of(-8), Some(16));"]
#[doc = "assert_eq!((-16_i128).checked_next_multiple_of(8), Some(-16));"]
#[doc = "assert_eq!((-23_i128).checked_next_multiple_of(8), Some(-16));"]
#[doc = "assert_eq!((-16_i128).checked_next_multiple_of(-8), Some(-16));"]
#[doc = "assert_eq!((-23_i128).checked_next_multiple_of(-8), Some(-24));"]
#[doc = "assert_eq!(1_i128.checked_next_multiple_of(0), None);"]
#[doc = "assert_eq!(i128::MAX.checked_next_multiple_of(2), None);"]
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
if rhs == -1 { return Some(self); }
let r =
match self.checked_rem(rhs) { Some(x) => x, None => return None, };
let m =
if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) { r + rhs } else { r };
if m == 0 { Some(self) } else { self.checked_add(rhs - m) }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// This method might not be optimized owing to implementation details;
/// [`ilog2`][Self::ilog2] can produce results more efficiently for base 2,
/// and [`ilog10`](Self::ilog10) can produce results more efficiently for base 10.
///
/// # Panics
///
/// This function will panic if `self` is less than or equal to zero,
/// or if `base` is less than 2.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i128.ilog(5), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog(self, base: Self) -> u32 {
if !(base >= 2) {
{
crate::panicking::panic_fmt(format_args!("base of integer logarithm must be at least 2"));
}
};
if let Some(log) = self.checked_ilog(base) {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the base 2 logarithm of the number, rounded down.
///
/// # Panics
///
/// This function will panic if `self` is less than or equal to zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2i128.ilog2(), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog2(self) -> u32 {
if let Some(log) = self.checked_ilog2() {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// # Panics
///
/// This function will panic if `self` is less than or equal to zero.
///
/// # Example
///
/// ```
#[doc = "assert_eq!(10i128.ilog10(), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog10(self) -> u32 {
if let Some(log) = self.checked_ilog10() {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// Returns `None` if the number is negative or zero, or if the base is not at least 2.
///
/// This method might not be optimized owing to implementation details;
/// `checked_ilog2` can produce results more efficiently for base 2, and
/// `checked_ilog10` can produce results more efficiently for base 10.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5i128.checked_ilog(5), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog(self, base: Self) -> Option<u32> {
if self <= 0 || base <= 1 {
None
} else { (self as u128).checked_ilog(base as u128) }
}
/// Returns the base 2 logarithm of the number, rounded down.
///
/// Returns `None` if the number is negative or zero.
///
/// Note that for non-negative numbers, this is equivalent to
/// [`highest_one`](Self::highest_one).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2i128.checked_ilog2(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog2(self) -> Option<u32> {
if self <= 0 {
None
} else {
let log =
(Self::BITS - 1) -
unsafe { intrinsics::ctlz_nonzero(self) as u32 };
Some(log)
}
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// Returns `None` if the number is negative or zero.
///
/// # Example
///
/// ```
#[doc = "assert_eq!(10i128.checked_ilog10(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog10(self) -> Option<u32> {
imp::int_log10::i128(self as i128)
}
/// Computes the absolute value of `self`.
///
/// # Overflow behavior
///
/// The absolute value of
#[doc = "`i128::MIN`"]
/// cannot be represented as an
#[doc = "`i128`,"]
/// and attempting to calculate it will cause an overflow. This means
/// that code in debug mode will trigger a panic on this case and
/// optimized code will return
#[doc = "`i128::MIN`"]
/// without a panic. If you do not want this behavior, consider
/// using [`unsigned_abs`](Self::unsigned_abs) instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i128.abs(), 10);"]
#[doc = "assert_eq!((-10i128).abs(), 10);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[allow(unused_attributes)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn abs(self) -> Self {
if self.is_negative() { -self } else { self }
}
/// Computes the absolute difference between `self` and `other`.
///
/// This function always returns the correct answer without overflow or
/// panics by returning an unsigned integer.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i128.abs_diff(80), 20u128);"]
#[doc = "assert_eq!(100i128.abs_diff(110), 10u128);"]
#[doc = "assert_eq!((-100i128).abs_diff(80), 180u128);"]
#[doc = "assert_eq!((-100i128).abs_diff(-120), 20u128);"]
#[doc = "assert_eq!(i128::MIN.abs_diff(i128::MAX), u128::MAX);"]
/// ```
#[stable(feature = "int_abs_diff", since = "1.60.0")]
#[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn abs_diff(self, other: Self) -> u128 {
if self < other {
(other as u128).wrapping_sub(self as u128)
} else { (self as u128).wrapping_sub(other as u128) }
}
/// Returns a number representing sign of `self`.
///
/// - `0` if the number is zero
/// - `1` if the number is positive
/// - `-1` if the number is negative
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i128.signum(), 1);"]
#[doc = "assert_eq!(0i128.signum(), 0);"]
#[doc = "assert_eq!((-10i128).signum(), -1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_sign", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn signum(self) -> Self {
crate::intrinsics::three_way_compare(self, 0) as Self
}
/// Returns `true` if `self` is positive and `false` if the number is zero or
/// negative.
///
/// # Examples
///
/// ```
#[doc = "assert!(10i128.is_positive());"]
#[doc = "assert!(!(-10i128).is_positive());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[inline(always)]
pub const fn is_positive(self) -> bool { self > 0 }
/// Returns `true` if `self` is negative and `false` if the number is zero or
/// positive.
///
/// # Examples
///
/// ```
#[doc = "assert!((-10i128).is_negative());"]
#[doc = "assert!(!10i128.is_negative());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[inline(always)]
pub const fn is_negative(self) -> bool { self < 0 }
/// Returns the memory representation of this integer as a byte array in
/// big-endian (network) byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12345678901234567890123456789012i128.to_be_bytes();"]
#[doc =
"assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
self.to_be().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// little-endian byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12345678901234567890123456789012i128.to_le_bytes();"]
#[doc =
"assert_eq!(bytes, [0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
self.to_le().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code
/// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
/// instead.
///
#[doc = ""]
///
/// [`to_be_bytes`]: Self::to_be_bytes
/// [`to_le_bytes`]: Self::to_le_bytes
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12345678901234567890123456789012i128.to_ne_bytes();"]
/// assert_eq!(
/// bytes,
/// if cfg!(target_endian = "big") {
#[doc =
" [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]"]
/// } else {
#[doc =
" [0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]"]
/// }
/// );
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
unsafe { mem::transmute(self) }
}
/// Creates an integer value from its representation as a byte array in
/// big endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc =
"let value = i128::from_be_bytes([0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]);"]
#[doc = "assert_eq!(value, 0x12345678901234567890123456789012);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_be_i128(input: &mut &[u8]) -> i128 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i128>());"]
/// *input = rest;
#[doc = " i128::from_be_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_be(Self::from_ne_bytes(bytes))
}
/// Creates an integer value from its representation as a byte array in
/// little endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc =
"let value = i128::from_le_bytes([0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);"]
#[doc = "assert_eq!(value, 0x12345678901234567890123456789012);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_le_i128(input: &mut &[u8]) -> i128 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i128>());"]
/// *input = rest;
#[doc = " i128::from_le_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_le(Self::from_ne_bytes(bytes))
}
/// Creates an integer value from its memory representation as a byte
/// array in native endianness.
///
/// As the target platform's native endianness is used, portable code
/// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
/// appropriate instead.
///
/// [`from_be_bytes`]: Self::from_be_bytes
/// [`from_le_bytes`]: Self::from_le_bytes
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = i128::from_ne_bytes(if cfg!(target_endian = \"big\") {"]
#[doc =
" [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]"]
/// } else {
#[doc =
" [0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]"]
/// });
#[doc = "assert_eq!(value, 0x12345678901234567890123456789012);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_ne_i128(input: &mut &[u8]) -> i128 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i128>());"]
/// *input = rest;
#[doc = " i128::from_ne_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use]
#[inline]
pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
unsafe { mem::transmute(bytes) }
}
/// New code should prefer to use
#[doc = "[`i128::MIN`] instead."]
///
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MIN` associated constant on this type")]
#[rustc_diagnostic_item = "i128_legacy_fn_min_value"]
pub const fn min_value() -> Self { Self::MIN }
/// New code should prefer to use
#[doc = "[`i128::MAX`] instead."]
///
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MAX` associated constant on this type")]
#[rustc_diagnostic_item = "i128_legacy_fn_max_value"]
pub const fn max_value() -> Self { Self::MAX }
/// Clamps this number to a symmetric range centred around zero.
///
/// The method clamps the number's magnitude (absolute value) to be at most `limit`.
///
/// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
/// explicit about the intent.
///
/// # Examples
///
/// ```
/// #![feature(clamp_magnitude)]
#[doc = "assert_eq!(120i128.clamp_magnitude(100), 100);"]
#[doc = "assert_eq!(-120i128.clamp_magnitude(100), -100);"]
#[doc = "assert_eq!(80i128.clamp_magnitude(100), 80);"]
#[doc = "assert_eq!(-80i128.clamp_magnitude(100), -80);"]
/// ```
#[must_use =
"this returns the clamped value and does not modify the original"]
#[unstable(feature = "clamp_magnitude", issue = "148519")]
#[inline]
pub fn clamp_magnitude(self, limit: u128) -> Self {
if let Ok(limit) = core::convert::TryInto::<i128>::try_into(limit) {
self.clamp(-limit, limit)
} else { self }
}
/// Truncate an integer to an integer of the same size or smaller, preserving the least
/// significant bits.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i8, 120i128.truncate());"]
#[doc = "assert_eq!(-120i8, (-120i128).truncate());"]
/// assert_eq!(120i8, 376i32.truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
/// instead of truncating.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i8, 120i128.saturating_truncate());"]
#[doc = "assert_eq!(-120i8, (-120i128).saturating_truncate());"]
/// assert_eq!(127i8, 376i32.saturating_truncate());
/// assert_eq!(-128i8, (-1000i32).saturating_truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn saturating_truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_saturating_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
/// is outside the bounds of the smaller type.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(Some(120i8), 120i128.checked_truncate());"]
#[doc = "assert_eq!(Some(-120i8), (-120i128).checked_truncate());"]
/// assert_eq!(None, 376i32.checked_truncate::<i8>());
/// assert_eq!(None, (-1000i32).checked_truncate::<i8>());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn checked_truncate<Target>(self) -> Option<Target> where
Self: [const] traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_checked_truncate(self)
}
/// Widen to an integer of the same size or larger, preserving its value.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i128, 120i8.widen());"]
#[doc = "assert_eq!(-120i128, (-120i8).widen());"]
/// ```
#[must_use =
"this returns the widened value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn widen<Target>(self) -> Target where Self: [const]
traits::WidenTarget<Target> {
traits::WidenTarget::internal_widen(self)
}
/// Converts `self` to the target integer type, saturating at the numeric
/// bounds instead of overflowing.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(i8::MAX, i128::MAX.saturating_cast());"]
#[doc = "assert_eq!(i8::MIN, i128::MIN.saturating_cast());"]
#[doc = "assert_eq!(42u8, 42i128.saturating_cast());"]
#[doc = "assert_eq!(0u8, (-42i128).saturating_cast());"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn saturating_cast<T: [const] BoundedCastFromInt<Self>>(self) -> T {
T::saturating_cast_from(self)
}
/// Converts `self` to the target integer type, wrapping around at the
/// boundary of the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(i128::MAX as i8, i128::MAX.wrapping_cast());"]
#[doc = "assert_eq!(i128::MIN as i8, i128::MIN.wrapping_cast());"]
#[doc = "assert_eq!(42u8, 42i128.wrapping_cast());"]
#[doc = "assert_eq!(u8::MAX - 41, (-42i128).wrapping_cast());"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn wrapping_cast<T: [const] BoundedCastFromInt<Self>>(self) -> T {
T::wrapping_cast_from(self)
}
/// Converts `self` to the target integer type, returning `None` if the value
/// is not representable by the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(Some(42u8), 42i128.checked_cast());"]
#[doc = "assert_eq!((-42i128).checked_cast::<u8>(), None);"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn checked_cast<T: [const] CheckedCastFromInt<Self>>(self)
-> Option<T> {
T::checked_cast_from(self)
}
/// Converts `self` to the target integer type, panicking if the value
/// is not representable by the target type.
///
/// # Panics
///
/// This function will panic if the value is not representable by the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(42u8, 42i128.strict_cast());"]
/// ```
///
/// The following will panic:
///
/// ```should_panic
/// #![feature(integer_casts)]
#[doc = "let _ = (-42i128).strict_cast::<u8>();"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
#[track_caller]
pub const fn strict_cast<T: [const] CheckedCastFromInt<Self>>(self) -> T {
T::strict_cast_from(self)
}
/// Converts `self` to the target integer type, assuming the value is
/// representable by the target type.
///
/// # Safety
///
/// This results in undefined behavior if the integer value of `self` is bigger than `T::MAX`,
/// or smaller than `T::MIN`, where `T` is the target type.
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const unsafe fn unchecked_cast<T: [const] CheckedCastFromInt<Self>>(self)
-> T {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(in_bounds: bool) {
if !in_bounds {
let msg =
"unsafe precondition(s) violated: i128::unchecked_cast must fit in the target type\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check({
let cast_val = self.checked_cast::<T>();
let ret = cast_val.is_some();
core::mem::forget(cast_val);
ret
});
}
};
unsafe { T::unchecked_cast_from(self) }
}int_impl! {
477Self = i128,
478 ActualT = i128,
479 UnsignedT = u128,
480 BITS = 128,
481 BITS_MINUS_ONE = 127,
482 Min = -170141183460469231731687303715884105728,
483 Max = 170141183460469231731687303715884105727,
484 rot = 16,
485 rot_op = "0x13f40000000000000000000000004f76",
486 rot_result = "0x4f7613f4",
487 swap_op = "0x12345678901234567890123456789012",
488 swapped = "0x12907856341290785634129078563412",
489 reversed = "0x48091e6a2c48091e6a2c48091e6a2c48",
490 le_bytes = "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
491 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
492 be_bytes = "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
493 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
494 to_xe_bytes_doc = "",
495 from_xe_bytes_doc = "",
496 bound_condition = "",
497 }498/// Calculates the midpoint (average) between `self` and `rhs`.
///
/// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
/// sufficiently-large signed integral type. This implies that the result is
/// always rounded towards zero and that no overflow will ever occur.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0i128.midpoint(4), 2);"]
#[doc = "assert_eq!((-1i128).midpoint(2), 0);"]
#[doc = "assert_eq!((-7i128).midpoint(0), -3);"]
#[doc = "assert_eq!(0i128.midpoint(-7), -3);"]
#[doc = "assert_eq!(0i128.midpoint(7), 3);"]
/// ```
#[stable(feature = "num_midpoint_signed", since = "1.87.0")]
#[rustc_const_stable(feature = "num_midpoint_signed", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[doc(alias = "average_floor")]
#[doc(alias = "average_ceil")]
#[doc(alias = "average")]
#[inline]
pub const fn midpoint(self, rhs: Self) -> Self {
let t = ((self ^ rhs) >> 1) + (self & rhs);
t + (if t < 0 { 1 } else { 0 } & (self ^ rhs))
}midpoint_impl! { i128, signed }499}
500501#[doc(auto_cfg = false)]
502#[cfg(target_pointer_width = "16")]
503impl isize {
504int_impl! {
505Self = isize,
506 ActualT = i16,
507 UnsignedT = usize,
508 BITS = 16,
509 BITS_MINUS_ONE = 15,
510 Min = -32768,
511 Max = 32767,
512 rot = 4,
513 rot_op = "-0x5ffd",
514 rot_result = "0x3a",
515 swap_op = "0x1234",
516 swapped = "0x3412",
517 reversed = "0x2c48",
518 le_bytes = "[0x34, 0x12]",
519 be_bytes = "[0x12, 0x34]",
520 to_xe_bytes_doc = usize_isize_to_xe_bytes_doc!(),
521 from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(),
522 bound_condition = " on 16-bit targets",
523 }
524midpoint_impl! { isize, i32, signed }
525}
526527#[doc(auto_cfg = false)]
528#[cfg(target_pointer_width = "32")]
529impl isize {
530int_impl! {
531Self = isize,
532 ActualT = i32,
533 UnsignedT = usize,
534 BITS = 32,
535 BITS_MINUS_ONE = 31,
536 Min = -2147483648,
537 Max = 2147483647,
538 rot = 8,
539 rot_op = "0x10000b3",
540 rot_result = "0xb301",
541 swap_op = "0x12345678",
542 swapped = "0x78563412",
543 reversed = "0x1e6a2c48",
544 le_bytes = "[0x78, 0x56, 0x34, 0x12]",
545 be_bytes = "[0x12, 0x34, 0x56, 0x78]",
546 to_xe_bytes_doc = usize_isize_to_xe_bytes_doc!(),
547 from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(),
548 bound_condition = " on 32-bit targets",
549 }
550midpoint_impl! { isize, i64, signed }
551}
552553#[doc(auto_cfg = false)]
554#[cfg(target_pointer_width = "64")]
555impl isize {
556/// The smallest value that can be represented by this integer type
#[doc = "(−2<sup>63</sup> on 64-bit targets)."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(isize::MIN, -9223372036854775808);"]
/// ```
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MIN: Self = !Self::MAX;
/// The largest value that can be represented by this integer type
#[doc = "(2<sup>63</sup> − 1 on 64-bit targets)."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(isize::MAX, 9223372036854775807);"]
/// ```
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MAX: Self = (<usize>::MAX >> 1) as Self;
/// The size of this integer type in bits.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(isize::BITS, 64);"]
/// ```
#[stable(feature = "int_bits_const", since = "1.53.0")]
pub const BITS: u32 = <usize>::BITS;
/// Returns the number of ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 0b100_0000isize;"]
///
/// assert_eq!(n.count_ones(), 1);
/// ```
///
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[doc(alias = "popcount")]
#[doc(alias = "popcnt")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn count_ones(self) -> u32 { (self as usize).count_ones() }
/// Returns the number of zeros in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(isize::MAX.count_zeros(), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn count_zeros(self) -> u32 { (!self).count_ones() }
/// Returns the number of leading zeros in the binary representation of `self`.
///
/// Depending on what you're doing with the value, you might also be interested in the
/// [`ilog2`] function which returns a consistent number, even if the type widens.
///
/// # Examples
///
/// ```
#[doc = "let n = -1isize;"]
///
/// assert_eq!(n.leading_zeros(), 0);
/// ```
#[doc = "[`ilog2`]: isize::ilog2"]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn leading_zeros(self) -> u32 { (self as usize).leading_zeros() }
/// Returns the number of trailing zeros in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = -4isize;"]
///
/// assert_eq!(n.trailing_zeros(), 2);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn trailing_zeros(self) -> u32 { (self as usize).trailing_zeros() }
/// Returns the number of leading ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = -1isize;"]
///
#[doc = "assert_eq!(n.leading_ones(), 64);"]
/// ```
#[stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn leading_ones(self) -> u32 { (self as usize).leading_ones() }
/// Returns the number of trailing ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 3isize;"]
///
/// assert_eq!(n.trailing_ones(), 2);
/// ```
#[stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn trailing_ones(self) -> u32 { (self as usize).trailing_ones() }
/// Returns `self` with only the most significant bit set, or `0` if
/// the input is `0`.
///
/// # Examples
///
/// ```
#[doc = "let n: isize = 0b_01100100;"]
///
/// assert_eq!(n.isolate_highest_one(), 0b_01000000);
#[doc = "assert_eq!(0_isize.isolate_highest_one(), 0);"]
/// ```
#[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn isolate_highest_one(self) -> Self {
self &
(((1 as isize) <<
(<isize>::BITS - 1)).wrapping_shr(self.leading_zeros()))
}
/// Returns `self` with only the least significant bit set, or `0` if
/// the input is `0`.
///
/// # Examples
///
/// ```
#[doc = "let n: isize = 0b_01100100;"]
///
/// assert_eq!(n.isolate_lowest_one(), 0b_00000100);
#[doc = "assert_eq!(0_isize.isolate_lowest_one(), 0);"]
/// ```
#[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn isolate_lowest_one(self) -> Self { self & self.wrapping_neg() }
/// Returns the index of the highest bit set to one in `self`, or `None`
/// if `self` is `0`.
///
/// Note that for non-negative numbers, this is equivalent to
/// [`checked_ilog2`](Self::checked_ilog2).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0b0_isize.highest_one(), None);"]
#[doc = "assert_eq!(0b1_isize.highest_one(), Some(0));"]
#[doc = "assert_eq!(0b1_0000_isize.highest_one(), Some(4));"]
#[doc = "assert_eq!(0b1_1111_isize.highest_one(), Some(4));"]
/// ```
#[stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn highest_one(self) -> Option<u32> {
(self as usize).highest_one()
}
/// Returns the index of the lowest bit set to one in `self`, or `None`
/// if `self` is `0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0b0_isize.lowest_one(), None);"]
#[doc = "assert_eq!(0b1_isize.lowest_one(), Some(0));"]
#[doc = "assert_eq!(0b1_0000_isize.lowest_one(), Some(4));"]
#[doc = "assert_eq!(0b1_1111_isize.lowest_one(), Some(0));"]
/// ```
#[stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn lowest_one(self) -> Option<u32> { (self as usize).lowest_one() }
/// Returns the bit pattern of `self` reinterpreted as an unsigned integer of the same size.
///
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
/// the same.
///
/// # Examples
///
/// ```
#[doc = "let n = -1isize;"]
///
#[doc = "assert_eq!(n.cast_unsigned(), usize::MAX);"]
/// ```
#[stable(feature = "integer_sign_cast", since = "1.87.0")]
#[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_unsigned(self) -> usize { self as usize }
/// Saturating conversion of `self` to an unsigned integer of the same size.
///
/// Negative values are clamped to `0`.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`checked_cast_unsigned`](Self::checked_cast_unsigned),
/// or [`strict_cast_unsigned`](Self::strict_cast_unsigned).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = isize::MIN;"]
///
#[doc = "assert_eq!(n.saturating_cast_unsigned(), 0usize);"]
#[doc = "assert_eq!(64isize.saturating_cast_unsigned(), 64usize);"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_cast_unsigned(self) -> usize {
if self >= 0 { self.cast_unsigned() } else { 0 }
}
/// Checked conversion of `self` to an unsigned integer of the same size,
/// returning `None` if `self` is negative.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`saturating_cast_unsigned`](Self::saturating_cast_unsigned),
/// or [`strict_cast_unsigned`](Self::strict_cast_unsigned).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = isize::MIN;"]
///
#[doc = "assert_eq!(n.checked_cast_unsigned(), None);"]
#[doc = "assert_eq!(64isize.checked_cast_unsigned(), Some(64usize));"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn checked_cast_unsigned(self) -> Option<usize> {
if self >= 0 { Some(self.cast_unsigned()) } else { None }
}
/// Strict conversion of `self` to an unsigned integer of the same size,
/// which panics if `self` is negative.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`checked_cast_unsigned`](Self::checked_cast_unsigned),
/// or [`saturating_cast_unsigned`](Self::saturating_cast_unsigned).
///
/// # Examples
///
/// ```should_panic
/// #![feature(integer_cast_extras)]
#[doc = "let _ = isize::MIN.strict_cast_unsigned();"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_cast_unsigned(self) -> usize {
match self.checked_cast_unsigned() {
Some(n) => n,
None => imp::overflow_panic::cast_integer(),
}
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `<<` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0xaa00000000006e1isize;"]
#[doc = "let m = 0x6e10aa;"]
///
#[doc = "assert_eq!(n.rotate_left(12), m);"]
#[doc = "assert_eq!(n.rotate_left(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn rotate_left(self, n: u32) -> Self {
(self as usize).rotate_left(n) as Self
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `>>` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x6e10aaisize;"]
#[doc = "let m = 0xaa00000000006e1;"]
///
#[doc = "assert_eq!(n.rotate_right(12), m);"]
#[doc = "assert_eq!(n.rotate_right(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn rotate_right(self, n: u32) -> Self {
(self as usize).rotate_right(n) as Self
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1234567890123456isize;"]
///
/// let m = n.swap_bytes();
///
#[doc = "assert_eq!(m, 0x5634129078563412);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn swap_bytes(self) -> Self { (self as usize).swap_bytes() as Self }
/// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
/// second least-significant bit becomes second most-significant bit, etc.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1234567890123456isize;"]
/// let m = n.reverse_bits();
///
#[doc = "assert_eq!(m, 0x6a2c48091e6a2c48);"]
#[doc = "assert_eq!(0, 0isize.reverse_bits());"]
/// ```
#[stable(feature = "reverse_bits", since = "1.37.0")]
#[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn reverse_bits(self) -> Self {
(self as usize).reverse_bits() as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are swapped.
///
/// See also [from_be_bytes()](Self::from_be_bytes).
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Aisize;"]
///
/// if cfg!(target_endian = "big") {
#[doc = " assert_eq!(isize::from_be(n), n)"]
/// } else {
#[doc = " assert_eq!(isize::from_be(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn from_be(x: Self) -> Self { x.swap_bytes() }
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are swapped.
///
/// See also [from_le_bytes()](Self::from_le_bytes).
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Aisize;"]
///
/// if cfg!(target_endian = "little") {
#[doc = " assert_eq!(isize::from_le(n), n)"]
/// } else {
#[doc = " assert_eq!(isize::from_le(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn from_le(x: Self) -> Self { x }
/// Swaps bytes of `self` on little endian targets.
///
/// On big endian this is a no-op.
///
/// The returned value has the same type as `self`, and will be interpreted
/// as (a potentially different) value of a native-endian
#[doc = "`isize`."]
///
/// See [`to_be_bytes()`](Self::to_be_bytes) for a type-safe alternative.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Aisize;"]
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be(self) -> Self { self.swap_bytes() }
/// Swaps bytes of `self` on big endian targets.
///
/// On little endian this is a no-op.
///
/// The returned value has the same type as `self`, and will be interpreted
/// as (a potentially different) value of a native-endian
#[doc = "`isize`."]
///
/// See [`to_le_bytes()`](Self::to_le_bytes) for a type-safe alternative.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Aisize;"]
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le(self) -> Self { self }
/// Checked integer addition. Computes `self + rhs`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((isize::MAX - 2).checked_add(1), Some(isize::MAX - 1));"]
#[doc = "assert_eq!((isize::MAX - 2).checked_add(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_add(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer addition. Computes `self + rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((isize::MAX - 2).strict_add(1), isize::MAX - 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (isize::MAX - 2).strict_add(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_add(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Unchecked integer addition. Computes `self + rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_add(y)` is semantically equivalent to calling
/// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_add`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self + rhs > isize::MAX` or `self + rhs < isize::MIN`,"]
/// i.e. when [`checked_add`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_add`]: isize::checked_add"]
#[doc = "[`wrapping_add`]: isize::wrapping_add"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: isize, rhs: isize) {
if !!lhs.overflowing_add(rhs).1 {
let msg =
"unsafe precondition(s) violated: isize::unchecked_add cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_add(self, rhs) }
}
/// Checked addition with an unsigned integer. Computes `self + rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1isize.checked_add_unsigned(2), Some(3));"]
#[doc = "assert_eq!((isize::MAX - 2).checked_add_unsigned(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add_unsigned(self, rhs: usize) -> Option<Self> {
let (a, b) = self.overflowing_add_unsigned(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict addition with an unsigned integer. Computes `self + rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1isize.strict_add_unsigned(2), 3);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (isize::MAX - 2).strict_add_unsigned(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add_unsigned(self, rhs: usize) -> Self {
let (a, b) = self.overflowing_add_unsigned(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Checked integer subtraction. Computes `self - rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((isize::MIN + 2).checked_sub(1), Some(isize::MIN + 1));"]
#[doc = "assert_eq!((isize::MIN + 2).checked_sub(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_sub(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer subtraction. Computes `self - rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((isize::MIN + 2).strict_sub(1), isize::MIN + 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (isize::MIN + 2).strict_sub(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_sub(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
/// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_sub`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self - rhs > isize::MAX` or `self - rhs < isize::MIN`,"]
/// i.e. when [`checked_sub`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_sub`]: isize::checked_sub"]
#[doc = "[`wrapping_sub`]: isize::wrapping_sub"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: isize, rhs: isize) {
if !!lhs.overflowing_sub(rhs).1 {
let msg =
"unsafe precondition(s) violated: isize::unchecked_sub cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_sub(self, rhs) }
}
/// Checked subtraction with an unsigned integer. Computes `self - rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1isize.checked_sub_unsigned(2), Some(-1));"]
#[doc = "assert_eq!((isize::MIN + 2).checked_sub_unsigned(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub_unsigned(self, rhs: usize) -> Option<Self> {
let (a, b) = self.overflowing_sub_unsigned(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict subtraction with an unsigned integer. Computes `self - rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1isize.strict_sub_unsigned(2), -1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (isize::MIN + 2).strict_sub_unsigned(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub_unsigned(self, rhs: usize) -> Self {
let (a, b) = self.overflowing_sub_unsigned(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Checked integer multiplication. Computes `self * rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(isize::MAX.checked_mul(1), Some(isize::MAX));"]
#[doc = "assert_eq!(isize::MAX.checked_mul(2), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer multiplication. Computes `self * rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(isize::MAX.strict_mul(1), isize::MAX);"]
/// ```
///
/// The following panics because of overflow:
///
/// ``` should_panic
#[doc = "let _ = isize::MAX.strict_mul(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_mul(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_mul(rhs);
if b { imp::overflow_panic::mul() } else { a }
}
/// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
/// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_mul`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self * rhs > isize::MAX` or `self * rhs < isize::MIN`,"]
/// i.e. when [`checked_mul`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_mul`]: isize::checked_mul"]
#[doc = "[`wrapping_mul`]: isize::wrapping_mul"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: isize, rhs: isize) {
if !!lhs.overflowing_mul(rhs).1 {
let msg =
"unsafe precondition(s) violated: isize::unchecked_mul cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_mul(self, rhs) }
}
/// Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
/// or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc =
"assert_eq!((isize::MIN + 1).checked_div(-1), Some(9223372036854775807));"]
#[doc = "assert_eq!(isize::MIN.checked_div(-1), None);"]
#[doc = "assert_eq!((1isize).checked_div(0), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1)))
{
None
} else { Some(unsafe { intrinsics::unchecked_div(self, rhs) }) }
}
/// Strict integer division. Computes `self / rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is when one divides `MIN / -1` on a signed type (where
/// [`MIN`](Self::MIN) is the negative minimal value for the type); the result of this is `-MIN`, a positive value
/// that is too large to represent in the type.
///
/// Note that this is equivalent to normal division: `MIN / -1` will also panic both in
/// debug and release builds.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((isize::MIN + 1).strict_div(-1), 9223372036854775807);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = isize::MIN.strict_div(-1);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1isize).strict_div(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_div(self, rhs: Self) -> Self { self / rhs }
/// Checked Euclidean division. Computes `self.div_euclid(rhs)`,
/// returning `None` if `rhs == 0` or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc =
"assert_eq!((isize::MIN + 1).checked_div_euclid(-1), Some(9223372036854775807));"]
#[doc = "assert_eq!(isize::MIN.checked_div_euclid(-1), None);"]
#[doc = "assert_eq!((1isize).checked_div_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) {
None
} else { Some(self.div_euclid(rhs)) }
}
/// Strict Euclidean division. Computes `self.div_euclid(rhs)`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is when one divides `MIN / -1` on a signed type (where
/// [`MIN`](Self::MIN) is the negative minimal value for the type); the result of this is `-MIN`, a positive value
/// that is too large to represent in the type.
///
/// Note that this is equivalent to `div_euclid`: `MIN.div_euclid(-1)` will also panic both
/// in debug and release builds.
///
/// # Examples
///
/// ```
#[doc =
"assert_eq!((isize::MIN + 1).strict_div_euclid(-1), 9223372036854775807);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = isize::MIN.strict_div_euclid(-1);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1isize).strict_div_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_div_euclid(self, rhs: Self) -> Self {
self.div_euclid(rhs)
}
/// Checked integer division without remainder. Computes `self / rhs`,
/// returning `None` if `rhs == 0`, the division results in overflow,
/// or `self % rhs != 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc =
"assert_eq!((isize::MIN + 1).checked_div_exact(-1), Some(9223372036854775807));"]
#[doc = "assert_eq!((-5isize).checked_div_exact(2), None);"]
#[doc = "assert_eq!(isize::MIN.checked_div_exact(-1), None);"]
#[doc = "assert_eq!((1isize).checked_div_exact(0), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_exact(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1)))
{
None
} else {
unsafe {
if intrinsics::unlikely(intrinsics::unchecked_rem(self, rhs) != 0)
{
None
} else { Some(intrinsics::exact_div(self, rhs)) }
}
}
}
/// Integer division without remainder. Computes `self / rhs`, returning `None` if `self % rhs != 0`.
///
/// # Panics
///
/// This function will panic if `rhs == 0`.
///
/// ## Overflow behavior
///
/// On overflow, this function will panic if overflow checks are enabled (default in debug
/// mode) and wrap if overflow checks are disabled (default in release mode).
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64isize.div_exact(2), Some(32));"]
#[doc = "assert_eq!(64isize.div_exact(32), Some(2));"]
#[doc =
"assert_eq!((isize::MIN + 1).div_exact(-1), Some(9223372036854775807));"]
#[doc = "assert_eq!(65isize.div_exact(2), None);"]
/// ```
/// ```should_panic
/// #![feature(exact_div)]
#[doc = "let _ = 64isize.div_exact(0);"]
/// ```
/// ```should_panic
/// #![feature(exact_div)]
#[doc = "let _ = isize::MIN.div_exact(-1);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn div_exact(self, rhs: Self) -> Option<Self> {
if self % rhs != 0 { None } else { Some(self / rhs) }
}
/// Unchecked integer division without remainder. Computes `self / rhs`.
///
/// # Safety
///
/// This results in undefined behavior when `rhs == 0`, `self % rhs != 0`, or
#[doc = "`self == isize::MIN && rhs == -1`,"]
/// i.e. when [`checked_div_exact`](Self::checked_div_exact) would return `None`.
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_div_exact(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: isize, rhs: isize) {
if !(rhs != 0 && lhs % rhs == 0 &&
(lhs != <isize>::MIN || rhs != -1)) {
let msg =
"unsafe precondition(s) violated: isize::unchecked_div_exact cannot overflow, divide by zero, or leave a remainder\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::exact_div(self, rhs) }
}
/// Checked integer remainder. Computes `self % rhs`, returning `None` if
/// `rhs == 0` or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5isize.checked_rem(2), Some(1));"]
#[doc = "assert_eq!(5isize.checked_rem(0), None);"]
#[doc = "assert_eq!(isize::MIN.checked_rem(-1), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1)))
{
None
} else { Some(unsafe { intrinsics::unchecked_rem(self, rhs) }) }
}
/// Strict integer remainder. Computes `self % rhs`, panicking if
/// the division results in overflow.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is `x % y` for `MIN / -1` on a
/// signed type (where [`MIN`](Self::MIN) is the negative minimal value), which is invalid due to implementation artifacts.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5isize.strict_rem(2), 1);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5isize.strict_rem(0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = isize::MIN.strict_rem(-1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_rem(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_rem(rhs);
if b { imp::overflow_panic::rem() } else { a }
}
/// Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning `None`
/// if `rhs == 0` or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5isize.checked_rem_euclid(2), Some(1));"]
#[doc = "assert_eq!(5isize.checked_rem_euclid(0), None);"]
#[doc = "assert_eq!(isize::MIN.checked_rem_euclid(-1), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) & (rhs == -1))) {
None
} else { Some(self.rem_euclid(rhs)) }
}
/// Strict Euclidean remainder. Computes `self.rem_euclid(rhs)`, panicking if
/// the division results in overflow.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is `x % y` for `MIN / -1` on a
/// signed type (where [`MIN`](Self::MIN) is the negative minimal value), which is invalid due to implementation artifacts.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5isize.strict_rem_euclid(2), 1);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5isize.strict_rem_euclid(0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = isize::MIN.strict_rem_euclid(-1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_rem_euclid(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_rem_euclid(rhs);
if b { imp::overflow_panic::rem() } else { a }
}
/// Checked negation. Computes `-self`, returning `None` if `self == MIN`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5isize.checked_neg(), Some(-5));"]
#[doc = "assert_eq!(isize::MIN.checked_neg(), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_neg(self) -> Option<Self> {
let (a, b) = self.overflowing_neg();
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Unchecked negation. Computes `-self`, assuming overflow cannot occur.
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self == isize::MIN`,"]
/// i.e. when [`checked_neg`] would return `None`.
///
#[doc = "[`checked_neg`]: isize::checked_neg"]
#[stable(feature = "unchecked_neg", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_neg", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_neg(self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: isize) {
if !!lhs.overflowing_neg().1 {
let msg =
"unsafe precondition(s) violated: isize::unchecked_neg cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self);
}
};
unsafe { intrinsics::unchecked_sub(0, self) }
}
/// Strict negation. Computes `-self`, panicking if `self == MIN`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5isize.strict_neg(), -5);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = isize::MIN.strict_neg();"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_neg(self) -> Self {
let (a, b) = self.overflowing_neg();
if b { imp::overflow_panic::neg() } else { a }
}
/// Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is larger
/// than or equal to the number of bits in `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1isize.checked_shl(4), Some(0x10));"]
#[doc = "assert_eq!(0x1isize.checked_shl(129), None);"]
#[doc = "assert_eq!(0x10isize.checked_shl(63), Some(0));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
if rhs < Self::BITS {
Some(unsafe { self.unchecked_shl(rhs) })
} else { None }
}
/// Strict shift left. Computes `self << rhs`, panicking if `rhs` is larger
/// than or equal to the number of bits in `self`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1isize.strict_shl(4), 0x10);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0x1isize.strict_shl(129);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_shl(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_shl(rhs);
if b { imp::overflow_panic::shl() } else { a }
}
/// Unchecked shift left. Computes `self << rhs`, assuming that
/// `rhs` is less than the number of bits in `self`.
///
/// # Safety
///
/// This results in undefined behavior if `rhs` is larger than
/// or equal to the number of bits in `self`,
/// i.e. when [`checked_shl`] would return `None`.
///
#[doc = "[`checked_shl`]: isize::checked_shl"]
#[stable(feature = "unchecked_shifts", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_shl(self, rhs: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(rhs: u32) {
if !(rhs < <i64>::BITS) {
let msg =
"unsafe precondition(s) violated: isize::unchecked_shl cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(rhs); }
};
unsafe { intrinsics::unchecked_shl(self, rhs) }
}
/// Unbounded shift left. Computes `self << rhs`, without bounding the value of `rhs`.
///
/// If `rhs` is larger or equal to the number of bits in `self`,
/// the entire value is shifted out, and `0` is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1_isize.unbounded_shl(4), 0x10);"]
#[doc = "assert_eq!(0x1_isize.unbounded_shl(129), 0);"]
#[doc = "assert_eq!(0b101_isize.unbounded_shl(0), 0b101);"]
#[doc = "assert_eq!(0b101_isize.unbounded_shl(1), 0b1010);"]
#[doc = "assert_eq!(0b101_isize.unbounded_shl(2), 0b10100);"]
#[doc = "assert_eq!(42_isize.unbounded_shl(64), 0);"]
#[doc = "assert_eq!(42_isize.unbounded_shl(1).unbounded_shl(63), 0);"]
#[doc = "assert_eq!((-13_isize).unbounded_shl(64), 0);"]
#[doc = "assert_eq!((-13_isize).unbounded_shl(1).unbounded_shl(63), 0);"]
/// ```
#[stable(feature = "unbounded_shifts", since = "1.87.0")]
#[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unbounded_shl(self, rhs: u32) -> isize {
if rhs < Self::BITS { unsafe { self.unchecked_shl(rhs) } } else { 0 }
}
/// Exact shift left. Computes `self << rhs` as long as it can be reversed losslessly.
///
/// Returns `None` if any bits that would be shifted out differ from the resulting sign bit
/// or if `rhs` >=
#[doc = "`isize::BITS`."]
/// Otherwise, returns `Some(self << rhs)`.
///
/// # Examples
///
/// ```
/// #![feature(exact_bitshifts)]
///
#[doc = "assert_eq!(0x1isize.shl_exact(4), Some(0x10));"]
#[doc =
"assert_eq!(0x1isize.shl_exact(isize::BITS - 2), Some(1 << isize::BITS - 2));"]
#[doc = "assert_eq!(0x1isize.shl_exact(isize::BITS - 1), None);"]
#[doc =
"assert_eq!((-0x2isize).shl_exact(isize::BITS - 2), Some(-0x2 << isize::BITS - 2));"]
#[doc = "assert_eq!((-0x2isize).shl_exact(isize::BITS - 1), None);"]
/// ```
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn shl_exact(self, rhs: u32) -> Option<isize> {
if rhs < self.leading_zeros() || rhs < self.leading_ones() {
Some(unsafe { self.unchecked_shl(rhs) })
} else { None }
}
/// Unchecked exact shift left. Computes `self << rhs`, assuming the operation can be
/// losslessly reversed and `rhs` cannot be larger than
#[doc = "`isize::BITS`."]
///
/// # Safety
///
/// This results in undefined behavior when `rhs >= self.leading_zeros() && rhs >=
/// self.leading_ones()` i.e. when
#[doc = "[`isize::shl_exact`]"]
/// would return `None`.
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_shl_exact(self, rhs: u32) -> isize {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(zeros: u32, ones: u32, rhs: u32) {
if !(rhs < zeros || rhs < ones) {
let msg =
"unsafe precondition(s) violated: isize::unchecked_shl_exact cannot shift out bits that would change the value of the first bit\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_library_ub() {
precondition_check(self.leading_zeros(), self.leading_ones(),
rhs);
}
};
unsafe { self.unchecked_shl(rhs) }
}
/// Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` is
/// larger than or equal to the number of bits in `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10isize.checked_shr(4), Some(0x1));"]
#[doc = "assert_eq!(0x10isize.checked_shr(128), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
if rhs < Self::BITS {
Some(unsafe { self.unchecked_shr(rhs) })
} else { None }
}
/// Strict shift right. Computes `self >> rhs`, panicking if `rhs` is
/// larger than or equal to the number of bits in `self`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10isize.strict_shr(4), 0x1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0x10isize.strict_shr(128);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_shr(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_shr(rhs);
if b { imp::overflow_panic::shr() } else { a }
}
/// Unchecked shift right. Computes `self >> rhs`, assuming that
/// `rhs` is less than the number of bits in `self`.
///
/// # Safety
///
/// This results in undefined behavior if `rhs` is larger than
/// or equal to the number of bits in `self`,
/// i.e. when [`checked_shr`] would return `None`.
///
#[doc = "[`checked_shr`]: isize::checked_shr"]
#[stable(feature = "unchecked_shifts", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_shr(self, rhs: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(rhs: u32) {
if !(rhs < <i64>::BITS) {
let msg =
"unsafe precondition(s) violated: isize::unchecked_shr cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(rhs); }
};
unsafe { intrinsics::unchecked_shr(self, rhs) }
}
/// Unbounded shift right. Computes `self >> rhs`, without bounding the value of `rhs`.
///
/// If `rhs` is larger or equal to the number of bits in `self`,
/// the entire value is shifted out, which yields `0` for a positive number,
/// and `-1` for a negative number.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10_isize.unbounded_shr(4), 0x1);"]
#[doc = "assert_eq!(0x10_isize.unbounded_shr(129), 0);"]
#[doc = "assert_eq!(isize::MIN.unbounded_shr(129), -1);"]
#[doc = "assert_eq!(0b1010_isize.unbounded_shr(0), 0b1010);"]
#[doc = "assert_eq!(0b1010_isize.unbounded_shr(1), 0b101);"]
#[doc = "assert_eq!(0b1010_isize.unbounded_shr(2), 0b10);"]
#[doc = "assert_eq!(42_isize.unbounded_shr(64), 0);"]
#[doc = "assert_eq!(42_isize.unbounded_shr(1).unbounded_shr(63), 0);"]
#[doc = "assert_eq!((-13_isize).unbounded_shr(64), -1);"]
#[doc = "assert_eq!((-13_isize).unbounded_shr(1).unbounded_shr(63), -1);"]
/// ```
#[stable(feature = "unbounded_shifts", since = "1.87.0")]
#[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unbounded_shr(self, rhs: u32) -> isize {
if rhs < Self::BITS {
unsafe { self.unchecked_shr(rhs) }
} else { unsafe { self.unchecked_shr(Self::BITS - 1) } }
}
/// Exact shift right. Computes `self >> rhs` as long as it can be reversed losslessly.
///
/// Returns `None` if any non-zero bits would be shifted out or if `rhs` >=
#[doc = "`isize::BITS`."]
/// Otherwise, returns `Some(self >> rhs)`.
///
/// # Examples
///
/// ```
/// #![feature(exact_bitshifts)]
///
#[doc = "assert_eq!(0x10isize.shr_exact(4), Some(0x1));"]
#[doc = "assert_eq!(0x10isize.shr_exact(5), None);"]
/// ```
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn shr_exact(self, rhs: u32) -> Option<isize> {
if rhs <= self.trailing_zeros() && rhs < <isize>::BITS {
Some(unsafe { self.unchecked_shr(rhs) })
} else { None }
}
/// Unchecked exact shift right. Computes `self >> rhs`, assuming the operation can be
/// losslessly reversed and `rhs` cannot be larger than
#[doc = "`isize::BITS`."]
///
/// # Safety
///
/// This results in undefined behavior when `rhs > self.trailing_zeros() || rhs >=
#[doc = "isize::BITS`"]
/// i.e. when
#[doc = "[`isize::shr_exact`]"]
/// would return `None`.
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_shr_exact(self, rhs: u32) -> isize {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(zeros: u32, bits: u32, rhs: u32) {
if !(rhs <= zeros && rhs < bits) {
let msg =
"unsafe precondition(s) violated: isize::unchecked_shr_exact cannot shift out non-zero bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_library_ub() {
precondition_check(self.trailing_zeros(), <isize>::BITS, rhs);
}
};
unsafe { self.unchecked_shr(rhs) }
}
/// Checked absolute value. Computes `self.abs()`, returning `None` if
/// `self == MIN`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-5isize).checked_abs(), Some(5));"]
#[doc = "assert_eq!(isize::MIN.checked_abs(), None);"]
/// ```
#[stable(feature = "no_panic_abs", since = "1.13.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_abs(self) -> Option<Self> {
if self.is_negative() { self.checked_neg() } else { Some(self) }
}
/// Strict absolute value. Computes `self.abs()`, panicking if
/// `self == MIN`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-5isize).strict_abs(), 5);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = isize::MIN.strict_abs();"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_abs(self) -> Self {
if self.is_negative() { self.strict_neg() } else { self }
}
/// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(8isize.checked_pow(2), Some(64));"]
#[doc = "assert_eq!(0_isize.checked_pow(0), Some(1));"]
#[doc = "assert_eq!(isize::MAX.checked_pow(2), None);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
let mut base = self;
let mut acc: Self = 1;
if intrinsics::is_val_statically_known(base) &&
base.unsigned_abs().is_power_of_two() {
let k = base.unsigned_abs().ilog2();
let shift =
match k.checked_mul(exp) { Some(x) => x, None => return None, };
return if base < 0 && (exp % 2) == 1 {
(-1 as Self).shl_exact(shift)
} else { (1 as Self).shl_exact(shift) }
}
if exp == 0 { return Some(1); }
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 {
acc =
match acc.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
exp /= 2;
base =
match base.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
return acc.checked_mul(base);
}
loop {
if (exp & 1) == 1 {
acc =
match acc.checked_mul(base) {
Some(x) => x,
None => return None,
};
if exp == 1 { return Some(acc); }
}
exp /= 2;
base =
match base.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
}
/// Strict exponentiation. Computes `self.pow(exp)`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(8isize.strict_pow(2), 64);"]
#[doc = "assert_eq!(0_isize.strict_pow(0), 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = isize::MAX.strict_pow(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) {
Some(x) => x,
None => imp::overflow_panic::pow(),
}
}
/// Returns the integer square root of the number, rounded down.
///
/// This function returns the **principal (non-negative) square root**.
/// For a given number `n`, although both `x` and `-x` satisfy x<sup>2</sup> = n,
/// this function always returns the non-negative value.
///
/// Returns `None` if `self` is negative.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10isize.checked_isqrt(), Some(3));"]
/// ```
#[stable(feature = "isqrt", since = "1.84.0")]
#[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_isqrt(self) -> Option<Self> {
if self < 0 {
None
} else {
let result = self.cast_unsigned().isqrt().cast_signed();
unsafe {
const MAX_RESULT: isize =
<isize>::MAX.cast_unsigned().isqrt().cast_signed();
crate::hint::assert_unchecked(result <= MAX_RESULT);
}
Some(result)
}
}
/// Saturating integer addition. Computes `self + rhs`, saturating at the numeric
/// bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100isize.saturating_add(1), 101);"]
#[doc = "assert_eq!(isize::MAX.saturating_add(100), isize::MAX);"]
#[doc = "assert_eq!(isize::MIN.saturating_add(-1), isize::MIN);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_add(self, rhs: Self) -> Self {
intrinsics::saturating_add(self, rhs)
}
/// Saturating addition with an unsigned integer. Computes `self + rhs`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1isize.saturating_add_unsigned(2), 3);"]
#[doc = "assert_eq!(isize::MAX.saturating_add_unsigned(100), isize::MAX);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_add_unsigned(self, rhs: usize) -> Self {
match self.checked_add_unsigned(rhs) { Some(x) => x, None => Self::MAX, }
}
/// Saturating integer subtraction. Computes `self - rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100isize.saturating_sub(127), -27);"]
#[doc = "assert_eq!(isize::MIN.saturating_sub(100), isize::MIN);"]
#[doc = "assert_eq!(isize::MAX.saturating_sub(-1), isize::MAX);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_sub(self, rhs: Self) -> Self {
intrinsics::saturating_sub(self, rhs)
}
/// Saturating subtraction with an unsigned integer. Computes `self - rhs`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100isize.saturating_sub_unsigned(127), -27);"]
#[doc = "assert_eq!(isize::MIN.saturating_sub_unsigned(100), isize::MIN);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_sub_unsigned(self, rhs: usize) -> Self {
match self.checked_sub_unsigned(rhs) { Some(x) => x, None => Self::MIN, }
}
/// Saturating integer negation. Computes `-self`, returning `MAX` if `self == MIN`
/// instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100isize.saturating_neg(), -100);"]
#[doc = "assert_eq!((-100isize).saturating_neg(), 100);"]
#[doc = "assert_eq!(isize::MIN.saturating_neg(), isize::MAX);"]
#[doc = "assert_eq!(isize::MAX.saturating_neg(), isize::MIN + 1);"]
/// ```
#[stable(feature = "saturating_neg", since = "1.45.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_neg(self) -> Self {
intrinsics::saturating_sub(0, self)
}
/// Saturating absolute value. Computes `self.abs()`, returning `MAX` if `self ==
/// MIN` instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100isize.saturating_abs(), 100);"]
#[doc = "assert_eq!((-100isize).saturating_abs(), 100);"]
#[doc = "assert_eq!(isize::MIN.saturating_abs(), isize::MAX);"]
#[doc = "assert_eq!((isize::MIN + 1).saturating_abs(), isize::MAX);"]
/// ```
#[stable(feature = "saturating_neg", since = "1.45.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_abs(self) -> Self {
if self.is_negative() { self.saturating_neg() } else { self }
}
/// Saturating integer multiplication. Computes `self * rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10isize.saturating_mul(12), 120);"]
#[doc = "assert_eq!(isize::MAX.saturating_mul(10), isize::MAX);"]
#[doc = "assert_eq!(isize::MIN.saturating_mul(10), isize::MIN);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_mul(self, rhs: Self) -> Self {
match self.checked_mul(rhs) {
Some(x) => x,
None => if (self < 0) == (rhs < 0) { Self::MAX } else { Self::MIN },
}
}
/// Saturating integer division. Computes `self / rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5isize.saturating_div(2), 2);"]
#[doc = "assert_eq!(isize::MAX.saturating_div(-1), isize::MIN + 1);"]
#[doc = "assert_eq!(isize::MIN.saturating_div(-1), isize::MAX);"]
///
/// ```
#[stable(feature = "saturating_div", since = "1.58.0")]
#[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_div(self, rhs: Self) -> Self {
match self.overflowing_div(rhs) {
(result, false) => result,
(_result, true) => Self::MAX,
}
}
/// Saturating integer exponentiation. Computes `self.pow(exp)`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-4isize).saturating_pow(3), -64);"]
#[doc = "assert_eq!(0_isize.saturating_pow(0), 1);"]
#[doc = "assert_eq!(isize::MIN.saturating_pow(2), isize::MAX);"]
#[doc = "assert_eq!(isize::MIN.saturating_pow(3), isize::MIN);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) {
Some(x) => x,
None if self < 0 && exp % 2 == 1 => Self::MIN,
None => Self::MAX,
}
}
/// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at the
/// boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100isize.wrapping_add(27), 127);"]
#[doc = "assert_eq!(isize::MAX.wrapping_add(2), isize::MIN + 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_add(self, rhs: Self) -> Self {
intrinsics::wrapping_add(self, rhs)
}
/// Wrapping (modular) addition with an unsigned integer. Computes
/// `self + rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100isize.wrapping_add_unsigned(27), 127);"]
#[doc = "assert_eq!(isize::MAX.wrapping_add_unsigned(2), isize::MIN + 1);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_add_unsigned(self, rhs: usize) -> Self {
self.wrapping_add(rhs as Self)
}
/// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around at the
/// boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0isize.wrapping_sub(127), -127);"]
#[doc = "assert_eq!((-2isize).wrapping_sub(isize::MAX), isize::MAX);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_sub(self, rhs: Self) -> Self {
intrinsics::wrapping_sub(self, rhs)
}
/// Wrapping (modular) subtraction with an unsigned integer. Computes
/// `self - rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0isize.wrapping_sub_unsigned(127), -127);"]
#[doc = "assert_eq!((-2isize).wrapping_sub_unsigned(usize::MAX), -1);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_sub_unsigned(self, rhs: usize) -> Self {
self.wrapping_sub(rhs as Self)
}
/// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping around at
/// the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10isize.wrapping_mul(12), 120);"]
/// assert_eq!(11i8.wrapping_mul(12), -124);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_mul(self, rhs: Self) -> Self {
intrinsics::wrapping_mul(self, rhs)
}
/// Wrapping (modular) division. Computes `self / rhs`, wrapping around at the
/// boundary of the type.
///
/// The only case where such wrapping can occur is when one divides `MIN / -1` on a signed type (where
/// [`MIN`](Self::MIN) is the negative minimal value for the type); this is equivalent to `-MIN`, a positive value
/// that is too large to represent in the type. In such a case, this function returns [`MIN`](Self::MIN) itself.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100isize.wrapping_div(10), 10);"]
/// assert_eq!((-128i8).wrapping_div(-1), -128);
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_div(self, rhs: Self) -> Self {
self.overflowing_div(rhs).0
}
/// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`,
/// wrapping around at the boundary of the type.
///
/// Wrapping will only occur in `MIN / -1` on a signed type (where [`MIN`](Self::MIN) is the negative minimal value
/// for the type). This is equivalent to `-MIN`, a positive value that is too large to represent in the
/// type. In this case, this method returns [`MIN`](Self::MIN) itself.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100isize.wrapping_div_euclid(10), 10);"]
/// assert_eq!((-128i8).wrapping_div_euclid(-1), -128);
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_div_euclid(self, rhs: Self) -> Self {
self.overflowing_div_euclid(rhs).0
}
/// Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at the
/// boundary of the type.
///
/// Such wrap-around never actually occurs mathematically; implementation artifacts make `x % y`
/// invalid for `MIN / -1` on a signed type (where [`MIN`](Self::MIN) is the negative minimal value). In such a case,
/// this function returns `0`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100isize.wrapping_rem(10), 0);"]
/// assert_eq!((-128i8).wrapping_rem(-1), 0);
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_rem(self, rhs: Self) -> Self {
self.overflowing_rem(rhs).0
}
/// Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping around
/// at the boundary of the type.
///
/// Wrapping will only occur in `MIN % -1` on a signed type (where [`MIN`](Self::MIN) is
/// the negative minimal value for the type). In this case, this method returns 0.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100isize.wrapping_rem_euclid(10), 0);"]
/// assert_eq!((-128i8).wrapping_rem_euclid(-1), 0);
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self {
self.overflowing_rem_euclid(rhs).0
}
/// Wrapping (modular) negation. Computes `-self`, wrapping around at the boundary
/// of the type.
///
/// The only case where such wrapping can occur is when one negates [`MIN`](Self::MIN) on a signed type (where [`MIN`](Self::MIN)
/// is the negative minimal value for the type); this is a positive value that is too large to represent
/// in the type. In such a case, this function returns [`MIN`](Self::MIN) itself.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100isize.wrapping_neg(), -100);"]
#[doc = "assert_eq!((-100isize).wrapping_neg(), 100);"]
#[doc = "assert_eq!(isize::MIN.wrapping_neg(), isize::MIN);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_neg(self) -> Self { (0 as isize).wrapping_sub(self) }
/// Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` removes
/// any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
///
/// Beware that, unlike most other `wrapping_*` methods on integers, this
/// does *not* give the same result as doing the shift in infinite precision
/// then truncating as needed. Instead, the behaviour of this method matches what shift instructions
/// do on many processors, and is what the `<<` operator does when overflow
/// checks are disabled, but numerically it's weird. Consider, instead,
/// using [`Self::unbounded_shl`] which has nicer behaviour.
///
/// Note that this is *not* the same as a rotate-left; the RHS of a wrapping shift-left is restricted to
/// the range of the type, rather than the bits shifted out of the LHS being returned to the other end.
/// The primitive integer types all implement a [`rotate_left`](Self::rotate_left) function,
/// which may be what you want instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-1_isize).wrapping_shl(7), -128);"]
#[doc = "assert_eq!(42_isize.wrapping_shl(64), 42);"]
#[doc = "assert_eq!(42_isize.wrapping_shl(1).wrapping_shl(63), 0);"]
#[doc = "assert_eq!((-1_isize).wrapping_shl(128), -1);"]
#[doc = "assert_eq!(5_isize.wrapping_shl(1025), 10);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_shl(self, rhs: u32) -> Self {
unsafe { self.unchecked_shl(rhs & (Self::BITS - 1)) }
}
/// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask`
/// removes any high-order bits of `rhs` that would cause the shift to exceed the bitwidth of the type.
///
/// Beware that, unlike most other `wrapping_*` methods on integers, this
/// does *not* give the same result as doing the shift in infinite precision
/// then truncating as needed. Instead, the behaviour of this method matches what shift instructions
/// do on many processors, and is what the `>>` operator does when overflow
/// checks are disabled, but numerically it's weird. Consider, instead,
/// using [`Self::unbounded_shr`] which has nicer behaviour.
///
/// Note that this is *not* the same as a rotate-right; the RHS of a wrapping shift-right is restricted
/// to the range of the type, rather than the bits shifted out of the LHS being returned to the other
/// end. The primitive integer types all implement a [`rotate_right`](Self::rotate_right) function,
/// which may be what you want instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((-128_isize).wrapping_shr(7), -1);"]
#[doc = "assert_eq!(42_isize.wrapping_shr(64), 42);"]
#[doc = "assert_eq!(42_isize.wrapping_shr(1).wrapping_shr(63), 0);"]
/// assert_eq!((-128_i16).wrapping_shr(64), -128);
#[doc = "assert_eq!(10_isize.wrapping_shr(1025), 5);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_shr(self, rhs: u32) -> Self {
unsafe { self.unchecked_shr(rhs & (Self::BITS - 1)) }
}
/// Wrapping (modular) absolute value. Computes `self.abs()`, wrapping around at
/// the boundary of the type.
///
/// The only case where such wrapping can occur is when one takes the absolute value of the negative
/// minimal value for the type; this is a positive value that is too large to represent in the type. In
/// such a case, this function returns [`MIN`](Self::MIN) itself.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100isize.wrapping_abs(), 100);"]
#[doc = "assert_eq!((-100isize).wrapping_abs(), 100);"]
#[doc = "assert_eq!(isize::MIN.wrapping_abs(), isize::MIN);"]
/// assert_eq!((-128i8).wrapping_abs() as u8, 128);
/// ```
#[stable(feature = "no_panic_abs", since = "1.13.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[allow(unused_attributes)]
#[inline]
pub const fn wrapping_abs(self) -> Self {
if self.is_negative() { self.wrapping_neg() } else { self }
}
/// Computes the absolute value of `self` without any wrapping
/// or panicking.
///
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100isize.unsigned_abs(), 100usize);"]
#[doc = "assert_eq!((-100isize).unsigned_abs(), 100usize);"]
/// assert_eq!((-128i8).unsigned_abs(), 128u8);
/// ```
#[stable(feature = "unsigned_abs", since = "1.51.0")]
#[rustc_const_stable(feature = "unsigned_abs", since = "1.51.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unsigned_abs(self) -> usize { self.wrapping_abs() as usize }
/// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3isize.wrapping_pow(4), 81);"]
/// assert_eq!(3i8.wrapping_pow(5), -13);
/// assert_eq!(3i8.wrapping_pow(6), -39);
#[doc = "assert_eq!(0_isize.wrapping_pow(0), 1);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_pow(self, exp: u32) -> Self {
let (a, _) = self.overflowing_pow(exp);
a
}
/// Calculates `self` + `rhs`.
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would have
/// occurred then the wrapped value is returned (negative if overflowed
/// above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5isize.overflowing_add(2), (7, false));"]
#[doc = "assert_eq!(isize::MAX.overflowing_add(1), (isize::MIN, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::add_with_overflow(self as i64, rhs as i64);
(a as Self, b)
}
/// Calculates `self` + `rhs` + `carry` and checks for overflow.
///
/// Performs "ternary addition" of two integer operands and a carry-in
/// bit, and returns a tuple of the sum along with a boolean indicating
/// whether an arithmetic overflow would occur. On overflow, the wrapped
/// value is returned.
///
/// This allows chaining together multiple additions to create a wider
/// addition, and can be useful for bignum addition. This method should
/// only be used for the most significant word; for the less significant
/// words the unsigned method
#[doc = "[`usize::carrying_add`]"]
/// should be used.
///
/// The output boolean returned by this method is *not* a carry flag,
/// and should *not* be added to a more significant word.
///
/// If overflow occurred, the wrapped value is returned (negative if overflowed
/// above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
///
/// If the input carry is false, this method is equivalent to
/// [`overflowing_add`](Self::overflowing_add).
///
/// # Examples
///
/// ```
/// #![feature(signed_bigint_helpers)]
/// // Only the most significant word is signed.
/// //
#[doc = "// 10 MAX (a = 10 \u{d7} 2^64 + 2^64 - 1)"]
#[doc = "// + -5 9 (b = -5 \u{d7} 2^64 + 9)"]
/// // ---------
#[doc = "// 6 8 (sum = 6 \u{d7} 2^64 + 8)"]
///
#[doc = "let (a1, a0): (isize, usize) = (10, usize::MAX);"]
#[doc = "let (b1, b0): (isize, usize) = (-5, 9);"]
/// let carry0 = false;
///
#[doc = "// usize::carrying_add for the less significant words"]
/// let (sum0, carry1) = a0.carrying_add(b0, carry0);
/// assert_eq!(carry1, true);
///
#[doc = "// isize::carrying_add for the most significant word"]
/// let (sum1, overflow) = a1.carrying_add(b1, carry1);
/// assert_eq!(overflow, false);
///
/// assert_eq!((sum1, sum0), (6, 8));
/// ```
#[unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
let (a, b) = self.overflowing_add(rhs);
let (c, d) = a.overflowing_add(carry as isize);
(c, b != d)
}
/// Calculates `self` + `rhs` with an unsigned `rhs`.
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1isize.overflowing_add_unsigned(2), (3, false));"]
#[doc =
"assert_eq!((isize::MIN).overflowing_add_unsigned(usize::MAX), (isize::MAX, false));"]
#[doc =
"assert_eq!((isize::MAX - 2).overflowing_add_unsigned(3), (isize::MIN, true));"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_add_unsigned(self, rhs: usize) -> (Self, bool) {
let rhs = rhs as Self;
let (res, overflowed) = self.overflowing_add(rhs);
(res, overflowed ^ (rhs < 0))
}
/// Calculates `self` - `rhs`.
///
/// Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
/// would occur. If an overflow would have occurred then the wrapped value is returned
/// (negative if overflowed above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5isize.overflowing_sub(2), (3, false));"]
#[doc = "assert_eq!(isize::MIN.overflowing_sub(1), (isize::MAX, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::sub_with_overflow(self as i64, rhs as i64);
(a as Self, b)
}
/// Calculates `self` − `rhs` − `borrow` and checks for
/// overflow.
///
/// Performs "ternary subtraction" by subtracting both an integer
/// operand and a borrow-in bit from `self`, and returns a tuple of the
/// difference along with a boolean indicating whether an arithmetic
/// overflow would occur. On overflow, the wrapped value is returned.
///
/// This allows chaining together multiple subtractions to create a
/// wider subtraction, and can be useful for bignum subtraction. This
/// method should only be used for the most significant word; for the
/// less significant words the unsigned method
#[doc = "[`usize::borrowing_sub`]"]
/// should be used.
///
/// The output boolean returned by this method is *not* a borrow flag,
/// and should *not* be subtracted from a more significant word.
///
/// If overflow occurred, the wrapped value is returned (negative if overflowed
/// above [`MAX`](Self::MAX), non-negative if below [`MIN`](Self::MIN)).
///
/// If the input borrow is false, this method is equivalent to
/// [`overflowing_sub`](Self::overflowing_sub).
///
/// # Examples
///
/// ```
/// #![feature(signed_bigint_helpers)]
/// // Only the most significant word is signed.
/// //
#[doc = "// 6 8 (a = 6 \u{d7} 2^64 + 8)"]
#[doc = "// - -5 9 (b = -5 \u{d7} 2^64 + 9)"]
/// // ---------
#[doc = "// 10 MAX (diff = 10 \u{d7} 2^64 + 2^64 - 1)"]
///
#[doc = "let (a1, a0): (isize, usize) = (6, 8);"]
#[doc = "let (b1, b0): (isize, usize) = (-5, 9);"]
/// let borrow0 = false;
///
#[doc = "// usize::borrowing_sub for the less significant words"]
/// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);
/// assert_eq!(borrow1, true);
///
#[doc = "// isize::borrowing_sub for the most significant word"]
/// let (diff1, overflow) = a1.borrowing_sub(b1, borrow1);
/// assert_eq!(overflow, false);
///
#[doc = "assert_eq!((diff1, diff0), (10, usize::MAX));"]
/// ```
#[unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
let (a, b) = self.overflowing_sub(rhs);
let (c, d) = a.overflowing_sub(borrow as isize);
(c, b != d)
}
/// Calculates `self` - `rhs` with an unsigned `rhs`.
///
/// Returns a tuple of the subtraction along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1isize.overflowing_sub_unsigned(2), (-1, false));"]
#[doc =
"assert_eq!((isize::MAX).overflowing_sub_unsigned(usize::MAX), (isize::MIN, false));"]
#[doc =
"assert_eq!((isize::MIN + 2).overflowing_sub_unsigned(3), (isize::MAX, true));"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_sub_unsigned(self, rhs: usize) -> (Self, bool) {
let rhs = rhs as Self;
let (res, overflowed) = self.overflowing_sub(rhs);
(res, overflowed ^ (rhs < 0))
}
/// Calculates the multiplication of `self` and `rhs`.
///
/// Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
/// would occur. If an overflow would have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5isize.overflowing_mul(2), (10, false));"]
/// assert_eq!(1_000_000_000i32.overflowing_mul(10), (1410065408, true));
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::mul_with_overflow(self as i64, rhs as i64);
(a as Self, b)
}
/// Calculates the "full multiplication" `self * rhs + carry`
/// without the possibility to overflow.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// Performs "long multiplication" which takes in an extra amount to add, and may return an
/// additional amount of overflow. This allows for chaining together multiple
/// multiplications to create "big integers" which represent larger values.
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why [`i32`] is used.
///
/// ```
/// #![feature(signed_bigint_helpers)]
/// assert_eq!(5i32.carrying_mul(-2, 0), (4294967286, -1));
/// assert_eq!(5i32.carrying_mul(-2, 10), (0, 0));
/// assert_eq!(1_000_000_000i32.carrying_mul(-10, 0), (2884901888, -3));
/// assert_eq!(1_000_000_000i32.carrying_mul(-10, 10), (2884901898, -3));
#[doc =
"assert_eq!(isize::MAX.carrying_mul(isize::MAX, isize::MAX), (isize::MAX.unsigned_abs() + 1, isize::MAX / 2));"]
/// ```
#[unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[rustc_const_unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_mul(self, rhs: Self, carry: Self) -> (usize, Self) {
Self::carrying_mul_add(self, rhs, carry, 0)
}
/// Calculates the "full multiplication" `self * rhs + carry + add`
/// without the possibility to overflow.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// Performs "long multiplication" which takes in an extra amount to add, and may return an
/// additional amount of overflow. This allows for chaining together multiple
/// multiplications to create "big integers" which represent larger values.
///
/// If you only need one `carry`, then you can use [`Self::carrying_mul`] instead.
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `i32` is used.
///
/// ```
/// #![feature(signed_bigint_helpers)]
/// assert_eq!(5i32.carrying_mul_add(-2, 0, 0), (4294967286, -1));
/// assert_eq!(5i32.carrying_mul_add(-2, 10, 10), (10, 0));
/// assert_eq!(1_000_000_000i32.carrying_mul_add(-10, 0, 0), (2884901888, -3));
/// assert_eq!(1_000_000_000i32.carrying_mul_add(-10, 10, 10), (2884901908, -3));
#[doc =
"assert_eq!(isize::MAX.carrying_mul_add(isize::MAX, isize::MAX, isize::MAX), (usize::MAX, isize::MAX / 2));"]
/// ```
#[unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[rustc_const_unstable(feature = "signed_bigint_helpers", issue = "151989")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_mul_add(self, rhs: Self, carry: Self, add: Self)
-> (usize, Self) {
intrinsics::carrying_mul_add(self, rhs, carry, add)
}
/// Calculates the divisor when `self` is divided by `rhs`.
///
/// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
/// occur. If an overflow would occur then self is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5isize.overflowing_div(2), (2, false));"]
#[doc = "assert_eq!(isize::MIN.overflowing_div(-1), (isize::MIN, true));"]
/// ```
#[inline]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_overflowing_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
if intrinsics::unlikely((self == Self::MIN) & (rhs == -1)) {
(self, true)
} else { (self / rhs, false) }
}
/// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
///
/// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
/// occur. If an overflow would occur then `self` is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5isize.overflowing_div_euclid(2), (2, false));"]
#[doc =
"assert_eq!(isize::MIN.overflowing_div_euclid(-1), (isize::MIN, true));"]
/// ```
#[inline]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
if intrinsics::unlikely((self == Self::MIN) & (rhs == -1)) {
(self, true)
} else { (self.div_euclid(rhs), false) }
}
/// Calculates the remainder when `self` is divided by `rhs`.
///
/// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
/// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5isize.overflowing_rem(2), (1, false));"]
#[doc = "assert_eq!(isize::MIN.overflowing_rem(-1), (0, true));"]
/// ```
#[inline]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_overflowing_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
if intrinsics::unlikely(rhs == -1) {
(0, self == Self::MIN)
} else { (self % rhs, false) }
}
/// Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`.
///
/// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
/// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5isize.overflowing_rem_euclid(2), (1, false));"]
#[doc = "assert_eq!(isize::MIN.overflowing_rem_euclid(-1), (0, true));"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
if intrinsics::unlikely(rhs == -1) {
(0, self == Self::MIN)
} else { (self.rem_euclid(rhs), false) }
}
/// Negates self, overflowing if this is equal to the minimum value.
///
/// Returns a tuple of the negated version of self along with a boolean indicating whether an overflow
/// happened. If `self` is the minimum value (e.g., [`i32::MIN`] for values of type [`i32`]), then the
/// minimum value will be returned again and `true` will be returned for an overflow happening.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2isize.overflowing_neg(), (-2, false));"]
#[doc = "assert_eq!(isize::MIN.overflowing_neg(), (isize::MIN, true));"]
/// ```
#[inline]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[allow(unused_attributes)]
pub const fn overflowing_neg(self) -> (Self, bool) {
if intrinsics::unlikely(self == Self::MIN) {
(Self::MIN, true)
} else { (-self, false) }
}
/// Shifts self left by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
/// value was larger than or equal to the number of bits. If the shift value is too large, then value is
/// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1isize.overflowing_shl(4), (0x10, false));"]
/// assert_eq!(0x1i32.overflowing_shl(36), (0x10, true));
#[doc = "assert_eq!(0x10isize.overflowing_shl(63), (0, false));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shl(rhs), rhs >= Self::BITS)
}
/// Shifts self right by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean indicating whether the shift
/// value was larger than or equal to the number of bits. If the shift value is too large, then value is
/// masked (N-1) where N is the number of bits, and this value is then used to perform the shift.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10isize.overflowing_shr(4), (0x1, false));"]
/// assert_eq!(0x10i32.overflowing_shr(36), (0x1, true));
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shr(rhs), rhs >= Self::BITS)
}
/// Computes the absolute value of `self`.
///
/// Returns a tuple of the absolute version of self along with a boolean indicating whether an overflow
/// happened. If self is the minimum value
#[doc = "(e.g., [`isize::MIN`] for values of type [`isize`]),"]
/// then the minimum value will be returned again and true will be returned
/// for an overflow happening.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10isize.overflowing_abs(), (10, false));"]
#[doc = "assert_eq!((-10isize).overflowing_abs(), (10, false));"]
#[doc = "assert_eq!((isize::MIN).overflowing_abs(), (isize::MIN, true));"]
/// ```
#[stable(feature = "no_panic_abs", since = "1.13.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_abs(self) -> (Self, bool) {
(self.wrapping_abs(), self == Self::MIN)
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// Returns a tuple of the exponentiation along with a bool indicating
/// whether an overflow happened.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3isize.overflowing_pow(4), (81, false));"]
#[doc = "assert_eq!(0_isize.overflowing_pow(0), (1, false));"]
/// assert_eq!(3i8.overflowing_pow(5), (-13, true));
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
let mut base = self;
let mut acc: Self = 1;
let mut overflow = false;
let mut tmp_overflow;
if intrinsics::is_val_statically_known(base) &&
base.unsigned_abs().is_power_of_two() {
let k = base.unsigned_abs().ilog2();
let Some(shift) = k.checked_mul(exp) else { return (0, true) };
let base: Self = if base < 0 && (exp % 2) != 0 { -1 } else { 1 };
return (base.unbounded_shl(shift), base.shl_exact(shift).is_none());
}
if exp == 0 { return (1, false); }
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 {
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
}
exp /= 2;
(base, tmp_overflow) = base.overflowing_mul(base);
overflow |= tmp_overflow;
}
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
return (acc, overflow);
}
loop {
if (exp & 1) == 1 {
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
if exp == 1 { return (acc, overflow); }
}
exp /= 2;
(base, tmp_overflow) = base.overflowing_mul(base);
overflow |= tmp_overflow;
}
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// # Examples
///
/// ```
#[doc = "let x: isize = 2; // or any other integer type"]
///
/// assert_eq!(x.pow(5), 32);
#[doc = "assert_eq!(0_isize.pow(0), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn pow(self, exp: u32) -> Self {
if intrinsics::overflow_checks() {
self.strict_pow(exp)
} else { self.wrapping_pow(exp) }
}
/// Returns the integer square root of the number, rounded down.
///
/// This function returns the **principal (non-negative) square root**.
/// For a given number `n`, although both `x` and `-x` satisfy x<sup>2</sup> = n,
/// this function always returns the non-negative value.
///
/// # Panics
///
/// This function will panic if `self` is negative.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10isize.isqrt(), 3);"]
/// ```
#[stable(feature = "isqrt", since = "1.84.0")]
#[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn isqrt(self) -> Self {
match self.checked_isqrt() {
Some(sqrt) => sqrt,
None => imp::int_sqrt::panic_for_negative_argument(),
}
}
/// Calculates the quotient of Euclidean division of `self` by `rhs`.
///
/// This computes the integer `q` such that `self = q * rhs + r`, with
/// `r = self.rem_euclid(rhs)` and `0 <= r < abs(rhs)`.
///
/// In other words, the result is `self / rhs` rounded to the integer `q`
/// such that `self >= q * rhs`.
/// If `self > 0`, this is equal to rounding towards zero (the default in Rust);
/// if `self < 0`, this is equal to rounding away from zero (towards +/- infinity).
/// If `rhs > 0`, this is equal to rounding towards -infinity;
/// if `rhs < 0`, this is equal to rounding towards +infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero or if `self` is [`Self::MIN`]
/// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
///
/// # Examples
///
/// ```
#[doc = "let a: isize = 7; // or any other integer type"]
/// let b = 4;
///
/// assert_eq!(a.div_euclid(b), 1); // 7 >= 4 * 1
/// assert_eq!(a.div_euclid(-b), -1); // 7 >= -4 * -1
/// assert_eq!((-a).div_euclid(b), -2); // -7 >= 4 * -2
/// assert_eq!((-a).div_euclid(-b), 2); // -7 >= -4 * 2
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_euclid(self, rhs: Self) -> Self {
let q = self / rhs;
if self % rhs < 0 { return if rhs > 0 { q - 1 } else { q + 1 } }
q
}
/// Calculates the least nonnegative remainder of `self` when
/// divided by `rhs`.
///
/// This is done as if by the Euclidean division algorithm -- given
/// `r = self.rem_euclid(rhs)`, the result satisfies
/// `self = rhs * self.div_euclid(rhs) + r` and `0 <= r < abs(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero or if `self` is [`Self::MIN`] and
/// `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
///
/// # Examples
///
/// ```
#[doc = "let a: isize = 7; // or any other integer type"]
/// let b = 4;
///
/// assert_eq!(a.rem_euclid(b), 3);
/// assert_eq!((-a).rem_euclid(b), 1);
/// assert_eq!(a.rem_euclid(-b), 3);
/// assert_eq!((-a).rem_euclid(-b), 1);
/// ```
///
/// This will panic:
/// ```should_panic
#[doc = "let _ = isize::MIN.rem_euclid(-1);"]
/// ```
#[doc(alias = "modulo", alias = "mod")]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn rem_euclid(self, rhs: Self) -> Self {
let r = self % rhs;
if r < 0 { r.wrapping_add(rhs.wrapping_abs()) } else { r }
}
/// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero or if `self` is [`Self::MIN`]
/// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "let a: isize = 8;"]
/// let b = 3;
///
/// assert_eq!(a.div_floor(b), 2);
/// assert_eq!(a.div_floor(-b), -3);
/// assert_eq!((-a).div_floor(b), -3);
/// assert_eq!((-a).div_floor(-b), 2);
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_floor(self, rhs: Self) -> Self {
let d = self / rhs;
let r = self % rhs;
let correction = (self ^ rhs) >> (Self::BITS - 1);
if r != 0 { d + correction } else { d }
}
/// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero or if `self` is [`Self::MIN`]
/// and `rhs` is -1. This behavior is not affected by the `overflow-checks` flag.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "let a: isize = 8;"]
/// let b = 3;
///
/// assert_eq!(a.div_ceil(b), 3);
/// assert_eq!(a.div_ceil(-b), -2);
/// assert_eq!((-a).div_ceil(b), -2);
/// assert_eq!((-a).div_ceil(-b), 3);
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_ceil(self, rhs: Self) -> Self {
let d = self / rhs;
let r = self % rhs;
let correction = 1 + ((self ^ rhs) >> (Self::BITS - 1));
if r != 0 { d + correction } else { d }
}
/// If `rhs` is positive, calculates the smallest value greater than or
/// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
/// calculates the largest value less than or equal to `self` that is a
/// multiple of `rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// On overflow, this function will panic if overflow checks are enabled (default in debug
/// mode) and wrap if overflow checks are disabled (default in release mode).
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "assert_eq!(16_isize.next_multiple_of(8), 16);"]
#[doc = "assert_eq!(23_isize.next_multiple_of(8), 24);"]
#[doc = "assert_eq!(16_isize.next_multiple_of(-8), 16);"]
#[doc = "assert_eq!(23_isize.next_multiple_of(-8), 16);"]
#[doc = "assert_eq!((-16_isize).next_multiple_of(8), -16);"]
#[doc = "assert_eq!((-23_isize).next_multiple_of(8), -16);"]
#[doc = "assert_eq!((-16_isize).next_multiple_of(-8), -16);"]
#[doc = "assert_eq!((-23_isize).next_multiple_of(-8), -24);"]
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_multiple_of(self, rhs: Self) -> Self {
if rhs == -1 { return self; }
let r = self % rhs;
let m =
if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) { r + rhs } else { r };
if m == 0 { self } else { self + (rhs - m) }
}
/// If `rhs` is positive, calculates the smallest value greater than or
/// equal to `self` that is a multiple of `rhs`. If `rhs` is negative,
/// calculates the largest value less than or equal to `self` that is a
/// multiple of `rhs`. Returns `None` if `rhs` is zero or the operation
/// would result in overflow.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "assert_eq!(16_isize.checked_next_multiple_of(8), Some(16));"]
#[doc = "assert_eq!(23_isize.checked_next_multiple_of(8), Some(24));"]
#[doc = "assert_eq!(16_isize.checked_next_multiple_of(-8), Some(16));"]
#[doc = "assert_eq!(23_isize.checked_next_multiple_of(-8), Some(16));"]
#[doc = "assert_eq!((-16_isize).checked_next_multiple_of(8), Some(-16));"]
#[doc = "assert_eq!((-23_isize).checked_next_multiple_of(8), Some(-16));"]
#[doc = "assert_eq!((-16_isize).checked_next_multiple_of(-8), Some(-16));"]
#[doc = "assert_eq!((-23_isize).checked_next_multiple_of(-8), Some(-24));"]
#[doc = "assert_eq!(1_isize.checked_next_multiple_of(0), None);"]
#[doc = "assert_eq!(isize::MAX.checked_next_multiple_of(2), None);"]
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
if rhs == -1 { return Some(self); }
let r =
match self.checked_rem(rhs) { Some(x) => x, None => return None, };
let m =
if (r > 0 && rhs < 0) || (r < 0 && rhs > 0) { r + rhs } else { r };
if m == 0 { Some(self) } else { self.checked_add(rhs - m) }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// This method might not be optimized owing to implementation details;
/// [`ilog2`][Self::ilog2] can produce results more efficiently for base 2,
/// and [`ilog10`](Self::ilog10) can produce results more efficiently for base 10.
///
/// # Panics
///
/// This function will panic if `self` is less than or equal to zero,
/// or if `base` is less than 2.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5isize.ilog(5), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog(self, base: Self) -> u32 {
if !(base >= 2) {
{
crate::panicking::panic_fmt(format_args!("base of integer logarithm must be at least 2"));
}
};
if let Some(log) = self.checked_ilog(base) {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the base 2 logarithm of the number, rounded down.
///
/// # Panics
///
/// This function will panic if `self` is less than or equal to zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2isize.ilog2(), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog2(self) -> u32 {
if let Some(log) = self.checked_ilog2() {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// # Panics
///
/// This function will panic if `self` is less than or equal to zero.
///
/// # Example
///
/// ```
#[doc = "assert_eq!(10isize.ilog10(), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog10(self) -> u32 {
if let Some(log) = self.checked_ilog10() {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// Returns `None` if the number is negative or zero, or if the base is not at least 2.
///
/// This method might not be optimized owing to implementation details;
/// `checked_ilog2` can produce results more efficiently for base 2, and
/// `checked_ilog10` can produce results more efficiently for base 10.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5isize.checked_ilog(5), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog(self, base: Self) -> Option<u32> {
if self <= 0 || base <= 1 {
None
} else { (self as usize).checked_ilog(base as usize) }
}
/// Returns the base 2 logarithm of the number, rounded down.
///
/// Returns `None` if the number is negative or zero.
///
/// Note that for non-negative numbers, this is equivalent to
/// [`highest_one`](Self::highest_one).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2isize.checked_ilog2(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog2(self) -> Option<u32> {
if self <= 0 {
None
} else {
let log =
(Self::BITS - 1) -
unsafe { intrinsics::ctlz_nonzero(self) as u32 };
Some(log)
}
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// Returns `None` if the number is negative or zero.
///
/// # Example
///
/// ```
#[doc = "assert_eq!(10isize.checked_ilog10(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog10(self) -> Option<u32> {
imp::int_log10::i64(self as i64)
}
/// Computes the absolute value of `self`.
///
/// # Overflow behavior
///
/// The absolute value of
#[doc = "`isize::MIN`"]
/// cannot be represented as an
#[doc = "`isize`,"]
/// and attempting to calculate it will cause an overflow. This means
/// that code in debug mode will trigger a panic on this case and
/// optimized code will return
#[doc = "`isize::MIN`"]
/// without a panic. If you do not want this behavior, consider
/// using [`unsigned_abs`](Self::unsigned_abs) instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10isize.abs(), 10);"]
#[doc = "assert_eq!((-10isize).abs(), 10);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[allow(unused_attributes)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn abs(self) -> Self {
if self.is_negative() { -self } else { self }
}
/// Computes the absolute difference between `self` and `other`.
///
/// This function always returns the correct answer without overflow or
/// panics by returning an unsigned integer.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100isize.abs_diff(80), 20usize);"]
#[doc = "assert_eq!(100isize.abs_diff(110), 10usize);"]
#[doc = "assert_eq!((-100isize).abs_diff(80), 180usize);"]
#[doc = "assert_eq!((-100isize).abs_diff(-120), 20usize);"]
#[doc = "assert_eq!(isize::MIN.abs_diff(isize::MAX), usize::MAX);"]
/// ```
#[stable(feature = "int_abs_diff", since = "1.60.0")]
#[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn abs_diff(self, other: Self) -> usize {
if self < other {
(other as usize).wrapping_sub(self as usize)
} else { (self as usize).wrapping_sub(other as usize) }
}
/// Returns a number representing sign of `self`.
///
/// - `0` if the number is zero
/// - `1` if the number is positive
/// - `-1` if the number is negative
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10isize.signum(), 1);"]
#[doc = "assert_eq!(0isize.signum(), 0);"]
#[doc = "assert_eq!((-10isize).signum(), -1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_sign", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn signum(self) -> Self {
crate::intrinsics::three_way_compare(self, 0) as Self
}
/// Returns `true` if `self` is positive and `false` if the number is zero or
/// negative.
///
/// # Examples
///
/// ```
#[doc = "assert!(10isize.is_positive());"]
#[doc = "assert!(!(-10isize).is_positive());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[inline(always)]
pub const fn is_positive(self) -> bool { self > 0 }
/// Returns `true` if `self` is negative and `false` if the number is zero or
/// positive.
///
/// # Examples
///
/// ```
#[doc = "assert!((-10isize).is_negative());"]
#[doc = "assert!(!10isize.is_negative());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[inline(always)]
pub const fn is_negative(self) -> bool { self < 0 }
/// Returns the memory representation of this integer as a byte array in
/// big-endian (network) byte order.
///
#[doc =
"
**Note**: This function returns an array of length 2, 4 or 8 bytes
depending on the target pointer size.
"]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234567890123456isize.to_be_bytes();"]
#[doc =
"assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
self.to_be().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// little-endian byte order.
///
#[doc =
"
**Note**: This function returns an array of length 2, 4 or 8 bytes
depending on the target pointer size.
"]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234567890123456isize.to_le_bytes();"]
#[doc =
"assert_eq!(bytes, [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
self.to_le().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code
/// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
/// instead.
///
#[doc =
"
**Note**: This function returns an array of length 2, 4 or 8 bytes
depending on the target pointer size.
"]
///
/// [`to_be_bytes`]: Self::to_be_bytes
/// [`to_le_bytes`]: Self::to_le_bytes
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234567890123456isize.to_ne_bytes();"]
/// assert_eq!(
/// bytes,
/// if cfg!(target_endian = "big") {
#[doc = " [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]"]
/// } else {
#[doc = " [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]"]
/// }
/// );
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
unsafe { mem::transmute(self) }
}
/// Creates an integer value from its representation as a byte array in
/// big endian.
///
#[doc =
"
**Note**: This function takes an array of length 2, 4 or 8 bytes
depending on the target pointer size.
"]
///
/// # Examples
///
/// ```
#[doc =
"let value = isize::from_be_bytes([0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]);"]
#[doc = "assert_eq!(value, 0x1234567890123456);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_be_isize(input: &mut &[u8]) -> isize {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<isize>());"]
/// *input = rest;
#[doc = " isize::from_be_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_be(Self::from_ne_bytes(bytes))
}
/// Creates an integer value from its representation as a byte array in
/// little endian.
///
#[doc =
"
**Note**: This function takes an array of length 2, 4 or 8 bytes
depending on the target pointer size.
"]
///
/// # Examples
///
/// ```
#[doc =
"let value = isize::from_le_bytes([0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);"]
#[doc = "assert_eq!(value, 0x1234567890123456);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_le_isize(input: &mut &[u8]) -> isize {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<isize>());"]
/// *input = rest;
#[doc = " isize::from_le_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_le(Self::from_ne_bytes(bytes))
}
/// Creates an integer value from its memory representation as a byte
/// array in native endianness.
///
/// As the target platform's native endianness is used, portable code
/// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
/// appropriate instead.
///
/// [`from_be_bytes`]: Self::from_be_bytes
/// [`from_le_bytes`]: Self::from_le_bytes
///
#[doc =
"
**Note**: This function takes an array of length 2, 4 or 8 bytes
depending on the target pointer size.
"]
///
/// # Examples
///
/// ```
#[doc = "let value = isize::from_ne_bytes(if cfg!(target_endian = \"big\") {"]
#[doc = " [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]"]
/// } else {
#[doc = " [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]"]
/// });
#[doc = "assert_eq!(value, 0x1234567890123456);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_ne_isize(input: &mut &[u8]) -> isize {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<isize>());"]
/// *input = rest;
#[doc = " isize::from_ne_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use]
#[inline]
pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
unsafe { mem::transmute(bytes) }
}
/// New code should prefer to use
#[doc = "[`isize::MIN`] instead."]
///
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MIN` associated constant on this type")]
#[rustc_diagnostic_item = "isize_legacy_fn_min_value"]
pub const fn min_value() -> Self { Self::MIN }
/// New code should prefer to use
#[doc = "[`isize::MAX`] instead."]
///
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MAX` associated constant on this type")]
#[rustc_diagnostic_item = "isize_legacy_fn_max_value"]
pub const fn max_value() -> Self { Self::MAX }
/// Clamps this number to a symmetric range centred around zero.
///
/// The method clamps the number's magnitude (absolute value) to be at most `limit`.
///
/// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
/// explicit about the intent.
///
/// # Examples
///
/// ```
/// #![feature(clamp_magnitude)]
#[doc = "assert_eq!(120isize.clamp_magnitude(100), 100);"]
#[doc = "assert_eq!(-120isize.clamp_magnitude(100), -100);"]
#[doc = "assert_eq!(80isize.clamp_magnitude(100), 80);"]
#[doc = "assert_eq!(-80isize.clamp_magnitude(100), -80);"]
/// ```
#[must_use =
"this returns the clamped value and does not modify the original"]
#[unstable(feature = "clamp_magnitude", issue = "148519")]
#[inline]
pub fn clamp_magnitude(self, limit: usize) -> Self {
if let Ok(limit) = core::convert::TryInto::<isize>::try_into(limit) {
self.clamp(-limit, limit)
} else { self }
}
/// Truncate an integer to an integer of the same size or smaller, preserving the least
/// significant bits.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i8, 120isize.truncate());"]
#[doc = "assert_eq!(-120i8, (-120isize).truncate());"]
/// assert_eq!(120i8, 376i32.truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
/// instead of truncating.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i8, 120isize.saturating_truncate());"]
#[doc = "assert_eq!(-120i8, (-120isize).saturating_truncate());"]
/// assert_eq!(127i8, 376i32.saturating_truncate());
/// assert_eq!(-128i8, (-1000i32).saturating_truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn saturating_truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_saturating_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
/// is outside the bounds of the smaller type.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(Some(120i8), 120isize.checked_truncate());"]
#[doc = "assert_eq!(Some(-120i8), (-120isize).checked_truncate());"]
/// assert_eq!(None, 376i32.checked_truncate::<i8>());
/// assert_eq!(None, (-1000i32).checked_truncate::<i8>());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn checked_truncate<Target>(self) -> Option<Target> where
Self: [const] traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_checked_truncate(self)
}
/// Widen to an integer of the same size or larger, preserving its value.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i128, 120i8.widen());"]
#[doc = "assert_eq!(-120i128, (-120i8).widen());"]
/// ```
#[must_use =
"this returns the widened value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn widen<Target>(self) -> Target where Self: [const]
traits::WidenTarget<Target> {
traits::WidenTarget::internal_widen(self)
}
/// Converts `self` to the target integer type, saturating at the numeric
/// bounds instead of overflowing.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(i8::MAX, isize::MAX.saturating_cast());"]
#[doc = "assert_eq!(i8::MIN, isize::MIN.saturating_cast());"]
#[doc = "assert_eq!(42u8, 42isize.saturating_cast());"]
#[doc = "assert_eq!(0u8, (-42isize).saturating_cast());"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn saturating_cast<T: [const] BoundedCastFromInt<Self>>(self) -> T {
T::saturating_cast_from(self)
}
/// Converts `self` to the target integer type, wrapping around at the
/// boundary of the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(isize::MAX as i8, isize::MAX.wrapping_cast());"]
#[doc = "assert_eq!(isize::MIN as i8, isize::MIN.wrapping_cast());"]
#[doc = "assert_eq!(42u8, 42isize.wrapping_cast());"]
#[doc = "assert_eq!(u8::MAX - 41, (-42isize).wrapping_cast());"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn wrapping_cast<T: [const] BoundedCastFromInt<Self>>(self) -> T {
T::wrapping_cast_from(self)
}
/// Converts `self` to the target integer type, returning `None` if the value
/// is not representable by the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(Some(42u8), 42isize.checked_cast());"]
#[doc = "assert_eq!((-42isize).checked_cast::<u8>(), None);"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn checked_cast<T: [const] CheckedCastFromInt<Self>>(self)
-> Option<T> {
T::checked_cast_from(self)
}
/// Converts `self` to the target integer type, panicking if the value
/// is not representable by the target type.
///
/// # Panics
///
/// This function will panic if the value is not representable by the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(42u8, 42isize.strict_cast());"]
/// ```
///
/// The following will panic:
///
/// ```should_panic
/// #![feature(integer_casts)]
#[doc = "let _ = (-42isize).strict_cast::<u8>();"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
#[track_caller]
pub const fn strict_cast<T: [const] CheckedCastFromInt<Self>>(self) -> T {
T::strict_cast_from(self)
}
/// Converts `self` to the target integer type, assuming the value is
/// representable by the target type.
///
/// # Safety
///
/// This results in undefined behavior if the integer value of `self` is bigger than `T::MAX`,
/// or smaller than `T::MIN`, where `T` is the target type.
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const unsafe fn unchecked_cast<T: [const] CheckedCastFromInt<Self>>(self)
-> T {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(in_bounds: bool) {
if !in_bounds {
let msg =
"unsafe precondition(s) violated: isize::unchecked_cast must fit in the target type\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check({
let cast_val = self.checked_cast::<T>();
let ret = cast_val.is_some();
core::mem::forget(cast_val);
ret
});
}
};
unsafe { T::unchecked_cast_from(self) }
}int_impl! {
557Self = isize,
558 ActualT = i64,
559 UnsignedT = usize,
560 BITS = 64,
561 BITS_MINUS_ONE = 63,
562 Min = -9223372036854775808,
563 Max = 9223372036854775807,
564 rot = 12,
565 rot_op = "0xaa00000000006e1",
566 rot_result = "0x6e10aa",
567 swap_op = "0x1234567890123456",
568 swapped = "0x5634129078563412",
569 reversed = "0x6a2c48091e6a2c48",
570 le_bytes = "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
571 be_bytes = "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
572 to_xe_bytes_doc = usize_isize_to_xe_bytes_doc!(),
573 from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(),
574 bound_condition = " on 64-bit targets",
575 }576/// Calculates the midpoint (average) between `self` and `rhs`.
///
/// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
/// sufficiently-large signed integral type. This implies that the result is
/// always rounded towards zero and that no overflow will ever occur.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0isize.midpoint(4), 2);"]
#[doc = "assert_eq!((-1isize).midpoint(2), 0);"]
#[doc = "assert_eq!((-7isize).midpoint(0), -3);"]
#[doc = "assert_eq!(0isize.midpoint(-7), -3);"]
#[doc = "assert_eq!(0isize.midpoint(7), 3);"]
/// ```
#[stable(feature = "num_midpoint_signed", since = "1.87.0")]
#[rustc_const_stable(feature = "num_midpoint_signed", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[doc(alias = "average_floor")]
#[doc(alias = "average_ceil")]
#[doc(alias = "average")]
#[inline]
pub const fn midpoint(self, rhs: Self) -> Self {
let t = ((self ^ rhs) >> 1) + (self & rhs);
t + (if t < 0 { 1 } else { 0 } & (self ^ rhs))
}midpoint_impl! { isize, signed }577}
578579/// If the bit selected by this mask is set, ascii is lower case.
580const ASCII_CASE_MASK: u8 = 0b0010_0000;
581582impl u8 {
583/// The smallest value that can be represented by this integer type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(u8::MIN, 0);"]
/// ```
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MIN: Self = 0;
/// The largest value that can be represented by this integer type
#[doc = "(2<sup>8</sup> − 1)."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(u8::MAX, 255);"]
/// ```
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MAX: Self = !0;
/// The size of this integer type in bits.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(u8::BITS, 8);"]
/// ```
#[stable(feature = "int_bits_const", since = "1.53.0")]
pub const BITS: u32 = Self::MAX.count_ones();
/// Returns the number of ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 0b01001100u8;"]
/// assert_eq!(n.count_ones(), 3);
///
#[doc = "let max = u8::MAX;"]
#[doc = "assert_eq!(max.count_ones(), 8);"]
///
#[doc = "let zero = 0u8;"]
/// assert_eq!(zero.count_ones(), 0);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[doc(alias = "popcount")]
#[doc(alias = "popcnt")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn count_ones(self) -> u32 { return intrinsics::ctpop(self); }
/// Returns the number of zeros in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let zero = 0u8;"]
#[doc = "assert_eq!(zero.count_zeros(), 8);"]
///
#[doc = "let max = u8::MAX;"]
/// assert_eq!(max.count_zeros(), 0);
/// ```
///
/// This is heavily dependent on the width of the type, and thus
/// might give surprising results depending on type inference:
/// ```
/// # fn foo(_: u8) {}
/// # fn bar(_: u16) {}
/// let lucky = 7;
/// foo(lucky);
/// assert_eq!(lucky.count_zeros(), 5);
/// assert_eq!(lucky.count_ones(), 3);
///
/// let lucky = 7;
/// bar(lucky);
/// assert_eq!(lucky.count_zeros(), 13);
/// assert_eq!(lucky.count_ones(), 3);
/// ```
/// You might want to use [`Self::count_ones`] instead, or emphasize
/// the type you're using in the call rather than method syntax:
/// ```
/// let small = 1;
#[doc = "assert_eq!(u8::count_zeros(small), 7);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn count_zeros(self) -> u32 { (!self).count_ones() }
/// Returns the number of leading zeros in the binary representation of `self`.
///
/// Depending on what you're doing with the value, you might also be interested in the
/// [`ilog2`] function which returns a consistent number, even if the type widens.
///
/// # Examples
///
/// ```
#[doc = "let n = u8::MAX >> 2;"]
/// assert_eq!(n.leading_zeros(), 2);
///
#[doc = "let zero = 0u8;"]
#[doc = "assert_eq!(zero.leading_zeros(), 8);"]
///
#[doc = "let max = u8::MAX;"]
/// assert_eq!(max.leading_zeros(), 0);
/// ```
#[doc = "[`ilog2`]: u8::ilog2"]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn leading_zeros(self) -> u32 {
return intrinsics::ctlz(self as u8);
}
/// Returns the number of trailing zeros in the binary representation
/// of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 0b0101000u8;"]
/// assert_eq!(n.trailing_zeros(), 3);
///
#[doc = "let zero = 0u8;"]
#[doc = "assert_eq!(zero.trailing_zeros(), 8);"]
///
#[doc = "let max = u8::MAX;"]
#[doc = "assert_eq!(max.trailing_zeros(), 0);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn trailing_zeros(self) -> u32 { return intrinsics::cttz(self); }
/// Returns the number of leading ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = !(u8::MAX >> 2);"]
/// assert_eq!(n.leading_ones(), 2);
///
#[doc = "let zero = 0u8;"]
/// assert_eq!(zero.leading_ones(), 0);
///
#[doc = "let max = u8::MAX;"]
#[doc = "assert_eq!(max.leading_ones(), 8);"]
/// ```
#[stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn leading_ones(self) -> u32 { (!self).leading_zeros() }
/// Returns the number of trailing ones in the binary representation
/// of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 0b1010111u8;"]
/// assert_eq!(n.trailing_ones(), 3);
///
#[doc = "let zero = 0u8;"]
/// assert_eq!(zero.trailing_ones(), 0);
///
#[doc = "let max = u8::MAX;"]
#[doc = "assert_eq!(max.trailing_ones(), 8);"]
/// ```
#[stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn trailing_ones(self) -> u32 { (!self).trailing_zeros() }
/// Returns the minimum number of bits required to represent `self`.
///
/// This method returns zero if `self` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0_u8.bit_width(), 0);"]
#[doc = "assert_eq!(0b111_u8.bit_width(), 3);"]
#[doc = "assert_eq!(0b1110_u8.bit_width(), 4);"]
#[doc = "assert_eq!(u8::MAX.bit_width(), 8);"]
/// ```
#[stable(feature = "uint_bit_width", since = "1.97.0")]
#[rustc_const_stable(feature = "uint_bit_width", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn bit_width(self) -> u32 { Self::BITS - self.leading_zeros() }
/// Returns `self` with only the most significant bit set, or `0` if
/// the input is `0`.
///
/// # Examples
///
/// ```
#[doc = "let n: u8 = 0b_01100100;"]
///
/// assert_eq!(n.isolate_highest_one(), 0b_01000000);
#[doc = "assert_eq!(0_u8.isolate_highest_one(), 0);"]
/// ```
#[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn isolate_highest_one(self) -> Self {
self &
(((1 as u8) << (<u8>::BITS - 1)).wrapping_shr(self.leading_zeros()))
}
/// Returns `self` with only the least significant bit set, or `0` if
/// the input is `0`.
///
/// # Examples
///
/// ```
#[doc = "let n: u8 = 0b_01100100;"]
///
/// assert_eq!(n.isolate_lowest_one(), 0b_00000100);
#[doc = "assert_eq!(0_u8.isolate_lowest_one(), 0);"]
/// ```
#[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn isolate_lowest_one(self) -> Self { self & self.wrapping_neg() }
/// Returns the index of the highest bit set to one in `self`, or `None`
/// if `self` is `0`.
///
/// Note that this is equivalent to [`checked_ilog2`](Self::checked_ilog2).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0b0_u8.highest_one(), None);"]
#[doc = "assert_eq!(0b1_u8.highest_one(), Some(0));"]
#[doc = "assert_eq!(0b1_0000_u8.highest_one(), Some(4));"]
#[doc = "assert_eq!(0b1_1111_u8.highest_one(), Some(4));"]
/// ```
#[stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn highest_one(self) -> Option<u32> {
match NonZero::new(self) {
Some(v) => Some(v.highest_one()),
None => None,
}
}
/// Returns the index of the lowest bit set to one in `self`, or `None`
/// if `self` is `0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0b0_u8.lowest_one(), None);"]
#[doc = "assert_eq!(0b1_u8.lowest_one(), Some(0));"]
#[doc = "assert_eq!(0b1_0000_u8.lowest_one(), Some(4));"]
#[doc = "assert_eq!(0b1_1111_u8.lowest_one(), Some(0));"]
/// ```
#[stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn lowest_one(self) -> Option<u32> {
match NonZero::new(self) {
Some(v) => Some(v.lowest_one()),
None => None,
}
}
/// Returns the bit pattern of `self` reinterpreted as a signed integer of the same size.
///
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
/// the same.
///
/// # Examples
///
/// ```
#[doc = "let n = u8::MAX;"]
///
#[doc = "assert_eq!(n.cast_signed(), -1i8);"]
/// ```
#[stable(feature = "integer_sign_cast", since = "1.87.0")]
#[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_signed(self) -> i8 { self as i8 }
/// Saturating conversion of `self` to a signed integer of the same size.
///
/// The signed integer's maximum value is returned if `self` is larger
/// than the maximum positive value representable by the signed integer.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`checked_cast_signed`](Self::checked_cast_signed),
/// or [`strict_cast_signed`](Self::strict_cast_signed).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = u8::MAX;"]
///
#[doc = "assert_eq!(n.saturating_cast_signed(), i8::MAX);"]
#[doc = "assert_eq!(64u8.saturating_cast_signed(), 64i8);"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_cast_signed(self) -> i8 {
if self <= <i8>::MAX.cast_unsigned() {
self.cast_signed()
} else { <i8>::MAX }
}
/// Checked conversion of `self` to a signed integer of the same size,
/// returning `None` if `self` is larger than the signed integer's
/// maximum value.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`saturating_cast_signed`](Self::saturating_cast_signed),
/// or [`strict_cast_signed`](Self::strict_cast_signed).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = u8::MAX;"]
///
#[doc = "assert_eq!(n.checked_cast_signed(), None);"]
#[doc = "assert_eq!(64u8.checked_cast_signed(), Some(64i8));"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn checked_cast_signed(self) -> Option<i8> {
if self <= <i8>::MAX.cast_unsigned() {
Some(self.cast_signed())
} else { None }
}
/// Strict conversion of `self` to a signed integer of the same size,
/// which panics if `self` is larger than the signed integer's maximum
/// value.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`checked_cast_signed`](Self::checked_cast_signed),
/// or [`saturating_cast_signed`](Self::saturating_cast_signed).
///
/// # Examples
///
/// ```should_panic
/// #![feature(integer_cast_extras)]
#[doc = "let _ = u8::MAX.strict_cast_signed();"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_cast_signed(self) -> i8 {
match self.checked_cast_signed() {
Some(n) => n,
None => imp::overflow_panic::cast_integer(),
}
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `<<` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x82u8;"]
#[doc = "let m = 0xa;"]
///
#[doc = "assert_eq!(n.rotate_left(2), m);"]
#[doc = "assert_eq!(n.rotate_left(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
pub const fn rotate_left(self, n: u32) -> Self {
return intrinsics::rotate_left(self, n);
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `>>` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0xau8;"]
#[doc = "let m = 0x82;"]
///
#[doc = "assert_eq!(n.rotate_right(2), m);"]
#[doc = "assert_eq!(n.rotate_right(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
pub const fn rotate_right(self, n: u32) -> Self {
return intrinsics::rotate_right(self, n);
}
/// Performs a left funnel shift (concatenates `self` with `rhs`, with `self`
/// making up the most significant half, then shifts the combined value left
/// by `n`, and most significant half is extracted to produce the result).
///
/// Please note this isn't the same operation as the `<<` shifting operator or
/// [`rotate_left`](Self::rotate_left), although `a.funnel_shl(a, n)` is *equivalent*
/// to `a.rotate_left(n)`.
///
/// # Panics
///
/// If `n` is greater than or equal to the number of bits in `self`
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(funnel_shifts)]
#[doc = "let a = 0x82u8;"]
#[doc = "let b = 0x36u8;"]
#[doc = "let m = 0x8;"]
///
#[doc = "assert_eq!(a.funnel_shl(b, 2), m);"]
/// ```
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn funnel_shl(self, rhs: Self, n: u32) -> Self {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift left with overflow"));
}
};
unsafe { self.unchecked_funnel_shl(rhs, n) }
}
/// Performs a right funnel shift (concatenates `self` and `rhs`, with `self`
/// making up the most significant half, then shifts the combined value right
/// by `n`, and least significant half is extracted to produce the result).
///
/// Please note this isn't the same operation as the `>>` shifting operator or
/// [`rotate_right`](Self::rotate_right), although `a.funnel_shr(a, n)` is *equivalent*
/// to `a.rotate_right(n)`.
///
/// # Panics
///
/// If `n` is greater than or equal to the number of bits in `self`
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(funnel_shifts)]
#[doc = "let a = 0x82u8;"]
#[doc = "let b = 0x36u8;"]
#[doc = "let m = 0x8d;"]
///
#[doc = "assert_eq!(a.funnel_shr(b, 2), m);"]
/// ```
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn funnel_shr(self, rhs: Self, n: u32) -> Self {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift right with overflow"));
}
};
unsafe { self.unchecked_funnel_shr(rhs, n) }
}
/// Unchecked funnel shift left.
///
/// # Safety
///
/// This results in undefined behavior if `n` is greater than or equal to
#[doc = "`u8::BITS`,"]
/// i.e. when [`funnel_shl`](Self::funnel_shl) would panic.
///
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_funnel_shl(self, low: Self, n: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(n: u32) {
if !(n < <u8>::BITS) {
let msg =
"unsafe precondition(s) violated: u8::unchecked_funnel_shl cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(n); }
};
unsafe { intrinsics::unchecked_funnel_shl(self, low, n) }
}
/// Unchecked funnel shift right.
///
/// # Safety
///
/// This results in undefined behavior if `n` is greater than or equal to
#[doc = "`u8::BITS`,"]
/// i.e. when [`funnel_shr`](Self::funnel_shr) would panic.
///
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_funnel_shr(self, low: Self, n: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(n: u32) {
if !(n < <u8>::BITS) {
let msg =
"unsafe precondition(s) violated: u8::unchecked_funnel_shr cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(n); }
};
unsafe { intrinsics::unchecked_funnel_shr(self, low, n) }
}
/// Performs a carry-less multiplication, returning the lower bits.
///
/// This operation is similar to long multiplication in base 2, except that exclusive or is
/// used instead of addition. The implementation is equivalent to:
///
/// ```no_run
#[doc = "pub fn carryless_mul(lhs: u8, rhs: u8) -> u8{"]
/// let mut retval = 0;
#[doc = " for i in 0..u8::BITS {"]
/// if (rhs >> i) & 1 != 0 {
/// // long multiplication would use +=
/// retval ^= lhs << i;
/// }
/// }
/// retval
/// }
/// ```
///
/// The actual implementation is more efficient, and on some platforms lowers directly to a
/// dedicated instruction.
///
/// # Uses
///
/// Carryless multiplication can be used to turn a bitmask of quote characters into a
/// bit mask of characters surrounded by quotes:
///
/// ```no_run
/// r#"abc xxx "foobar" zzz "a"!"#; // input string
/// 0b0000000010000001000001010; // quote_mask
/// 0b0000000001111110000000100; // quote_mask.carryless_mul(!0) & !quote_mask
/// ```
///
/// Another use is in cryptography, where carryless multiplication allows for efficient
/// implementations of polynomial multiplication in `GF(2)[X]`, the polynomial ring
/// over `GF(2)`.
///
/// # Examples
///
/// ```
/// #![feature(uint_carryless_mul)]
///
#[doc = "let a = 0x12u8;"]
#[doc = "let b = 0x34u8;"]
///
#[doc = "assert_eq!(a.carryless_mul(b), 0x28);"]
/// ```
#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
#[doc(alias = "clmul")]
#[unstable(feature = "uint_carryless_mul", issue = "152080")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn carryless_mul(self, rhs: Self) -> Self {
intrinsics::carryless_mul(self, rhs)
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x12u8;"]
/// let m = n.swap_bytes();
///
#[doc = "assert_eq!(m, 0x12);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn swap_bytes(self) -> Self {
intrinsics::bswap(self as u8) as Self
}
/// Returns an integer with the bit locations specified by `mask` packed
/// contiguously into the least significant bits of the result.
/// ```
/// #![feature(uint_gather_scatter_bits)]
#[doc = "let n: u8 = 0b1011_1100;"]
///
/// assert_eq!(n.extract_bits(0b0010_0100), 0b0000_0011);
/// assert_eq!(n.extract_bits(0xF0), 0b0000_1011);
/// ```
#[doc(alias = "pext")]
#[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn extract_bits(self, mask: Self) -> Self {
imp::int_bits::u8::extract_impl(self as u8, mask as u8) as u8
}
/// Returns an integer with the least significant bits of `self`
/// distributed to the bit locations specified by `mask`.
/// ```
/// #![feature(uint_gather_scatter_bits)]
#[doc = "let n: u8 = 0b1010_1101;"]
///
/// assert_eq!(n.deposit_bits(0b0101_0101), 0b0101_0001);
/// assert_eq!(n.deposit_bits(0xF0), 0b1101_0000);
/// ```
#[doc(alias = "pdep")]
#[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn deposit_bits(self, mask: Self) -> Self {
imp::int_bits::u8::deposit_impl(self as u8, mask as u8) as u8
}
/// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
/// second least-significant bit becomes second most-significant bit, etc.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x12u8;"]
/// let m = n.reverse_bits();
///
#[doc = "assert_eq!(m, 0x48);"]
#[doc = "assert_eq!(0, 0u8.reverse_bits());"]
/// ```
#[stable(feature = "reverse_bits", since = "1.37.0")]
#[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn reverse_bits(self) -> Self {
intrinsics::bitreverse(self as u8) as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au8;"]
///
/// if cfg!(target_endian = "big") {
#[doc = " assert_eq!(u8::from_be(n), n)"]
/// } else {
#[doc = " assert_eq!(u8::from_be(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use]
#[inline(always)]
pub const fn from_be(x: Self) -> Self { x.swap_bytes() }
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au8;"]
///
/// if cfg!(target_endian = "little") {
#[doc = " assert_eq!(u8::from_le(n), n)"]
/// } else {
#[doc = " assert_eq!(u8::from_le(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use]
#[inline(always)]
pub const fn from_le(x: Self) -> Self { x }
/// Converts `self` to big endian from the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au8;"]
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn to_be(self) -> Self { self.swap_bytes() }
/// Converts `self` to little endian from the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au8;"]
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn to_le(self) -> Self { self }
/// Checked integer addition. Computes `self + rhs`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((u8::MAX - 2).checked_add(1), Some(u8::MAX - 1));"]
#[doc = "assert_eq!((u8::MAX - 2).checked_add(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(intrinsics::add_with_overflow(self, rhs).1) {
None
} else { Some(unsafe { intrinsics::unchecked_add(self, rhs) }) }
}
/// Strict integer addition. Computes `self + rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((u8::MAX - 2).strict_add(1), u8::MAX - 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (u8::MAX - 2).strict_add(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_add(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Unchecked integer addition. Computes `self + rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_add(y)` is semantically equivalent to calling
/// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_add`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self + rhs > u8::MAX`,"]
/// i.e. when [`checked_add`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_add`]: u8::checked_add"]
#[doc = "[`wrapping_add`]: u8::wrapping_add"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u8, rhs: u8) {
if !!lhs.overflowing_add(rhs).1 {
let msg =
"unsafe precondition(s) violated: u8::unchecked_add cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_add(self, rhs) }
}
/// Checked addition with a signed integer. Computes `self + rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u8.checked_add_signed(2), Some(3));"]
#[doc = "assert_eq!(1u8.checked_add_signed(-2), None);"]
#[doc = "assert_eq!((u8::MAX - 2).checked_add_signed(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add_signed(self, rhs: i8) -> Option<Self> {
let (a, b) = self.overflowing_add_signed(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict addition with a signed integer. Computes `self + rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u8.strict_add_signed(2), 3);"]
/// ```
///
/// The following panic because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1u8.strict_add_signed(-2);"]
/// ```
///
/// ```should_panic
#[doc = "let _ = (u8::MAX - 2).strict_add_signed(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add_signed(self, rhs: i8) -> Self {
let (a, b) = self.overflowing_add_signed(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Checked integer subtraction. Computes `self - rhs`, returning
/// `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u8.checked_sub(1), Some(0));"]
#[doc = "assert_eq!(0u8.checked_sub(1), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
if self < rhs {
None
} else { Some(unsafe { intrinsics::unchecked_sub(self, rhs) }) }
}
/// Strict integer subtraction. Computes `self - rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u8.strict_sub(1), 0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0u8.strict_sub(1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_sub(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
/// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_sub`].
///
/// If you find yourself writing code like this:
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if foo >= bar {
/// // SAFETY: just checked it will not overflow
/// let diff = unsafe { foo.unchecked_sub(bar) };
/// // ... use diff ...
/// }
/// ```
///
/// Consider changing it to
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if let Some(diff) = foo.checked_sub(bar) {
/// // ... use diff ...
/// }
/// ```
///
/// As that does exactly the same thing -- including telling the optimizer
/// that the subtraction cannot overflow -- but avoids needing `unsafe`.
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self - rhs < u8::MIN`,"]
/// i.e. when [`checked_sub`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_sub`]: u8::checked_sub"]
#[doc = "[`wrapping_sub`]: u8::wrapping_sub"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u8, rhs: u8) {
if !!lhs.overflowing_sub(rhs).1 {
let msg =
"unsafe precondition(s) violated: u8::unchecked_sub cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_sub(self, rhs) }
}
/// Checked subtraction with a signed integer. Computes `self - rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u8.checked_sub_signed(2), None);"]
#[doc = "assert_eq!(1u8.checked_sub_signed(-2), Some(3));"]
#[doc = "assert_eq!((u8::MAX - 2).checked_sub_signed(-4), None);"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub_signed(self, rhs: i8) -> Option<Self> {
let (res, overflow) = self.overflowing_sub_signed(rhs);
if !overflow { Some(res) } else { None }
}
/// Strict subtraction with a signed integer. Computes `self - rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3u8.strict_sub_signed(2), 1);"]
/// ```
///
/// The following panic because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1u8.strict_sub_signed(2);"]
/// ```
///
/// ```should_panic
#[doc = "let _ = (u8::MAX).strict_sub_signed(-1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub_signed(self, rhs: i8) -> Self {
let (a, b) = self.overflowing_sub_signed(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
#[doc =
"Checked integer subtraction. Computes `self - rhs` and checks if the result fits into an [`i8`], returning `None` if overflow occurred."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10u8.checked_signed_diff(2), Some(8));"]
#[doc = "assert_eq!(2u8.checked_signed_diff(10), Some(-8));"]
#[doc = "assert_eq!(u8::MAX.checked_signed_diff(i8::MAX as u8), None);"]
#[doc =
"assert_eq!((i8::MAX as u8).checked_signed_diff(u8::MAX), Some(i8::MIN));"]
#[doc = "assert_eq!((i8::MAX as u8 + 1).checked_signed_diff(0), None);"]
#[doc = "assert_eq!(u8::MAX.checked_signed_diff(u8::MAX), Some(0));"]
/// ```
#[stable(feature = "unsigned_signed_diff", since = "1.91.0")]
#[rustc_const_stable(feature = "unsigned_signed_diff", since = "1.91.0")]
#[inline]
pub const fn checked_signed_diff(self, rhs: Self) -> Option<i8> {
let res = self.wrapping_sub(rhs) as i8;
let overflow = (self >= rhs) == (res < 0);
if !overflow { Some(res) } else { None }
}
/// Checked integer multiplication. Computes `self * rhs`, returning
/// `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u8.checked_mul(1), Some(5));"]
#[doc = "assert_eq!(u8::MAX.checked_mul(2), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer multiplication. Computes `self * rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u8.strict_mul(1), 5);"]
/// ```
///
/// The following panics because of overflow:
///
/// ``` should_panic
#[doc = "let _ = u8::MAX.strict_mul(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_mul(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_mul(rhs);
if b { imp::overflow_panic::mul() } else { a }
}
/// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
/// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_mul`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self * rhs > u8::MAX`,"]
/// i.e. when [`checked_mul`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_mul`]: u8::checked_mul"]
#[doc = "[`wrapping_mul`]: u8::wrapping_mul"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u8, rhs: u8) {
if !!lhs.overflowing_mul(rhs).1 {
let msg =
"unsafe precondition(s) violated: u8::unchecked_mul cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_mul(self, rhs) }
}
/// Checked integer division. Computes `self / rhs`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128u8.checked_div(2), Some(64));"]
#[doc = "assert_eq!(1u8.checked_div(0), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(unsafe { intrinsics::unchecked_div(self, rhs) }) }
}
/// Strict integer division. Computes `self / rhs`.
///
/// Strict division on unsigned types is just normal division. There's no
/// way overflow could ever happen. This function exists so that all
/// operations are accounted for in the strict operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u8.strict_div(10), 10);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1u8).strict_div(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_div(self, rhs: Self) -> Self { self / rhs }
/// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128u8.checked_div_euclid(2), Some(64));"]
#[doc = "assert_eq!(1u8.checked_div_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(self.div_euclid(rhs)) }
}
/// Strict Euclidean division. Computes `self.div_euclid(rhs)`.
///
/// Strict division on unsigned types is just normal division. There's no
/// way overflow could ever happen. This function exists so that all
/// operations are accounted for in the strict operations. Since, for the
/// positive integers, all common definitions of division are equal, this
/// is exactly equal to `self.strict_div(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u8.strict_div_euclid(10), 10);"]
/// ```
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1u8).strict_div_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Checked integer division without remainder. Computes `self / rhs`,
/// returning `None` if `rhs == 0` or if `self % rhs != 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64u8.checked_div_exact(2), Some(32));"]
#[doc = "assert_eq!(64u8.checked_div_exact(32), Some(2));"]
#[doc = "assert_eq!(64u8.checked_div_exact(0), None);"]
#[doc = "assert_eq!(65u8.checked_div_exact(2), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_exact(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else {
unsafe {
if intrinsics::unlikely(intrinsics::unchecked_rem(self, rhs) != 0)
{
None
} else { Some(intrinsics::exact_div(self, rhs)) }
}
}
}
/// Integer division without remainder. Computes `self / rhs`, returning `None` if `self % rhs != 0`.
///
/// # Panics
///
/// This function will panic if `rhs == 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64u8.div_exact(2), Some(32));"]
#[doc = "assert_eq!(64u8.div_exact(32), Some(2));"]
#[doc = "assert_eq!(65u8.div_exact(2), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn div_exact(self, rhs: Self) -> Option<Self> {
if self % rhs != 0 { None } else { Some(self / rhs) }
}
/// Unchecked integer division without remainder. Computes `self / rhs`.
///
/// # Safety
///
/// This results in undefined behavior when `rhs == 0` or `self % rhs != 0`,
/// i.e. when [`checked_div_exact`](Self::checked_div_exact) would return `None`.
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_div_exact(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u8, rhs: u8) {
if !(rhs > 0 && lhs % rhs == 0) {
let msg =
"unsafe precondition(s) violated: u8::unchecked_div_exact divide by zero or leave a remainder\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::exact_div(self, rhs) }
}
/// Checked integer remainder. Computes `self % rhs`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u8.checked_rem(2), Some(1));"]
#[doc = "assert_eq!(5u8.checked_rem(0), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(unsafe { intrinsics::unchecked_rem(self, rhs) }) }
}
/// Strict integer remainder. Computes `self % rhs`.
///
/// Strict remainder calculation on unsigned types is just the regular
/// remainder calculation. There's no way overflow could ever happen.
/// This function exists so that all operations are accounted for in the
/// strict operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u8.strict_rem(10), 0);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5u8.strict_rem(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_rem(self, rhs: Self) -> Self { self % rhs }
/// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u8.checked_rem_euclid(2), Some(1));"]
#[doc = "assert_eq!(5u8.checked_rem_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(self.rem_euclid(rhs)) }
}
/// Strict Euclidean modulo. Computes `self.rem_euclid(rhs)`.
///
/// Strict modulo calculation on unsigned types is just the regular
/// remainder calculation. There's no way overflow could ever happen.
/// This function exists so that all operations are accounted for in the
/// strict operations. Since, for the positive integers, all common
/// definitions of division are equal, this is exactly equal to
/// `self.strict_rem(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u8.strict_rem_euclid(10), 0);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5u8.strict_rem_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Same value as `self | other`, but UB if any bit position is set in both inputs.
///
/// This is a situational micro-optimization for places where you'd rather
/// use addition on some platforms and bitwise or on other platforms, based
/// on exactly which instructions combine better with whatever else you're
/// doing. Note that there's no reason to bother using this for places
/// where it's clear from the operations involved that they can't overlap.
/// For example, if you're combining `u16`s into a `u32` with
/// `((a as u32) << 16) | (b as u32)`, that's fine, as the backend will
/// know those sides of the `|` are disjoint without needing help.
///
/// # Examples
///
/// ```
/// #![feature(disjoint_bitor)]
///
/// // SAFETY: `1` and `4` have no bits in common.
/// unsafe {
#[doc = " assert_eq!(1_u8.unchecked_disjoint_bitor(4), 5);"]
/// }
/// ```
///
/// # Safety
///
/// Requires that `(self & other) == 0`, otherwise it's immediate UB.
///
/// Equivalently, requires that `(self | other) == (self + other)`.
#[unstable(feature = "disjoint_bitor", issue = "135758")]
#[rustc_const_unstable(feature = "disjoint_bitor", issue = "135758")]
#[inline]
pub const unsafe fn unchecked_disjoint_bitor(self, other: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u8, rhs: u8) {
if !((lhs & rhs) == 0) {
let msg =
"unsafe precondition(s) violated: u8::unchecked_disjoint_bitor cannot have overlapping bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, other);
}
};
unsafe { intrinsics::disjoint_bitor(self, other) }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// This method might not be optimized owing to implementation details;
/// [`ilog2`](Self::ilog2) can produce results more efficiently for base 2,
/// and [`ilog10`](Self::ilog10) can produce results more efficiently for base 10.
///
/// # Panics
///
/// This function will panic if `self` is zero, or if `base` is less than 2.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u8.ilog(5), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog(self, base: Self) -> u32 {
if !(base >= 2) {
{
crate::panicking::panic_fmt(format_args!("base of integer logarithm must be at least 2"));
}
};
if let Some(log) = self.checked_ilog(base) {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the base 2 logarithm of the number, rounded down.
///
/// # Panics
///
/// This function will panic if `self` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u8.ilog2(), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog2(self) -> u32 {
if let Some(log) = self.checked_ilog2() {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// # Panics
///
/// This function will panic if `self` is zero.
///
/// # Example
///
/// ```
#[doc = "assert_eq!(10u8.ilog10(), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog10(self) -> u32 {
if let Some(log) = self.checked_ilog10() {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// Returns `None` if the number is zero, or if the base is not at least 2.
///
/// This method might not be optimized owing to implementation details;
/// `checked_ilog2` can produce results more efficiently for base 2, and
/// `checked_ilog10` can produce results more efficiently for base 10.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u8.checked_ilog(5), Some(1));"]
#[doc = "assert_eq!(4u8.checked_ilog(5), Some(0));"]
#[doc = "assert_eq!(5u8.checked_ilog(0), None);"]
#[doc = "assert_eq!(5u8.checked_ilog(1), None);"]
#[doc = "assert_eq!(0u8.checked_ilog(1), None);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog(self, base: Self) -> Option<u32> {
if core::intrinsics::is_val_statically_known(base) {
if base.is_power_of_two() && base > 1 {
let k = base.ilog2();
return Some(match self.checked_ilog2() {
Some(x) => x,
None => return None,
} / k);
}
if base == 10 { return self.checked_ilog10(); }
}
if self <= 0 || base <= 1 {
None
} else if self < base {
Some(0)
} else {
let mut n = 1;
let mut r = base;
if Self::BITS == 128 {
n = self.ilog2() / (base.ilog2() + 1);
r = base.pow(n);
}
while r <= self / base { n += 1; r *= base; }
Some(n)
}
}
/// Returns the base 2 logarithm of the number, rounded down.
///
/// Returns `None` if the number is zero.
///
/// Note that this is equivalent to [`highest_one`](Self::highest_one).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u8.checked_ilog2(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog2(self) -> Option<u32> {
match NonZero::new(self) { Some(x) => Some(x.ilog2()), None => None, }
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// Returns `None` if the number is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10u8.checked_ilog10(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog10(self) -> Option<u32> {
match NonZero::new(self) { Some(x) => Some(x.ilog10()), None => None, }
}
/// Checked negation. Computes `-self`, returning `None` unless `self ==
/// 0`.
///
/// Note that negating any positive integer will overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0u8.checked_neg(), Some(0));"]
#[doc = "assert_eq!(1u8.checked_neg(), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_neg(self) -> Option<Self> {
let (a, b) = self.overflowing_neg();
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict negation. Computes `-self`, panicking unless `self ==
/// 0`.
///
/// Note that negating any positive integer will overflow.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0u8.strict_neg(), 0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1u8.strict_neg();"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_neg(self) -> Self {
let (a, b) = self.overflowing_neg();
if b { imp::overflow_panic::neg() } else { a }
}
/// Checked shift left. Computes `self << rhs`, returning `None`
/// if `rhs` is larger than or equal to the number of bits in `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1u8.checked_shl(4), Some(0x10));"]
#[doc = "assert_eq!(0x10u8.checked_shl(129), None);"]
#[doc = "assert_eq!(0x10u8.checked_shl(7), Some(0));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
if rhs < Self::BITS {
Some(unsafe { self.unchecked_shl(rhs) })
} else { None }
}
/// Strict shift left. Computes `self << rhs`, panicking if `rhs` is larger
/// than or equal to the number of bits in `self`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1u8.strict_shl(4), 0x10);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0x10u8.strict_shl(129);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_shl(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_shl(rhs);
if b { imp::overflow_panic::shl() } else { a }
}
/// Unchecked shift left. Computes `self << rhs`, assuming that
/// `rhs` is less than the number of bits in `self`.
///
/// # Safety
///
/// This results in undefined behavior if `rhs` is larger than
/// or equal to the number of bits in `self`,
/// i.e. when [`checked_shl`] would return `None`.
///
#[doc = "[`checked_shl`]: u8::checked_shl"]
#[stable(feature = "unchecked_shifts", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_shl(self, rhs: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(rhs: u32) {
if !(rhs < <u8>::BITS) {
let msg =
"unsafe precondition(s) violated: u8::unchecked_shl cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(rhs); }
};
unsafe { intrinsics::unchecked_shl(self, rhs) }
}
/// Unbounded shift left. Computes `self << rhs`, without bounding the value of `rhs`.
///
/// If `rhs` is larger or equal to the number of bits in `self`,
/// the entire value is shifted out, and `0` is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1_u8.unbounded_shl(4), 0x10);"]
#[doc = "assert_eq!(0x1_u8.unbounded_shl(129), 0);"]
#[doc = "assert_eq!(0b101_u8.unbounded_shl(0), 0b101);"]
#[doc = "assert_eq!(0b101_u8.unbounded_shl(1), 0b1010);"]
#[doc = "assert_eq!(0b101_u8.unbounded_shl(2), 0b10100);"]
#[doc = "assert_eq!(42_u8.unbounded_shl(8), 0);"]
#[doc = "assert_eq!(42_u8.unbounded_shl(1).unbounded_shl(7), 0);"]
///
#[doc = "let start : u8 = 13;"]
/// let mut running = start;
/// for i in 0..160 {
/// // The unbounded shift left by i is the same as `<< 1` i times
/// assert_eq!(running, start.unbounded_shl(i));
/// // Which is not always the case for a wrapping shift
#[doc = " assert_eq!(running == start.wrapping_shl(i), i < 8);"]
///
/// running <<= 1;
/// }
/// ```
#[stable(feature = "unbounded_shifts", since = "1.87.0")]
#[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unbounded_shl(self, rhs: u32) -> u8 {
if rhs < Self::BITS { unsafe { self.unchecked_shl(rhs) } } else { 0 }
}
/// Exact shift left. Computes `self << rhs` as long as it can be reversed losslessly.
///
/// Returns `None` if any non-zero bits would be shifted out or if `rhs` >=
#[doc = "`u8::BITS`."]
/// Otherwise, returns `Some(self << rhs)`.
///
/// # Examples
///
/// ```
/// #![feature(exact_bitshifts)]
///
#[doc = "assert_eq!(0x1u8.shl_exact(4), Some(0x10));"]
#[doc = "assert_eq!(0x1u8.shl_exact(129), None);"]
/// ```
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn shl_exact(self, rhs: u32) -> Option<u8> {
if rhs <= self.leading_zeros() && rhs < <u8>::BITS {
Some(unsafe { self.unchecked_shl(rhs) })
} else { None }
}
/// Unchecked exact shift left. Computes `self << rhs`, assuming the operation can be
/// losslessly reversed `rhs` cannot be larger than
#[doc = "`u8::BITS`."]
///
/// # Safety
///
/// This results in undefined behavior when `rhs > self.leading_zeros() || rhs >=
#[doc = "u8::BITS`"]
/// i.e. when
#[doc = "[`u8::shl_exact`]"]
/// would return `None`.
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_shl_exact(self, rhs: u32) -> u8 {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(zeros: u32, bits: u32, rhs: u32) {
if !(rhs <= zeros && rhs < bits) {
let msg =
"unsafe precondition(s) violated: u8::unchecked_shl_exact cannot shift out non-zero bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_library_ub() {
precondition_check(self.leading_zeros(), <u8>::BITS, rhs);
}
};
unsafe { self.unchecked_shl(rhs) }
}
/// Checked shift right. Computes `self >> rhs`, returning `None`
/// if `rhs` is larger than or equal to the number of bits in `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10u8.checked_shr(4), Some(0x1));"]
#[doc = "assert_eq!(0x10u8.checked_shr(129), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
if rhs < Self::BITS {
Some(unsafe { self.unchecked_shr(rhs) })
} else { None }
}
/// Strict shift right. Computes `self >> rhs`, panicking if `rhs` is
/// larger than or equal to the number of bits in `self`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10u8.strict_shr(4), 0x1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0x10u8.strict_shr(129);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_shr(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_shr(rhs);
if b { imp::overflow_panic::shr() } else { a }
}
/// Unchecked shift right. Computes `self >> rhs`, assuming that
/// `rhs` is less than the number of bits in `self`.
///
/// # Safety
///
/// This results in undefined behavior if `rhs` is larger than
/// or equal to the number of bits in `self`,
/// i.e. when [`checked_shr`] would return `None`.
///
#[doc = "[`checked_shr`]: u8::checked_shr"]
#[stable(feature = "unchecked_shifts", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_shr(self, rhs: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(rhs: u32) {
if !(rhs < <u8>::BITS) {
let msg =
"unsafe precondition(s) violated: u8::unchecked_shr cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(rhs); }
};
unsafe { intrinsics::unchecked_shr(self, rhs) }
}
/// Unbounded shift right. Computes `self >> rhs`, without bounding the value of `rhs`.
///
/// If `rhs` is larger or equal to the number of bits in `self`,
/// the entire value is shifted out, and `0` is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10_u8.unbounded_shr(4), 0x1);"]
#[doc = "assert_eq!(0x10_u8.unbounded_shr(129), 0);"]
#[doc = "assert_eq!(0b1010_u8.unbounded_shr(0), 0b1010);"]
#[doc = "assert_eq!(0b1010_u8.unbounded_shr(1), 0b101);"]
#[doc = "assert_eq!(0b1010_u8.unbounded_shr(2), 0b10);"]
#[doc = "assert_eq!(42_u8.unbounded_shr(8), 0);"]
#[doc = "assert_eq!(42_u8.unbounded_shr(1).unbounded_shr(7), 0);"]
///
#[doc = "let start = u8::rotate_right(13, 4);"]
/// let mut running = start;
/// for i in 0..160 {
/// // The unbounded shift right by i is the same as `>> 1` i times
/// assert_eq!(running, start.unbounded_shr(i));
/// // Which is not always the case for a wrapping shift
#[doc = " assert_eq!(running == start.wrapping_shr(i), i < 8);"]
///
/// running >>= 1;
/// }
/// ```
#[stable(feature = "unbounded_shifts", since = "1.87.0")]
#[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unbounded_shr(self, rhs: u32) -> u8 {
if rhs < Self::BITS { unsafe { self.unchecked_shr(rhs) } } else { 0 }
}
/// Exact shift right. Computes `self >> rhs` as long as it can be reversed losslessly.
///
/// Returns `None` if any non-zero bits would be shifted out or if `rhs` >=
#[doc = "`u8::BITS`."]
/// Otherwise, returns `Some(self >> rhs)`.
///
/// # Examples
///
/// ```
/// #![feature(exact_bitshifts)]
///
#[doc = "assert_eq!(0x10u8.shr_exact(4), Some(0x1));"]
#[doc = "assert_eq!(0x10u8.shr_exact(5), None);"]
/// ```
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn shr_exact(self, rhs: u32) -> Option<u8> {
if rhs <= self.trailing_zeros() && rhs < <u8>::BITS {
Some(unsafe { self.unchecked_shr(rhs) })
} else { None }
}
/// Unchecked exact shift right. Computes `self >> rhs`, assuming the operation can be
/// losslessly reversed and `rhs` cannot be larger than
#[doc = "`u8::BITS`."]
///
/// # Safety
///
/// This results in undefined behavior when `rhs > self.trailing_zeros() || rhs >=
#[doc = "u8::BITS`"]
/// i.e. when
#[doc = "[`u8::shr_exact`]"]
/// would return `None`.
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_shr_exact(self, rhs: u32) -> u8 {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(zeros: u32, bits: u32, rhs: u32) {
if !(rhs <= zeros && rhs < bits) {
let msg =
"unsafe precondition(s) violated: u8::unchecked_shr_exact cannot shift out non-zero bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_library_ub() {
precondition_check(self.trailing_zeros(), <u8>::BITS, rhs);
}
};
unsafe { self.unchecked_shr(rhs) }
}
/// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u8.checked_pow(5), Some(32));"]
#[doc = "assert_eq!(0_u8.checked_pow(0), Some(1));"]
#[doc = "assert_eq!(u8::MAX.checked_pow(2), None);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
let mut base = self;
let mut acc: Self = 1;
if intrinsics::is_val_statically_known(base) && base.is_power_of_two() {
let k = base.ilog2();
let shift =
match k.checked_mul(exp) { Some(x) => x, None => return None, };
return (1 as Self).checked_shl(shift);
}
if exp == 0 { return Some(1); }
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 {
acc =
match acc.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
exp /= 2;
base =
match base.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
return acc.checked_mul(base);
}
loop {
if (exp & 1) == 1 {
acc =
match acc.checked_mul(base) {
Some(x) => x,
None => return None,
};
if exp == 1 { return Some(acc); }
}
exp /= 2;
base =
match base.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
}
/// Strict exponentiation. Computes `self.pow(exp)`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u8.strict_pow(5), 32);"]
#[doc = "assert_eq!(0_u8.strict_pow(0), 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = u8::MAX.strict_pow(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) {
None => imp::overflow_panic::pow(),
Some(a) => a,
}
}
/// Saturating integer addition. Computes `self + rhs`, saturating at
/// the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u8.saturating_add(1), 101);"]
#[doc = "assert_eq!(u8::MAX.saturating_add(127), u8::MAX);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[inline(always)]
pub const fn saturating_add(self, rhs: Self) -> Self {
intrinsics::saturating_add(self, rhs)
}
/// Saturating addition with a signed integer. Computes `self + rhs`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u8.saturating_add_signed(2), 3);"]
#[doc = "assert_eq!(1u8.saturating_add_signed(-2), 0);"]
#[doc = "assert_eq!((u8::MAX - 2).saturating_add_signed(4), u8::MAX);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_add_signed(self, rhs: i8) -> Self {
let (res, overflow) = self.overflowing_add(rhs as Self);
if overflow == (rhs < 0) { res } else if overflow { Self::MAX } else { 0 }
}
/// Saturating integer subtraction. Computes `self - rhs`, saturating
/// at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u8.saturating_sub(27), 73);"]
#[doc = "assert_eq!(13u8.saturating_sub(127), 0);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[inline(always)]
pub const fn saturating_sub(self, rhs: Self) -> Self {
intrinsics::saturating_sub(self, rhs)
}
/// Saturating integer subtraction. Computes `self` - `rhs`, saturating at
/// the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u8.saturating_sub_signed(2), 0);"]
#[doc = "assert_eq!(1u8.saturating_sub_signed(-2), 3);"]
#[doc = "assert_eq!((u8::MAX - 2).saturating_sub_signed(-4), u8::MAX);"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_sub_signed(self, rhs: i8) -> Self {
let (res, overflow) = self.overflowing_sub_signed(rhs);
if !overflow { res } else if rhs < 0 { Self::MAX } else { 0 }
}
/// Saturating integer multiplication. Computes `self * rhs`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u8.saturating_mul(10), 20);"]
#[doc = "assert_eq!((u8::MAX).saturating_mul(10), u8::MAX);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_mul(self, rhs: Self) -> Self {
match self.checked_mul(rhs) { Some(x) => x, None => Self::MAX, }
}
/// Saturating integer division. Computes `self / rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u8.saturating_div(2), 2);"]
///
/// ```
#[stable(feature = "saturating_div", since = "1.58.0")]
#[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn saturating_div(self, rhs: Self) -> Self {
self.wrapping_div(rhs)
}
/// Saturating integer exponentiation. Computes `self.pow(exp)`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(4u8.saturating_pow(3), 64);"]
#[doc = "assert_eq!(0_u8.saturating_pow(0), 1);"]
#[doc = "assert_eq!(u8::MAX.saturating_pow(2), u8::MAX);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) { Some(x) => x, None => Self::MAX, }
}
/// Wrapping (modular) addition. Computes `self + rhs`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(200u8.wrapping_add(55), 255);"]
#[doc = "assert_eq!(200u8.wrapping_add(u8::MAX), 199);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_add(self, rhs: Self) -> Self {
intrinsics::wrapping_add(self, rhs)
}
/// Wrapping (modular) addition with a signed integer. Computes
/// `self + rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u8.wrapping_add_signed(2), 3);"]
#[doc = "assert_eq!(1u8.wrapping_add_signed(-2), u8::MAX);"]
#[doc = "assert_eq!((u8::MAX - 2).wrapping_add_signed(4), 1);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_add_signed(self, rhs: i8) -> Self {
self.wrapping_add(rhs as Self)
}
/// Wrapping (modular) subtraction. Computes `self - rhs`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u8.wrapping_sub(100), 0);"]
#[doc = "assert_eq!(100u8.wrapping_sub(u8::MAX), 101);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_sub(self, rhs: Self) -> Self {
intrinsics::wrapping_sub(self, rhs)
}
/// Wrapping (modular) subtraction with a signed integer. Computes
/// `self - rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u8.wrapping_sub_signed(2), u8::MAX);"]
#[doc = "assert_eq!(1u8.wrapping_sub_signed(-2), 3);"]
#[doc = "assert_eq!((u8::MAX - 2).wrapping_sub_signed(-4), 1);"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_sub_signed(self, rhs: i8) -> Self {
self.wrapping_sub(rhs as Self)
}
/// Wrapping (modular) multiplication. Computes `self *
/// rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `u8` is used.
///
/// ```
/// assert_eq!(10u8.wrapping_mul(12), 120);
/// assert_eq!(25u8.wrapping_mul(12), 44);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_mul(self, rhs: Self) -> Self {
intrinsics::wrapping_mul(self, rhs)
}
/// Wrapping (modular) division. Computes `self / rhs`.
///
/// Wrapped division on unsigned types is just normal division. There's
/// no way wrapping could ever happen. This function exists so that all
/// operations are accounted for in the wrapping operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u8.wrapping_div(10), 10);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn wrapping_div(self, rhs: Self) -> Self { self / rhs }
/// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
///
/// Wrapped division on unsigned types is just normal division. There's
/// no way wrapping could ever happen. This function exists so that all
/// operations are accounted for in the wrapping operations. Since, for
/// the positive integers, all common definitions of division are equal,
/// this is exactly equal to `self.wrapping_div(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u8.wrapping_div_euclid(10), 10);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn wrapping_div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Wrapping (modular) remainder. Computes `self % rhs`.
///
/// Wrapped remainder calculation on unsigned types is just the regular
/// remainder calculation. There's no way wrapping could ever happen.
/// This function exists so that all operations are accounted for in the
/// wrapping operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u8.wrapping_rem(10), 0);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn wrapping_rem(self, rhs: Self) -> Self { self % rhs }
/// Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
///
/// Wrapped modulo calculation on unsigned types is just the regular
/// remainder calculation. There's no way wrapping could ever happen.
/// This function exists so that all operations are accounted for in the
/// wrapping operations. Since, for the positive integers, all common
/// definitions of division are equal, this is exactly equal to
/// `self.wrapping_rem(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u8.wrapping_rem_euclid(10), 0);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Wrapping (modular) negation. Computes `-self`,
/// wrapping around at the boundary of the type.
///
/// Since unsigned types do not have negative equivalents
/// all applications of this function will wrap (except for `-0`).
/// For values smaller than the corresponding signed type's maximum
/// the result is the same as casting the corresponding signed value.
/// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
/// `MAX` is the corresponding signed type's maximum.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0_u8.wrapping_neg(), 0);"]
#[doc = "assert_eq!(u8::MAX.wrapping_neg(), 1);"]
#[doc = "assert_eq!(13_u8.wrapping_neg(), (!13) + 1);"]
#[doc = "assert_eq!(42_u8.wrapping_neg(), !(42 - 1));"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_neg(self) -> Self { (0 as u8).wrapping_sub(self) }
/// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
/// where `mask` removes any high-order bits of `rhs` that
/// would cause the shift to exceed the bitwidth of the type.
///
/// Beware that, unlike most other `wrapping_*` methods on integers, this
/// does *not* give the same result as doing the shift in infinite precision
/// then truncating as needed. Instead, the behaviour of this method matches what shift instructions
/// do on many processors, and is what the `<<` operator does when overflow
/// checks are disabled, but numerically it's weird. Consider, instead,
/// using [`Self::unbounded_shl`] which has nicer behaviour.
///
/// Note that this is *not* the same as a rotate-left; the
/// RHS of a wrapping shift-left is restricted to the range
/// of the type, rather than the bits shifted out of the LHS
/// being returned to the other end. The primitive integer
/// types all implement a [`rotate_left`](Self::rotate_left) function,
/// which may be what you want instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1_u8.wrapping_shl(7), 128);"]
#[doc = "assert_eq!(0b101_u8.wrapping_shl(0), 0b101);"]
#[doc = "assert_eq!(0b101_u8.wrapping_shl(1), 0b1010);"]
#[doc = "assert_eq!(0b101_u8.wrapping_shl(2), 0b10100);"]
#[doc = "assert_eq!(u8::MAX.wrapping_shl(2), u8::MAX - 3);"]
#[doc = "assert_eq!(42_u8.wrapping_shl(8), 42);"]
#[doc = "assert_eq!(42_u8.wrapping_shl(1).wrapping_shl(7), 0);"]
#[doc = "assert_eq!(1_u8.wrapping_shl(128), 1);"]
#[doc = "assert_eq!(5_u8.wrapping_shl(1025), 10);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_shl(self, rhs: u32) -> Self {
unsafe { self.unchecked_shl(rhs & (Self::BITS - 1)) }
}
/// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
/// where `mask` removes any high-order bits of `rhs` that
/// would cause the shift to exceed the bitwidth of the type.
///
/// Beware that, unlike most other `wrapping_*` methods on integers, this
/// does *not* give the same result as doing the shift in infinite precision
/// then truncating as needed. Instead, the behaviour of this method matches what shift instructions
/// do on many processors, and is what the `>>` operator does when overflow
/// checks are disabled, but numerically it's weird. Consider, instead,
/// using [`Self::unbounded_shr`] which has nicer behaviour.
///
/// Note that this is *not* the same as a rotate-right; the
/// RHS of a wrapping shift-right is restricted to the range
/// of the type, rather than the bits shifted out of the LHS
/// being returned to the other end. The primitive integer
/// types all implement a [`rotate_right`](Self::rotate_right) function,
/// which may be what you want instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128_u8.wrapping_shr(7), 1);"]
#[doc = "assert_eq!(0b1010_u8.wrapping_shr(0), 0b1010);"]
#[doc = "assert_eq!(0b1010_u8.wrapping_shr(1), 0b101);"]
#[doc = "assert_eq!(0b1010_u8.wrapping_shr(2), 0b10);"]
#[doc = "assert_eq!(u8::MAX.wrapping_shr(1), i8::MAX.cast_unsigned());"]
#[doc = "assert_eq!(42_u8.wrapping_shr(8), 42);"]
#[doc = "assert_eq!(42_u8.wrapping_shr(1).wrapping_shr(7), 0);"]
#[doc = "assert_eq!(128_u8.wrapping_shr(128), 128);"]
#[doc = "assert_eq!(10_u8.wrapping_shr(1025), 5);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_shr(self, rhs: u32) -> Self {
unsafe { self.unchecked_shr(rhs & (Self::BITS - 1)) }
}
/// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3u8.wrapping_pow(5), 243);"]
/// assert_eq!(3u8.wrapping_pow(6), 217);
#[doc = "assert_eq!(0_u8.wrapping_pow(0), 1);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_pow(self, exp: u32) -> Self {
let (a, _) = self.overflowing_pow(exp);
a
}
/// Calculates `self` + `rhs`.
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u8.overflowing_add(2), (7, false));"]
#[doc = "assert_eq!(u8::MAX.overflowing_add(1), (0, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::add_with_overflow(self as u8, rhs as u8);
(a as Self, b)
}
/// Calculates `self` + `rhs` + `carry` and returns a tuple containing
/// the sum and the output carry (in that order).
///
/// Performs "ternary addition" of two integer operands and a carry-in
/// bit, and returns an output integer and a carry-out bit. This allows
/// chaining together multiple additions to create a wider addition, and
/// can be useful for bignum addition.
///
#[doc =
"This can be thought of as a 8-bit \"full adder\", in the electronics sense."]
///
/// If the input carry is false, this method is equivalent to
/// [`overflowing_add`](Self::overflowing_add), and the output carry is
/// equal to the overflow flag. Note that although carry and overflow
/// flags are similar for unsigned integers, they are different for
/// signed integers.
///
/// # Examples
///
/// ```
#[doc = "// 3 MAX (a = 3 \u{d7} 2^8 + 2^8 - 1)"]
#[doc = "// + 5 7 (b = 5 \u{d7} 2^8 + 7)"]
/// // ---------
#[doc = "// 9 6 (sum = 9 \u{d7} 2^8 + 6)"]
///
#[doc = "let (a1, a0): (u8, u8) = (3, u8::MAX);"]
#[doc = "let (b1, b0): (u8, u8) = (5, 7);"]
/// let carry0 = false;
///
/// let (sum0, carry1) = a0.carrying_add(b0, carry0);
/// assert_eq!(carry1, true);
/// let (sum1, carry2) = a1.carrying_add(b1, carry1);
/// assert_eq!(carry2, false);
///
/// assert_eq!((sum1, sum0), (9, 6));
/// ```
#[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
#[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue =
"152015")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
let (a, c1) = self.overflowing_add(rhs);
let (b, c2) = a.overflowing_add(carry as u8);
(b, unsafe { intrinsics::disjoint_bitor(c1, c2) })
}
/// Calculates `self` + `rhs` with a signed `rhs`.
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u8.overflowing_add_signed(2), (3, false));"]
#[doc = "assert_eq!(1u8.overflowing_add_signed(-2), (u8::MAX, true));"]
#[doc = "assert_eq!((u8::MAX - 2).overflowing_add_signed(4), (1, true));"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_add_signed(self, rhs: i8) -> (Self, bool) {
let (res, overflowed) = self.overflowing_add(rhs as Self);
(res, overflowed ^ (rhs < 0))
}
/// Calculates `self` - `rhs`.
///
/// Returns a tuple of the subtraction along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u8.overflowing_sub(2), (3, false));"]
#[doc = "assert_eq!(0u8.overflowing_sub(1), (u8::MAX, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::sub_with_overflow(self as u8, rhs as u8);
(a as Self, b)
}
/// Calculates `self` − `rhs` − `borrow` and returns a tuple
/// containing the difference and the output borrow.
///
/// Performs "ternary subtraction" by subtracting both an integer
/// operand and a borrow-in bit from `self`, and returns an output
/// integer and a borrow-out bit. This allows chaining together multiple
/// subtractions to create a wider subtraction, and can be useful for
/// bignum subtraction.
///
/// # Examples
///
/// ```
#[doc = "// 9 6 (a = 9 \u{d7} 2^8 + 6)"]
#[doc = "// - 5 7 (b = 5 \u{d7} 2^8 + 7)"]
/// // ---------
#[doc = "// 3 MAX (diff = 3 \u{d7} 2^8 + 2^8 - 1)"]
///
#[doc = "let (a1, a0): (u8, u8) = (9, 6);"]
#[doc = "let (b1, b0): (u8, u8) = (5, 7);"]
/// let borrow0 = false;
///
/// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);
/// assert_eq!(borrow1, true);
/// let (diff1, borrow2) = a1.borrowing_sub(b1, borrow1);
/// assert_eq!(borrow2, false);
///
#[doc = "assert_eq!((diff1, diff0), (3, u8::MAX));"]
/// ```
#[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
#[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue =
"152015")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
let (a, c1) = self.overflowing_sub(rhs);
let (b, c2) = a.overflowing_sub(borrow as u8);
(b, unsafe { intrinsics::disjoint_bitor(c1, c2) })
}
/// Calculates `self` - `rhs` with a signed `rhs`
///
/// Returns a tuple of the subtraction along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u8.overflowing_sub_signed(2), (u8::MAX, true));"]
#[doc = "assert_eq!(1u8.overflowing_sub_signed(-2), (3, false));"]
#[doc = "assert_eq!((u8::MAX - 2).overflowing_sub_signed(-4), (1, true));"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_sub_signed(self, rhs: i8) -> (Self, bool) {
let (res, overflow) = self.overflowing_sub(rhs as Self);
(res, overflow ^ (rhs < 0))
}
/// Computes the absolute difference between `self` and `other`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u8.abs_diff(80), 20u8);"]
#[doc = "assert_eq!(100u8.abs_diff(110), 10u8);"]
/// ```
#[stable(feature = "int_abs_diff", since = "1.60.0")]
#[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn abs_diff(self, other: Self) -> Self {
if size_of::<Self>() == 1 {
(self as i32).wrapping_sub(other as i32).unsigned_abs() as Self
} else { if self < other { other - self } else { self - other } }
}
/// Calculates the multiplication of `self` and `rhs`.
///
/// Returns a tuple of the multiplication along with a boolean
/// indicating whether an arithmetic overflow would occur. If an
/// overflow would have occurred then the wrapped value is returned.
///
/// If you want the *value* of the overflow, rather than just *whether*
/// an overflow occurred, see [`Self::carrying_mul`].
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `u32` is used.
///
/// ```
/// assert_eq!(5u32.overflowing_mul(2), (10, false));
/// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::mul_with_overflow(self as u8, rhs as u8);
(a as Self, b)
}
/// Calculates the "full multiplication" `self * rhs + carry`
/// without the possibility to overflow.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// Performs "long multiplication" which takes in an extra amount to add, and may return an
/// additional amount of overflow. This allows for chaining together multiple
/// multiplications to create "big integers" which represent larger values.
///
/// If you also need to add a value, then use [`Self::carrying_mul_add`].
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `u32` is used.
///
/// ```
/// assert_eq!(5u32.carrying_mul(2, 0), (10, 0));
/// assert_eq!(5u32.carrying_mul(2, 10), (20, 0));
/// assert_eq!(1_000_000_000u32.carrying_mul(10, 0), (1410065408, 2));
/// assert_eq!(1_000_000_000u32.carrying_mul(10, 10), (1410065418, 2));
#[doc = "assert_eq!(u8::MAX.carrying_mul(u8::MAX, u8::MAX), (0, u8::MAX));"]
/// ```
///
/// This is the core operation needed for scalar multiplication when
/// implementing it for wider-than-native types.
///
/// ```
/// fn scalar_mul_eq(little_endian_digits: &mut Vec<u16>, multiplicand: u16) {
/// let mut carry = 0;
/// for d in little_endian_digits.iter_mut() {
/// (*d, carry) = d.carrying_mul(multiplicand, carry);
/// }
/// if carry != 0 {
/// little_endian_digits.push(carry);
/// }
/// }
///
/// let mut v = vec![10, 20];
/// scalar_mul_eq(&mut v, 3);
/// assert_eq!(v, [30, 60]);
///
/// assert_eq!(0x87654321_u64 * 0xFEED, 0x86D3D159E38D);
/// let mut v = vec![0x4321, 0x8765];
/// scalar_mul_eq(&mut v, 0xFEED);
/// assert_eq!(v, [0xE38D, 0xD159, 0x86D3]);
/// ```
///
/// If `carry` is zero, this is similar to [`overflowing_mul`](Self::overflowing_mul),
/// except that it gives the value of the overflow instead of just whether one happened:
///
/// ```
/// # #![allow(unused_features)]
/// #![feature(const_unsigned_bigint_helpers)]
/// let r = u8::carrying_mul(7, 13, 0);
/// assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(7, 13));
/// let r = u8::carrying_mul(13, 42, 0);
/// assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(13, 42));
/// ```
///
/// The value of the first field in the returned tuple matches what you'd get
/// by combining the [`wrapping_mul`](Self::wrapping_mul) and
/// [`wrapping_add`](Self::wrapping_add) methods:
///
/// ```
/// # #![allow(unused_features)]
/// #![feature(const_unsigned_bigint_helpers)]
/// assert_eq!(
/// 789_u16.carrying_mul(456, 123).0,
/// 789_u16.wrapping_mul(456).wrapping_add(123),
/// );
/// ```
#[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
#[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue =
"152015")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_mul(self, rhs: Self, carry: Self) -> (Self, Self) {
Self::carrying_mul_add(self, rhs, carry, 0)
}
/// Calculates the "full multiplication" `self * rhs + carry + add`.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// This cannot overflow, as the double-width result has exactly enough
/// space for the largest possible result. This is equivalent to how, in
/// decimal, 9 × 9 + 9 + 9 = 81 + 18 = 99 = 9×10⁰ + 9×10¹ = 10² - 1.
///
/// Performs "long multiplication" which takes in an extra amount to add, and may return an
/// additional amount of overflow. This allows for chaining together multiple
/// multiplications to create "big integers" which represent larger values.
///
/// If you don't need the `add` part, then you can use [`Self::carrying_mul`] instead.
///
/// # Examples
///
/// Please note that this example is shared between integer types,
/// which explains why `u32` is used here.
///
/// ```
/// assert_eq!(5u32.carrying_mul_add(2, 0, 0), (10, 0));
/// assert_eq!(5u32.carrying_mul_add(2, 10, 10), (30, 0));
/// assert_eq!(1_000_000_000u32.carrying_mul_add(10, 0, 0), (1410065408, 2));
/// assert_eq!(1_000_000_000u32.carrying_mul_add(10, 10, 10), (1410065428, 2));
#[doc =
"assert_eq!(u8::MAX.carrying_mul_add(u8::MAX, u8::MAX, u8::MAX), (u8::MAX, u8::MAX));"]
/// ```
///
/// This is the core per-digit operation for "grade school" O(n²) multiplication.
///
/// Please note that this example is shared between integer types,
/// using `u8` for simplicity of the demonstration.
///
/// ```
/// fn quadratic_mul<const N: usize>(a: [u8; N], b: [u8; N]) -> [u8; N] {
/// let mut out = [0; N];
/// for j in 0..N {
/// let mut carry = 0;
/// for i in 0..(N - j) {
/// (out[j + i], carry) = u8::carrying_mul_add(a[i], b[j], out[j + i], carry);
/// }
/// }
/// out
/// }
///
/// // -1 * -1 == 1
/// assert_eq!(quadratic_mul([0xFF; 3], [0xFF; 3]), [1, 0, 0]);
///
/// assert_eq!(u32::wrapping_mul(0x9e3779b9, 0x7f4a7c15), 0xcffc982d);
/// assert_eq!(
/// quadratic_mul(u32::to_le_bytes(0x9e3779b9), u32::to_le_bytes(0x7f4a7c15)),
/// u32::to_le_bytes(0xcffc982d)
/// );
/// ```
#[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
#[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue =
"152015")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_mul_add(self, rhs: Self, carry: Self, add: Self)
-> (Self, Self) {
intrinsics::carrying_mul_add(self, rhs, carry, add)
}
/// Calculates the divisor when `self` is divided by `rhs`.
///
/// Returns a tuple of the divisor along with a boolean indicating
/// whether an arithmetic overflow would occur. Note that for unsigned
/// integers overflow never occurs, so the second value is always
/// `false`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u8.overflowing_div(2), (2, false));"]
/// ```
#[inline(always)]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_overflowing_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[track_caller]
pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
(self / rhs, false)
}
/// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
///
/// Returns a tuple of the divisor along with a boolean indicating
/// whether an arithmetic overflow would occur. Note that for unsigned
/// integers overflow never occurs, so the second value is always
/// `false`.
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self.overflowing_div(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u8.overflowing_div_euclid(2), (2, false));"]
/// ```
#[inline(always)]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[track_caller]
pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
(self / rhs, false)
}
/// Calculates the remainder when `self` is divided by `rhs`.
///
/// Returns a tuple of the remainder after dividing along with a boolean
/// indicating whether an arithmetic overflow would occur. Note that for
/// unsigned integers overflow never occurs, so the second value is
/// always `false`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u8.overflowing_rem(2), (1, false));"]
/// ```
#[inline(always)]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_overflowing_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[track_caller]
pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
(self % rhs, false)
}
/// Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
///
/// Returns a tuple of the modulo after dividing along with a boolean
/// indicating whether an arithmetic overflow would occur. Note that for
/// unsigned integers overflow never occurs, so the second value is
/// always `false`.
/// Since, for the positive integers, all common
/// definitions of division are equal, this operation
/// is exactly equal to `self.overflowing_rem(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u8.overflowing_rem_euclid(2), (1, false));"]
/// ```
#[inline(always)]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[track_caller]
pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
(self % rhs, false)
}
/// Negates self in an overflowing fashion.
///
/// Returns `!self + 1` using wrapping operations to return the value
/// that represents the negation of this unsigned value. Note that for
/// positive unsigned values overflow always occurs, but negating 0 does
/// not overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0u8.overflowing_neg(), (0, false));"]
#[doc = "assert_eq!(2u8.overflowing_neg(), (-2i32 as u8, true));"]
/// ```
#[inline(always)]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn overflowing_neg(self) -> (Self, bool) {
((!self).wrapping_add(1), self != 0)
}
/// Shifts self left by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean
/// indicating whether the shift value was larger than or equal to the
/// number of bits. If the shift value is too large, then value is
/// masked (N-1) where N is the number of bits, and this value is then
/// used to perform the shift.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1u8.overflowing_shl(4), (0x10, false));"]
#[doc = "assert_eq!(0x1u8.overflowing_shl(132), (0x10, true));"]
#[doc = "assert_eq!(0x10u8.overflowing_shl(7), (0, false));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shl(rhs), rhs >= Self::BITS)
}
/// Shifts self right by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean
/// indicating whether the shift value was larger than or equal to the
/// number of bits. If the shift value is too large, then value is
/// masked (N-1) where N is the number of bits, and this value is then
/// used to perform the shift.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10u8.overflowing_shr(4), (0x1, false));"]
#[doc = "assert_eq!(0x10u8.overflowing_shr(132), (0x1, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shr(rhs), rhs >= Self::BITS)
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// Returns a tuple of the exponentiation along with a bool indicating
/// whether an overflow happened.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3u8.overflowing_pow(5), (243, false));"]
#[doc = "assert_eq!(0_u8.overflowing_pow(0), (1, false));"]
/// assert_eq!(3u8.overflowing_pow(6), (217, true));
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
let mut base = self;
let mut acc: Self = 1;
let mut overflow = false;
let mut tmp_overflow;
if intrinsics::is_val_statically_known(base) && base.is_power_of_two() {
let k = base.ilog2();
let Some(shift) = k.checked_mul(exp) else { return (0, true) };
return ((1 as Self).unbounded_shl(shift), shift >= Self::BITS)
}
if exp == 0 { return (1, false); }
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 {
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
}
exp /= 2;
(base, tmp_overflow) = base.overflowing_mul(base);
overflow |= tmp_overflow;
}
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
return (acc, overflow);
}
loop {
if (exp & 1) == 1 {
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
if exp == 1 { return (acc, overflow); }
}
exp /= 2;
(base, tmp_overflow) = base.overflowing_mul(base);
overflow |= tmp_overflow;
}
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u8.pow(5), 32);"]
#[doc = "assert_eq!(0_u8.pow(0), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn pow(self, exp: u32) -> Self {
if intrinsics::overflow_checks() {
self.strict_pow(exp)
} else { self.wrapping_pow(exp) }
}
/// Returns the square root of the number, rounded down.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10u8.isqrt(), 3);"]
/// ```
#[stable(feature = "isqrt", since = "1.84.0")]
#[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn isqrt(self) -> Self {
let result = imp::int_sqrt::u8(self as u8) as Self;
unsafe {
const MAX_RESULT: u8 = imp::int_sqrt::u8(<u8>::MAX) as u8;
crate::hint::assert_unchecked(result <= MAX_RESULT)
}
if self >= 1 { unsafe { crate::hint::assert_unchecked(result >= 1) } }
unsafe {
crate::hint::assert_unchecked(result.unchecked_mul(result) <= self);
crate::hint::assert_unchecked(result <= self);
}
result
}
/// Performs Euclidean division.
///
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self / rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7u8.div_euclid(4), 1); // or any other integer type"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Calculates the least remainder of `self` when divided by
/// `rhs`.
///
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self % rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7u8.rem_euclid(4), 3); // or any other integer type"]
/// ```
#[doc(alias = "modulo", alias = "mod")]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
///
/// This is the same as performing `self / rhs` for all unsigned integers.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "assert_eq!(7_u8.div_floor(4), 1);"]
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn div_floor(self, rhs: Self) -> Self { self / rhs }
/// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7_u8.div_ceil(4), 2);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_ceil(self, rhs: Self) -> Self {
let d = self / rhs;
let r = self % rhs;
if r > 0 { d + 1 } else { d }
}
/// Calculates the smallest value greater than or equal to `self` that
/// is a multiple of `rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// On overflow, this function will panic if overflow checks are enabled (default in debug
/// mode) and wrap if overflow checks are disabled (default in release mode).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(16_u8.next_multiple_of(8), 16);"]
#[doc = "assert_eq!(23_u8.next_multiple_of(8), 24);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_multiple_of(self, rhs: Self) -> Self {
match self % rhs { 0 => self, r => self + (rhs - r), }
}
/// Calculates the smallest value greater than or equal to `self` that
/// is a multiple of `rhs`. Returns `None` if `rhs` is zero or the
/// operation would result in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(16_u8.checked_next_multiple_of(8), Some(16));"]
#[doc = "assert_eq!(23_u8.checked_next_multiple_of(8), Some(24));"]
#[doc = "assert_eq!(1_u8.checked_next_multiple_of(0), None);"]
#[doc = "assert_eq!(u8::MAX.checked_next_multiple_of(2), None);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
match match self.checked_rem(rhs) { Some(x) => x, None => return None, } {
0 => Some(self),
r => self.checked_add(rhs - r),
}
}
/// Returns `true` if `self` is an integer multiple of `rhs`, and false otherwise.
///
/// This function is equivalent to `self % rhs == 0`, except that it will not panic
/// for `rhs == 0`. Instead, `0.is_multiple_of(0) == true`, and for any non-zero `n`,
/// `n.is_multiple_of(0) == false`.
///
/// # Examples
///
/// ```
#[doc = "assert!(6_u8.is_multiple_of(2));"]
#[doc = "assert!(!5_u8.is_multiple_of(2));"]
///
#[doc = "assert!(0_u8.is_multiple_of(0));"]
#[doc = "assert!(!6_u8.is_multiple_of(0));"]
/// ```
#[stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
#[rustc_const_stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
#[must_use]
#[inline]
pub const fn is_multiple_of(self, rhs: Self) -> bool {
match rhs { 0 => self == 0, _ => self % rhs == 0, }
}
/// Returns `true` if and only if `self == 2^k` for some unsigned integer `k`.
///
/// # Examples
///
/// ```
#[doc = "assert!(16u8.is_power_of_two());"]
#[doc = "assert!(!10u8.is_power_of_two());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
#[inline(always)]
pub const fn is_power_of_two(self) -> bool { self.count_ones() == 1 }
#[inline]
const fn one_less_than_next_power_of_two(self) -> Self {
if self <= 1 { return 0; }
let p = self - 1;
let z = unsafe { intrinsics::ctlz_nonzero(p) };
<u8>::MAX >> z
}
/// Returns the smallest power of two greater than or equal to `self`.
///
/// When return value overflows (i.e., `self > (1 << (N-1))` for type
/// `uN`), it panics in debug mode and the return value is wrapped to 0 in
/// release mode (the only situation in which this method can return 0).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u8.next_power_of_two(), 2);"]
#[doc = "assert_eq!(3u8.next_power_of_two(), 4);"]
#[doc = "assert_eq!(0u8.next_power_of_two(), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_power_of_two(self) -> Self {
self.one_less_than_next_power_of_two() + 1
}
/// Returns the smallest power of two greater than or equal to `self`. If
/// the next power of two is greater than the type's maximum value,
/// `None` is returned, otherwise the power of two is wrapped in `Some`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u8.checked_next_power_of_two(), Some(2));"]
#[doc = "assert_eq!(3u8.checked_next_power_of_two(), Some(4));"]
#[doc = "assert_eq!(u8::MAX.checked_next_power_of_two(), None);"]
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn checked_next_power_of_two(self) -> Option<Self> {
self.one_less_than_next_power_of_two().checked_add(1)
}
/// Returns the smallest power of two greater than or equal to `n`. If
/// the next power of two is greater than the type's maximum value,
/// the return value is wrapped to `0`.
///
/// # Examples
///
/// ```
/// #![feature(wrapping_next_power_of_two)]
///
#[doc = "assert_eq!(2u8.wrapping_next_power_of_two(), 2);"]
#[doc = "assert_eq!(3u8.wrapping_next_power_of_two(), 4);"]
#[doc = "assert_eq!(u8::MAX.wrapping_next_power_of_two(), 0);"]
/// ```
#[inline]
#[unstable(feature = "wrapping_next_power_of_two", issue = "32463", reason =
"needs decision on wrapping behavior")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn wrapping_next_power_of_two(self) -> Self {
self.one_less_than_next_power_of_two().wrapping_add(1)
}
/// Returns the memory representation of this integer as a byte array in
/// big-endian (network) byte order.
///
#[doc =
"
**Note**: This function is meaningless on `u8`. Byte order does not exist as a
concept for byte-sized integers. This function is only provided in symmetry
with larger integer types.
"]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12u8.to_be_bytes();"]
#[doc = "assert_eq!(bytes, [0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
self.to_be().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// little-endian byte order.
///
#[doc =
"
**Note**: This function is meaningless on `u8`. Byte order does not exist as a
concept for byte-sized integers. This function is only provided in symmetry
with larger integer types.
"]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12u8.to_le_bytes();"]
#[doc = "assert_eq!(bytes, [0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
self.to_le().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code
/// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
/// instead.
///
#[doc =
"
**Note**: This function is meaningless on `u8`. Byte order does not exist as a
concept for byte-sized integers. This function is only provided in symmetry
with larger integer types.
"]
///
/// [`to_be_bytes`]: Self::to_be_bytes
/// [`to_le_bytes`]: Self::to_le_bytes
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12u8.to_ne_bytes();"]
/// assert_eq!(
/// bytes,
/// if cfg!(target_endian = "big") {
#[doc = " [0x12]"]
/// } else {
#[doc = " [0x12]"]
/// }
/// );
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[allow(unnecessary_transmutes)]
#[inline]
pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
unsafe { mem::transmute(self) }
}
/// Creates a native endian integer value from its representation
/// as a byte array in big endian.
///
#[doc =
"
**Note**: This function is meaningless on `u8`. Byte order does not exist as a
concept for byte-sized integers. This function is only provided in symmetry
with larger integer types.
"]
///
/// # Examples
///
/// ```
#[doc = "let value = u8::from_be_bytes([0x12]);"]
#[doc = "assert_eq!(value, 0x12);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_be_u8(input: &mut &[u8]) -> u8 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u8>());"]
/// *input = rest;
#[doc = " u8::from_be_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_be(Self::from_ne_bytes(bytes))
}
/// Creates a native endian integer value from its representation
/// as a byte array in little endian.
///
#[doc =
"
**Note**: This function is meaningless on `u8`. Byte order does not exist as a
concept for byte-sized integers. This function is only provided in symmetry
with larger integer types.
"]
///
/// # Examples
///
/// ```
#[doc = "let value = u8::from_le_bytes([0x12]);"]
#[doc = "assert_eq!(value, 0x12);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_le_u8(input: &mut &[u8]) -> u8 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u8>());"]
/// *input = rest;
#[doc = " u8::from_le_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_le(Self::from_ne_bytes(bytes))
}
/// Creates a native endian integer value from its memory representation
/// as a byte array in native endianness.
///
/// As the target platform's native endianness is used, portable code
/// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
/// appropriate instead.
///
/// [`from_be_bytes`]: Self::from_be_bytes
/// [`from_le_bytes`]: Self::from_le_bytes
///
#[doc =
"
**Note**: This function is meaningless on `u8`. Byte order does not exist as a
concept for byte-sized integers. This function is only provided in symmetry
with larger integer types.
"]
///
/// # Examples
///
/// ```
#[doc = "let value = u8::from_ne_bytes(if cfg!(target_endian = \"big\") {"]
#[doc = " [0x12]"]
/// } else {
#[doc = " [0x12]"]
/// });
#[doc = "assert_eq!(value, 0x12);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_ne_u8(input: &mut &[u8]) -> u8 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u8>());"]
/// *input = rest;
#[doc = " u8::from_ne_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use]
#[inline]
pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
unsafe { mem::transmute(bytes) }
}
/// New code should prefer to use
#[doc = "[`u8::MIN`] instead."]
///
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_promotable]
#[inline(always)]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MIN` associated constant on this type")]
#[rustc_diagnostic_item = "u8_legacy_fn_min_value"]
pub const fn min_value() -> Self { Self::MIN }
/// New code should prefer to use
#[doc = "[`u8::MAX`] instead."]
///
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_promotable]
#[inline(always)]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MAX` associated constant on this type")]
#[rustc_diagnostic_item = "u8_legacy_fn_max_value"]
pub const fn max_value() -> Self { Self::MAX }
/// Truncate an integer to an integer of the same size or smaller, preserving the least
/// significant bits.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u8, 120u8.truncate());"]
/// assert_eq!(120u8, 376u32.truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
/// instead of truncating.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u8, 120u8.saturating_truncate());"]
/// assert_eq!(255u8, 376u32.saturating_truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn saturating_truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_saturating_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
/// is outside the bounds of the smaller type.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(Some(120u8), 120u8.checked_truncate());"]
/// assert_eq!(None, 376u32.checked_truncate::<u8>());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn checked_truncate<Target>(self) -> Option<Target> where
Self: [const] traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_checked_truncate(self)
}
/// Widen to an integer of the same size or larger, preserving its value.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u128, 120u8.widen());"]
/// ```
#[must_use =
"this returns the widened value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn widen<Target>(self) -> Target where Self: [const]
traits::WidenTarget<Target> {
traits::WidenTarget::internal_widen(self)
}
/// Converts `self` to the target integer type, saturating at the numeric
/// bounds instead of overflowing.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(255u8, u8::MAX.saturating_cast());"]
#[doc = "assert_eq!(127i8, u8::MAX.saturating_cast());"]
#[doc = "assert_eq!(42i8, 42u8.saturating_cast());"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn saturating_cast<T: [const] BoundedCastFromInt<Self>>(self) -> T {
T::saturating_cast_from(self)
}
/// Converts `self` to the target integer type, wrapping around at the
/// boundary of the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(255u8, u8::MAX.wrapping_cast());"]
#[doc = "assert_eq!(42i8, 42u8.wrapping_cast());"]
#[doc = "assert_eq!(u8::MAX as i8, u8::MAX.wrapping_cast());"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn wrapping_cast<T: [const] BoundedCastFromInt<Self>>(self) -> T {
T::wrapping_cast_from(self)
}
/// Converts `self` to the target integer type, returning `None` if the value
/// is not representable by the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(Some(42u8), 42u8.checked_cast());"]
#[doc = "assert_eq!(128u8.checked_cast::<i8>(), None);"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn checked_cast<T: [const] CheckedCastFromInt<Self>>(self)
-> Option<T> {
T::checked_cast_from(self)
}
/// Converts `self` to the target integer type, panicking if the value
/// is not representable by the target type.
///
/// # Panics
///
/// This function will panic if the value is not representable by the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(42u8, 42u8.strict_cast());"]
/// ```
///
/// The following will panic:
///
/// ```should_panic
/// #![feature(integer_casts)]
#[doc = "let _ = 128u8.strict_cast::<i8>();"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
#[track_caller]
pub const fn strict_cast<T: [const] CheckedCastFromInt<Self>>(self) -> T {
T::strict_cast_from(self)
}
/// Converts `self` to the target integer type, assuming the value is
/// representable by the target type.
///
/// # Safety
///
/// This results in undefined behavior if the integer value of `self` is bigger than `T::MAX`,
/// or smaller than `T::MIN`, where `T` is the target type.
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const unsafe fn unchecked_cast<T: [const] CheckedCastFromInt<Self>>(self)
-> T {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(in_bounds: bool) {
if !in_bounds {
let msg =
"unsafe precondition(s) violated: u8::unchecked_cast must fit in the target type\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check({
let cast_val = self.checked_cast::<T>();
let ret = cast_val.is_some();
core::mem::forget(cast_val);
ret
});
}
};
unsafe { T::unchecked_cast_from(self) }
}uint_impl! {
584Self = u8,
585 ActualT = u8,
586 SignedT = i8,
587 BITS = 8,
588 BITS_MINUS_ONE = 7,
589 MAX = 255,
590 rot = 2,
591 rot_op = "0x82",
592 rot_result = "0xa",
593 fsh_op = "0x36",
594 fshl_result = "0x8",
595 fshr_result = "0x8d",
596 clmul_lhs = "0x12",
597 clmul_rhs = "0x34",
598 clmul_result = "0x28",
599 swap_op = "0x12",
600 swapped = "0x12",
601 reversed = "0x48",
602 le_bytes = "[0x12]",
603 be_bytes = "[0x12]",
604 to_xe_bytes_doc = u8_xe_bytes_doc!(),
605 from_xe_bytes_doc = u8_xe_bytes_doc!(),
606 bound_condition = "",
607 }608/// Calculates the midpoint (average) between `self` and `rhs`.
///
/// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
/// sufficiently-large unsigned integral type. This implies that the result is
/// always rounded towards zero and that no overflow will ever occur.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0u8.midpoint(4), 2);"]
#[doc = "assert_eq!(1u8.midpoint(4), 2);"]
/// ```
#[stable(feature = "num_midpoint", since = "1.85.0")]
#[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[doc(alias = "average_floor")]
#[doc(alias = "average")]
#[inline]
pub const fn midpoint(self, rhs: u8) -> u8 {
((self as u16 + rhs as u16) / 2) as u8
}midpoint_impl! { u8, u16, unsigned }609/// Widening multiplication. Computes `self * rhs`, widening to a larger integer.
///
/// The returned value is always exact and can never overflow.
///
/// Note that this method is semantically equivalent to [`carrying_mul`] with a
/// carry of zero, with the latter instead returning a tuple denoting the low and
/// high parts of the result. Consider using it instead if you need
/// interoperability with other big int helper functions, or if this method isn't
/// available for a given type.
///
/// [`carrying_mul`]: Self::carrying_mul
///
/// # Examples
///
/// ```
/// #![feature(widening_mul)]
///
#[doc = "assert_eq!(u8::MAX.widening_mul(0_u8), 0);"]
#[doc =
"assert_eq!(u8::MAX.widening_mul(u8::MAX), u8::MAX as u16 * u8::MAX as u16);"]
/// ```
#[unstable(feature = "widening_mul", issue = "152016")]
#[rustc_const_unstable(feature = "widening_mul", issue = "152016")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn widening_mul(self, rhs: Self) -> u16 { self as u16 * rhs as u16 }widening_mul_impl! { u8, u16 }610/// Performs a widening carry-less multiplication.
///
/// # Examples
///
/// ```
/// #![feature(uint_carryless_mul)]
///
#[doc = "assert_eq!(u8::MAX.widening_carryless_mul(u8::MAX), u16::MAX / 3);"]
/// ```
#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
#[doc(alias = "clmul")]
#[unstable(feature = "uint_carryless_mul", issue = "152080")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn widening_carryless_mul(self, rhs: u8) -> u16 {
(self as u16).carryless_mul(rhs as u16)
}widening_carryless_mul_impl! { u8, u16 }611/// Calculates the "full carryless multiplication" without the possibility to overflow.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `u8` is used.
///
/// ```
/// #![feature(uint_carryless_mul)]
///
/// assert_eq!(0b1000_0000u8.carrying_carryless_mul(0b1000_0000, 0b0000), (0, 0b0100_0000));
/// assert_eq!(0b1000_0000u8.carrying_carryless_mul(0b1000_0000, 0b1111), (0b1111, 0b0100_0000));
#[doc =
"assert_eq!(u8::MAX.carrying_carryless_mul(u8::MAX, u8::MAX), (!(u8::MAX / 3), u8::MAX / 3));"]
/// ```
#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
#[doc(alias = "clmul")]
#[unstable(feature = "uint_carryless_mul", issue = "152080")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_carryless_mul(self, rhs: Self, carry: Self)
-> (Self, Self) {
let p = (self as u16).carryless_mul(rhs as u16);
let lo = (p as u8);
let hi = (p >> Self::BITS) as u8;
(lo ^ carry, hi)
}carrying_carryless_mul_impl! { u8, u16 }612613/// Checks if the value is within the ASCII range.
614 ///
615 /// # Examples
616 ///
617 /// ```
618 /// let ascii = 97u8;
619 /// let non_ascii = 150u8;
620 ///
621 /// assert!(ascii.is_ascii());
622 /// assert!(!non_ascii.is_ascii());
623 /// ```
624#[must_use]
625 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
626 #[rustc_const_stable(feature = "const_u8_is_ascii", since = "1.43.0")]
627 #[inline]
628pub const fn is_ascii(&self) -> bool {
629*self <= 127
630}
631632/// If the value of this byte is within the ASCII range, returns it as an
633 /// [ASCII character](ascii::Char). Otherwise, returns `None`.
634#[must_use]
635 #[unstable(feature = "ascii_char", issue = "110998")]
636 #[inline]
637pub const fn as_ascii(&self) -> Option<ascii::Char> {
638 ascii::Char::from_u8(*self)
639 }
640641/// Converts this byte to an [ASCII character](ascii::Char), without
642 /// checking whether or not it's valid.
643 ///
644 /// # Safety
645 ///
646 /// This byte must be valid ASCII, or else this is UB.
647#[must_use]
648 #[unstable(feature = "ascii_char", issue = "110998")]
649 #[inline]
650pub const unsafe fn as_ascii_unchecked(&self) -> ascii::Char {
651{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(it: &u8) {
if !it.is_ascii() {
let msg =
"unsafe precondition(s) violated: as_ascii_unchecked requires that the byte is valid ASCII\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_library_ub() { precondition_check(self); }
};assert_unsafe_precondition!(
652 check_library_ub,
653"as_ascii_unchecked requires that the byte is valid ASCII",
654 (it: &u8 = self) => it.is_ascii()
655 );
656657// SAFETY: the caller promised that this byte is ASCII.
658unsafe { ascii::Char::from_u8_unchecked(*self) }
659 }
660661/// Makes a copy of the value in its ASCII upper case equivalent.
662 ///
663 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
664 /// but non-ASCII letters are unchanged.
665 ///
666 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
667 ///
668 /// # Examples
669 ///
670 /// ```
671 /// let lowercase_a = 97u8;
672 ///
673 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
674 /// ```
675 ///
676 /// [`make_ascii_uppercase`]: Self::make_ascii_uppercase
677#[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"]
678 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
679 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
680 #[inline]
681pub const fn to_ascii_uppercase(&self) -> u8 {
682// Toggle the 6th bit if this is a lowercase letter
683*self ^ ((self.is_ascii_lowercase() as u8) * ASCII_CASE_MASK)
684 }
685686/// Makes a copy of the value in its ASCII lower case equivalent.
687 ///
688 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
689 /// but non-ASCII letters are unchanged.
690 ///
691 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
692 ///
693 /// # Examples
694 ///
695 /// ```
696 /// let uppercase_a = 65u8;
697 ///
698 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
699 /// ```
700 ///
701 /// [`make_ascii_lowercase`]: Self::make_ascii_lowercase
702#[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"]
703 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
704 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
705 #[inline]
706pub const fn to_ascii_lowercase(&self) -> u8 {
707// Set the 6th bit if this is an uppercase letter
708*self | (self.is_ascii_uppercase() as u8 * ASCII_CASE_MASK)
709 }
710711/// Assumes self is ascii
712#[inline]
713pub(crate) const fn ascii_change_case_unchecked(&self) -> u8 {
714*self ^ ASCII_CASE_MASK715 }
716717/// Checks that two values are an ASCII case-insensitive match.
718 ///
719 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
720 ///
721 /// # Examples
722 ///
723 /// ```
724 /// let lowercase_a = 97u8;
725 /// let uppercase_a = 65u8;
726 ///
727 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
728 /// ```
729#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
730 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
731 #[inline]
732pub const fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
733self.to_ascii_lowercase() == other.to_ascii_lowercase()
734 }
735736/// Converts this value to its ASCII upper case equivalent in-place.
737 ///
738 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
739 /// but non-ASCII letters are unchanged.
740 ///
741 /// To return a new uppercased value without modifying the existing one, use
742 /// [`to_ascii_uppercase`].
743 ///
744 /// # Examples
745 ///
746 /// ```
747 /// let mut byte = b'a';
748 ///
749 /// byte.make_ascii_uppercase();
750 ///
751 /// assert_eq!(b'A', byte);
752 /// ```
753 ///
754 /// [`to_ascii_uppercase`]: Self::to_ascii_uppercase
755#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
756 #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
757 #[inline]
758pub const fn make_ascii_uppercase(&mut self) {
759*self = self.to_ascii_uppercase();
760 }
761762/// Converts this value to its ASCII lower case equivalent in-place.
763 ///
764 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
765 /// but non-ASCII letters are unchanged.
766 ///
767 /// To return a new lowercased value without modifying the existing one, use
768 /// [`to_ascii_lowercase`].
769 ///
770 /// # Examples
771 ///
772 /// ```
773 /// let mut byte = b'A';
774 ///
775 /// byte.make_ascii_lowercase();
776 ///
777 /// assert_eq!(b'a', byte);
778 /// ```
779 ///
780 /// [`to_ascii_lowercase`]: Self::to_ascii_lowercase
781#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
782 #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
783 #[inline]
784pub const fn make_ascii_lowercase(&mut self) {
785*self = self.to_ascii_lowercase();
786 }
787788/// Checks if the value is an ASCII alphabetic character:
789 ///
790 /// - U+0041 'A' ..= U+005A 'Z', or
791 /// - U+0061 'a' ..= U+007A 'z'.
792 ///
793 /// # Examples
794 ///
795 /// ```
796 /// let uppercase_a = b'A';
797 /// let uppercase_g = b'G';
798 /// let a = b'a';
799 /// let g = b'g';
800 /// let zero = b'0';
801 /// let percent = b'%';
802 /// let space = b' ';
803 /// let lf = b'\n';
804 /// let esc = b'\x1b';
805 ///
806 /// assert!(uppercase_a.is_ascii_alphabetic());
807 /// assert!(uppercase_g.is_ascii_alphabetic());
808 /// assert!(a.is_ascii_alphabetic());
809 /// assert!(g.is_ascii_alphabetic());
810 /// assert!(!zero.is_ascii_alphabetic());
811 /// assert!(!percent.is_ascii_alphabetic());
812 /// assert!(!space.is_ascii_alphabetic());
813 /// assert!(!lf.is_ascii_alphabetic());
814 /// assert!(!esc.is_ascii_alphabetic());
815 /// ```
816#[must_use]
817 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
818 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
819 #[inline]
820pub const fn is_ascii_alphabetic(&self) -> bool {
821#[allow(non_exhaustive_omitted_patterns)] match *self {
b'A'..=b'Z' | b'a'..=b'z' => true,
_ => false,
}matches!(*self, b'A'..=b'Z' | b'a'..=b'z')822 }
823824/// Checks if the value is an ASCII uppercase character:
825 /// U+0041 'A' ..= U+005A 'Z'.
826 ///
827 /// # Examples
828 ///
829 /// ```
830 /// let uppercase_a = b'A';
831 /// let uppercase_g = b'G';
832 /// let a = b'a';
833 /// let g = b'g';
834 /// let zero = b'0';
835 /// let percent = b'%';
836 /// let space = b' ';
837 /// let lf = b'\n';
838 /// let esc = b'\x1b';
839 ///
840 /// assert!(uppercase_a.is_ascii_uppercase());
841 /// assert!(uppercase_g.is_ascii_uppercase());
842 /// assert!(!a.is_ascii_uppercase());
843 /// assert!(!g.is_ascii_uppercase());
844 /// assert!(!zero.is_ascii_uppercase());
845 /// assert!(!percent.is_ascii_uppercase());
846 /// assert!(!space.is_ascii_uppercase());
847 /// assert!(!lf.is_ascii_uppercase());
848 /// assert!(!esc.is_ascii_uppercase());
849 /// ```
850#[must_use]
851 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
852 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
853 #[inline]
854pub const fn is_ascii_uppercase(&self) -> bool {
855#[allow(non_exhaustive_omitted_patterns)] match *self {
b'A'..=b'Z' => true,
_ => false,
}matches!(*self, b'A'..=b'Z')856 }
857858/// Checks if the value is an ASCII lowercase character:
859 /// U+0061 'a' ..= U+007A 'z'.
860 ///
861 /// # Examples
862 ///
863 /// ```
864 /// let uppercase_a = b'A';
865 /// let uppercase_g = b'G';
866 /// let a = b'a';
867 /// let g = b'g';
868 /// let zero = b'0';
869 /// let percent = b'%';
870 /// let space = b' ';
871 /// let lf = b'\n';
872 /// let esc = b'\x1b';
873 ///
874 /// assert!(!uppercase_a.is_ascii_lowercase());
875 /// assert!(!uppercase_g.is_ascii_lowercase());
876 /// assert!(a.is_ascii_lowercase());
877 /// assert!(g.is_ascii_lowercase());
878 /// assert!(!zero.is_ascii_lowercase());
879 /// assert!(!percent.is_ascii_lowercase());
880 /// assert!(!space.is_ascii_lowercase());
881 /// assert!(!lf.is_ascii_lowercase());
882 /// assert!(!esc.is_ascii_lowercase());
883 /// ```
884#[must_use]
885 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
886 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
887 #[inline]
888pub const fn is_ascii_lowercase(&self) -> bool {
889#[allow(non_exhaustive_omitted_patterns)] match *self {
b'a'..=b'z' => true,
_ => false,
}matches!(*self, b'a'..=b'z')890 }
891892/// Checks if the value is an ASCII alphanumeric character:
893 ///
894 /// - U+0041 'A' ..= U+005A 'Z', or
895 /// - U+0061 'a' ..= U+007A 'z', or
896 /// - U+0030 '0' ..= U+0039 '9'.
897 ///
898 /// # Examples
899 ///
900 /// ```
901 /// let uppercase_a = b'A';
902 /// let uppercase_g = b'G';
903 /// let a = b'a';
904 /// let g = b'g';
905 /// let zero = b'0';
906 /// let percent = b'%';
907 /// let space = b' ';
908 /// let lf = b'\n';
909 /// let esc = b'\x1b';
910 ///
911 /// assert!(uppercase_a.is_ascii_alphanumeric());
912 /// assert!(uppercase_g.is_ascii_alphanumeric());
913 /// assert!(a.is_ascii_alphanumeric());
914 /// assert!(g.is_ascii_alphanumeric());
915 /// assert!(zero.is_ascii_alphanumeric());
916 /// assert!(!percent.is_ascii_alphanumeric());
917 /// assert!(!space.is_ascii_alphanumeric());
918 /// assert!(!lf.is_ascii_alphanumeric());
919 /// assert!(!esc.is_ascii_alphanumeric());
920 /// ```
921#[must_use]
922 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
923 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
924 #[inline]
925pub const fn is_ascii_alphanumeric(&self) -> bool {
926#[allow(non_exhaustive_omitted_patterns)] match *self {
b'0'..=b'9' => true,
_ => false,
}matches!(*self, b'0'..=b'9') | #[allow(non_exhaustive_omitted_patterns)] match *self {
b'A'..=b'Z' => true,
_ => false,
}matches!(*self, b'A'..=b'Z') | #[allow(non_exhaustive_omitted_patterns)] match *self {
b'a'..=b'z' => true,
_ => false,
}matches!(*self, b'a'..=b'z')927 }
928929/// Checks if the value is an ASCII decimal digit:
930 /// U+0030 '0' ..= U+0039 '9'.
931 ///
932 /// # Examples
933 ///
934 /// ```
935 /// let uppercase_a = b'A';
936 /// let uppercase_g = b'G';
937 /// let a = b'a';
938 /// let g = b'g';
939 /// let zero = b'0';
940 /// let percent = b'%';
941 /// let space = b' ';
942 /// let lf = b'\n';
943 /// let esc = b'\x1b';
944 ///
945 /// assert!(!uppercase_a.is_ascii_digit());
946 /// assert!(!uppercase_g.is_ascii_digit());
947 /// assert!(!a.is_ascii_digit());
948 /// assert!(!g.is_ascii_digit());
949 /// assert!(zero.is_ascii_digit());
950 /// assert!(!percent.is_ascii_digit());
951 /// assert!(!space.is_ascii_digit());
952 /// assert!(!lf.is_ascii_digit());
953 /// assert!(!esc.is_ascii_digit());
954 /// ```
955#[must_use]
956 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
957 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
958 #[inline]
959pub const fn is_ascii_digit(&self) -> bool {
960#[allow(non_exhaustive_omitted_patterns)] match *self {
b'0'..=b'9' => true,
_ => false,
}matches!(*self, b'0'..=b'9')961 }
962963/// Checks if the value is an ASCII octal digit:
964 /// U+0030 '0' ..= U+0037 '7'.
965 ///
966 /// # Examples
967 ///
968 /// ```
969 /// #![feature(is_ascii_octdigit)]
970 ///
971 /// let uppercase_a = b'A';
972 /// let a = b'a';
973 /// let zero = b'0';
974 /// let seven = b'7';
975 /// let nine = b'9';
976 /// let percent = b'%';
977 /// let lf = b'\n';
978 ///
979 /// assert!(!uppercase_a.is_ascii_octdigit());
980 /// assert!(!a.is_ascii_octdigit());
981 /// assert!(zero.is_ascii_octdigit());
982 /// assert!(seven.is_ascii_octdigit());
983 /// assert!(!nine.is_ascii_octdigit());
984 /// assert!(!percent.is_ascii_octdigit());
985 /// assert!(!lf.is_ascii_octdigit());
986 /// ```
987#[must_use]
988 #[unstable(feature = "is_ascii_octdigit", issue = "101288")]
989 #[inline]
990pub const fn is_ascii_octdigit(&self) -> bool {
991#[allow(non_exhaustive_omitted_patterns)] match *self {
b'0'..=b'7' => true,
_ => false,
}matches!(*self, b'0'..=b'7')992 }
993994/// Checks if the value is an ASCII hexadecimal digit:
995 ///
996 /// - U+0030 '0' ..= U+0039 '9', or
997 /// - U+0041 'A' ..= U+0046 'F', or
998 /// - U+0061 'a' ..= U+0066 'f'.
999 ///
1000 /// # Examples
1001 ///
1002 /// ```
1003 /// let uppercase_a = b'A';
1004 /// let uppercase_g = b'G';
1005 /// let a = b'a';
1006 /// let g = b'g';
1007 /// let zero = b'0';
1008 /// let percent = b'%';
1009 /// let space = b' ';
1010 /// let lf = b'\n';
1011 /// let esc = b'\x1b';
1012 ///
1013 /// assert!(uppercase_a.is_ascii_hexdigit());
1014 /// assert!(!uppercase_g.is_ascii_hexdigit());
1015 /// assert!(a.is_ascii_hexdigit());
1016 /// assert!(!g.is_ascii_hexdigit());
1017 /// assert!(zero.is_ascii_hexdigit());
1018 /// assert!(!percent.is_ascii_hexdigit());
1019 /// assert!(!space.is_ascii_hexdigit());
1020 /// assert!(!lf.is_ascii_hexdigit());
1021 /// assert!(!esc.is_ascii_hexdigit());
1022 /// ```
1023#[must_use]
1024 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1025 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1026 #[inline]
1027pub const fn is_ascii_hexdigit(&self) -> bool {
1028#[allow(non_exhaustive_omitted_patterns)] match *self {
b'0'..=b'9' => true,
_ => false,
}matches!(*self, b'0'..=b'9') | #[allow(non_exhaustive_omitted_patterns)] match *self {
b'A'..=b'F' => true,
_ => false,
}matches!(*self, b'A'..=b'F') | #[allow(non_exhaustive_omitted_patterns)] match *self {
b'a'..=b'f' => true,
_ => false,
}matches!(*self, b'a'..=b'f')1029 }
10301031/// Checks if the value is an ASCII punctuation or symbol character
1032 /// (i.e. not alphanumeric, whitespace, or control):
1033 ///
1034 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
1035 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
1036 /// - U+005B ..= U+0060 `` [ \ ] ^ _ ` ``, or
1037 /// - U+007B ..= U+007E `{ | } ~`
1038 ///
1039 /// # Examples
1040 ///
1041 /// ```
1042 /// let uppercase_a = b'A';
1043 /// let uppercase_g = b'G';
1044 /// let a = b'a';
1045 /// let g = b'g';
1046 /// let zero = b'0';
1047 /// let percent = b'%';
1048 /// let space = b' ';
1049 /// let lf = b'\n';
1050 /// let esc = b'\x1b';
1051 ///
1052 /// assert!(!uppercase_a.is_ascii_punctuation());
1053 /// assert!(!uppercase_g.is_ascii_punctuation());
1054 /// assert!(!a.is_ascii_punctuation());
1055 /// assert!(!g.is_ascii_punctuation());
1056 /// assert!(!zero.is_ascii_punctuation());
1057 /// assert!(percent.is_ascii_punctuation());
1058 /// assert!(!space.is_ascii_punctuation());
1059 /// assert!(!lf.is_ascii_punctuation());
1060 /// assert!(!esc.is_ascii_punctuation());
1061 /// ```
1062#[must_use]
1063 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1064 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1065 #[inline]
1066pub const fn is_ascii_punctuation(&self) -> bool {
1067#[allow(non_exhaustive_omitted_patterns)] match *self {
b'!'..=b'/' => true,
_ => false,
}matches!(*self, b'!'..=b'/')1068 | #[allow(non_exhaustive_omitted_patterns)] match *self {
b':'..=b'@' => true,
_ => false,
}matches!(*self, b':'..=b'@')1069 | #[allow(non_exhaustive_omitted_patterns)] match *self {
b'['..=b'`' => true,
_ => false,
}matches!(*self, b'['..=b'`')1070 | #[allow(non_exhaustive_omitted_patterns)] match *self {
b'{'..=b'~' => true,
_ => false,
}matches!(*self, b'{'..=b'~')1071 }
10721073/// Checks if the value is an ASCII graphic character
1074 /// (i.e. not whitespace or control):
1075 /// U+0021 '!' ..= U+007E '~'.
1076 ///
1077 /// # Examples
1078 ///
1079 /// ```
1080 /// let uppercase_a = b'A';
1081 /// let uppercase_g = b'G';
1082 /// let a = b'a';
1083 /// let g = b'g';
1084 /// let zero = b'0';
1085 /// let percent = b'%';
1086 /// let space = b' ';
1087 /// let lf = b'\n';
1088 /// let esc = b'\x1b';
1089 ///
1090 /// assert!(uppercase_a.is_ascii_graphic());
1091 /// assert!(uppercase_g.is_ascii_graphic());
1092 /// assert!(a.is_ascii_graphic());
1093 /// assert!(g.is_ascii_graphic());
1094 /// assert!(zero.is_ascii_graphic());
1095 /// assert!(percent.is_ascii_graphic());
1096 /// assert!(!space.is_ascii_graphic());
1097 /// assert!(!lf.is_ascii_graphic());
1098 /// assert!(!esc.is_ascii_graphic());
1099 /// ```
1100#[must_use]
1101 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1102 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1103 #[inline]
1104pub const fn is_ascii_graphic(&self) -> bool {
1105#[allow(non_exhaustive_omitted_patterns)] match *self {
b'!'..=b'~' => true,
_ => false,
}matches!(*self, b'!'..=b'~')1106 }
11071108/// Checks if the value is an ASCII whitespace character:
1109 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
1110 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
1111 ///
1112 /// **Warning:** Because the list above excludes U+000B VERTICAL TAB,
1113 /// `b.is_ascii_whitespace()` is **not** equivalent to `char::from(b).is_whitespace()`.
1114 ///
1115 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
1116 /// whitespace][infra-aw]. There are several other definitions in
1117 /// wide use. For instance, [the POSIX locale][pct] includes
1118 /// U+000B VERTICAL TAB as well as all the above characters,
1119 /// but—from the very same specification—[the default rule for
1120 /// "field splitting" in the Bourne shell][bfs] considers *only*
1121 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
1122 ///
1123 /// If you are writing a program that will process an existing
1124 /// file format, check what that format's definition of whitespace is
1125 /// before using this function.
1126 ///
1127 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
1128 /// [pct]: https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/V1_chap07.html#tag_07_03_01
1129 /// [bfs]: https://pubs.opengroup.org/onlinepubs/9799919799/utilities/V3_chap02.html#tag_19_06_05
1130 ///
1131 /// # Examples
1132 ///
1133 /// ```
1134 /// let uppercase_a = b'A';
1135 /// let uppercase_g = b'G';
1136 /// let a = b'a';
1137 /// let g = b'g';
1138 /// let zero = b'0';
1139 /// let percent = b'%';
1140 /// let space = b' ';
1141 /// let lf = b'\n';
1142 /// let esc = b'\x1b';
1143 ///
1144 /// assert!(!uppercase_a.is_ascii_whitespace());
1145 /// assert!(!uppercase_g.is_ascii_whitespace());
1146 /// assert!(!a.is_ascii_whitespace());
1147 /// assert!(!g.is_ascii_whitespace());
1148 /// assert!(!zero.is_ascii_whitespace());
1149 /// assert!(!percent.is_ascii_whitespace());
1150 /// assert!(space.is_ascii_whitespace());
1151 /// assert!(lf.is_ascii_whitespace());
1152 /// assert!(!esc.is_ascii_whitespace());
1153 /// ```
1154#[must_use]
1155 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1156 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1157 #[inline]
1158pub const fn is_ascii_whitespace(&self) -> bool {
1159#[allow(non_exhaustive_omitted_patterns)] match *self {
b'\t' | b'\n' | b'\x0C' | b'\r' | b' ' => true,
_ => false,
}matches!(*self, b'\t' | b'\n' | b'\x0C' | b'\r' | b' ')1160 }
11611162/// Checks if the value is an ASCII control character:
1163 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
1164 /// Note that most ASCII whitespace characters are control
1165 /// characters, but SPACE is not.
1166 ///
1167 /// # Examples
1168 ///
1169 /// ```
1170 /// let uppercase_a = b'A';
1171 /// let uppercase_g = b'G';
1172 /// let a = b'a';
1173 /// let g = b'g';
1174 /// let zero = b'0';
1175 /// let percent = b'%';
1176 /// let space = b' ';
1177 /// let lf = b'\n';
1178 /// let esc = b'\x1b';
1179 ///
1180 /// assert!(!uppercase_a.is_ascii_control());
1181 /// assert!(!uppercase_g.is_ascii_control());
1182 /// assert!(!a.is_ascii_control());
1183 /// assert!(!g.is_ascii_control());
1184 /// assert!(!zero.is_ascii_control());
1185 /// assert!(!percent.is_ascii_control());
1186 /// assert!(!space.is_ascii_control());
1187 /// assert!(lf.is_ascii_control());
1188 /// assert!(esc.is_ascii_control());
1189 /// ```
1190#[must_use]
1191 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1192 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1193 #[inline]
1194pub const fn is_ascii_control(&self) -> bool {
1195#[allow(non_exhaustive_omitted_patterns)] match *self {
b'\0'..=b'\x1F' | b'\x7F' => true,
_ => false,
}matches!(*self, b'\0'..=b'\x1F' | b'\x7F')1196 }
11971198/// Returns an iterator that produces an escaped version of a `u8`,
1199 /// treating it as an ASCII character.
1200 ///
1201 /// The behavior is identical to [`ascii::escape_default`].
1202 ///
1203 /// # Examples
1204 ///
1205 /// ```
1206 /// assert_eq!("0", b'0'.escape_ascii().to_string());
1207 /// assert_eq!("\\t", b'\t'.escape_ascii().to_string());
1208 /// assert_eq!("\\r", b'\r'.escape_ascii().to_string());
1209 /// assert_eq!("\\n", b'\n'.escape_ascii().to_string());
1210 /// assert_eq!("\\'", b'\''.escape_ascii().to_string());
1211 /// assert_eq!("\\\"", b'"'.escape_ascii().to_string());
1212 /// assert_eq!("\\\\", b'\\'.escape_ascii().to_string());
1213 /// assert_eq!("\\x9d", b'\x9d'.escape_ascii().to_string());
1214 /// ```
1215#[must_use = "this returns the escaped byte as an iterator, \
1216 without modifying the original"]
1217 #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
1218 #[inline]
1219pub fn escape_ascii(self) -> ascii::EscapeDefault {
1220 ascii::escape_default(self)
1221 }
12221223#[inline]
1224pub(crate) const fn is_utf8_char_boundary(self) -> bool {
1225// This is bit magic equivalent to: b < 128 || b >= 192
1226(selfas i8) >= -0x40
1227}
1228}
12291230impl u16 {
1231/// The smallest value that can be represented by this integer type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(u16::MIN, 0);"]
/// ```
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MIN: Self = 0;
/// The largest value that can be represented by this integer type
#[doc = "(2<sup>16</sup> − 1)."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(u16::MAX, 65535);"]
/// ```
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MAX: Self = !0;
/// The size of this integer type in bits.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(u16::BITS, 16);"]
/// ```
#[stable(feature = "int_bits_const", since = "1.53.0")]
pub const BITS: u32 = Self::MAX.count_ones();
/// Returns the number of ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 0b01001100u16;"]
/// assert_eq!(n.count_ones(), 3);
///
#[doc = "let max = u16::MAX;"]
#[doc = "assert_eq!(max.count_ones(), 16);"]
///
#[doc = "let zero = 0u16;"]
/// assert_eq!(zero.count_ones(), 0);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[doc(alias = "popcount")]
#[doc(alias = "popcnt")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn count_ones(self) -> u32 { return intrinsics::ctpop(self); }
/// Returns the number of zeros in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let zero = 0u16;"]
#[doc = "assert_eq!(zero.count_zeros(), 16);"]
///
#[doc = "let max = u16::MAX;"]
/// assert_eq!(max.count_zeros(), 0);
/// ```
///
/// This is heavily dependent on the width of the type, and thus
/// might give surprising results depending on type inference:
/// ```
/// # fn foo(_: u8) {}
/// # fn bar(_: u16) {}
/// let lucky = 7;
/// foo(lucky);
/// assert_eq!(lucky.count_zeros(), 5);
/// assert_eq!(lucky.count_ones(), 3);
///
/// let lucky = 7;
/// bar(lucky);
/// assert_eq!(lucky.count_zeros(), 13);
/// assert_eq!(lucky.count_ones(), 3);
/// ```
/// You might want to use [`Self::count_ones`] instead, or emphasize
/// the type you're using in the call rather than method syntax:
/// ```
/// let small = 1;
#[doc = "assert_eq!(u16::count_zeros(small), 15);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn count_zeros(self) -> u32 { (!self).count_ones() }
/// Returns the number of leading zeros in the binary representation of `self`.
///
/// Depending on what you're doing with the value, you might also be interested in the
/// [`ilog2`] function which returns a consistent number, even if the type widens.
///
/// # Examples
///
/// ```
#[doc = "let n = u16::MAX >> 2;"]
/// assert_eq!(n.leading_zeros(), 2);
///
#[doc = "let zero = 0u16;"]
#[doc = "assert_eq!(zero.leading_zeros(), 16);"]
///
#[doc = "let max = u16::MAX;"]
/// assert_eq!(max.leading_zeros(), 0);
/// ```
#[doc = "[`ilog2`]: u16::ilog2"]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn leading_zeros(self) -> u32 {
return intrinsics::ctlz(self as u16);
}
/// Returns the number of trailing zeros in the binary representation
/// of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 0b0101000u16;"]
/// assert_eq!(n.trailing_zeros(), 3);
///
#[doc = "let zero = 0u16;"]
#[doc = "assert_eq!(zero.trailing_zeros(), 16);"]
///
#[doc = "let max = u16::MAX;"]
#[doc = "assert_eq!(max.trailing_zeros(), 0);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn trailing_zeros(self) -> u32 { return intrinsics::cttz(self); }
/// Returns the number of leading ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = !(u16::MAX >> 2);"]
/// assert_eq!(n.leading_ones(), 2);
///
#[doc = "let zero = 0u16;"]
/// assert_eq!(zero.leading_ones(), 0);
///
#[doc = "let max = u16::MAX;"]
#[doc = "assert_eq!(max.leading_ones(), 16);"]
/// ```
#[stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn leading_ones(self) -> u32 { (!self).leading_zeros() }
/// Returns the number of trailing ones in the binary representation
/// of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 0b1010111u16;"]
/// assert_eq!(n.trailing_ones(), 3);
///
#[doc = "let zero = 0u16;"]
/// assert_eq!(zero.trailing_ones(), 0);
///
#[doc = "let max = u16::MAX;"]
#[doc = "assert_eq!(max.trailing_ones(), 16);"]
/// ```
#[stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn trailing_ones(self) -> u32 { (!self).trailing_zeros() }
/// Returns the minimum number of bits required to represent `self`.
///
/// This method returns zero if `self` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0_u16.bit_width(), 0);"]
#[doc = "assert_eq!(0b111_u16.bit_width(), 3);"]
#[doc = "assert_eq!(0b1110_u16.bit_width(), 4);"]
#[doc = "assert_eq!(u16::MAX.bit_width(), 16);"]
/// ```
#[stable(feature = "uint_bit_width", since = "1.97.0")]
#[rustc_const_stable(feature = "uint_bit_width", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn bit_width(self) -> u32 { Self::BITS - self.leading_zeros() }
/// Returns `self` with only the most significant bit set, or `0` if
/// the input is `0`.
///
/// # Examples
///
/// ```
#[doc = "let n: u16 = 0b_01100100;"]
///
/// assert_eq!(n.isolate_highest_one(), 0b_01000000);
#[doc = "assert_eq!(0_u16.isolate_highest_one(), 0);"]
/// ```
#[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn isolate_highest_one(self) -> Self {
self &
(((1 as u16) << (<u16>::BITS - 1)).wrapping_shr(self.leading_zeros()))
}
/// Returns `self` with only the least significant bit set, or `0` if
/// the input is `0`.
///
/// # Examples
///
/// ```
#[doc = "let n: u16 = 0b_01100100;"]
///
/// assert_eq!(n.isolate_lowest_one(), 0b_00000100);
#[doc = "assert_eq!(0_u16.isolate_lowest_one(), 0);"]
/// ```
#[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn isolate_lowest_one(self) -> Self { self & self.wrapping_neg() }
/// Returns the index of the highest bit set to one in `self`, or `None`
/// if `self` is `0`.
///
/// Note that this is equivalent to [`checked_ilog2`](Self::checked_ilog2).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0b0_u16.highest_one(), None);"]
#[doc = "assert_eq!(0b1_u16.highest_one(), Some(0));"]
#[doc = "assert_eq!(0b1_0000_u16.highest_one(), Some(4));"]
#[doc = "assert_eq!(0b1_1111_u16.highest_one(), Some(4));"]
/// ```
#[stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn highest_one(self) -> Option<u32> {
match NonZero::new(self) {
Some(v) => Some(v.highest_one()),
None => None,
}
}
/// Returns the index of the lowest bit set to one in `self`, or `None`
/// if `self` is `0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0b0_u16.lowest_one(), None);"]
#[doc = "assert_eq!(0b1_u16.lowest_one(), Some(0));"]
#[doc = "assert_eq!(0b1_0000_u16.lowest_one(), Some(4));"]
#[doc = "assert_eq!(0b1_1111_u16.lowest_one(), Some(0));"]
/// ```
#[stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn lowest_one(self) -> Option<u32> {
match NonZero::new(self) {
Some(v) => Some(v.lowest_one()),
None => None,
}
}
/// Returns the bit pattern of `self` reinterpreted as a signed integer of the same size.
///
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
/// the same.
///
/// # Examples
///
/// ```
#[doc = "let n = u16::MAX;"]
///
#[doc = "assert_eq!(n.cast_signed(), -1i16);"]
/// ```
#[stable(feature = "integer_sign_cast", since = "1.87.0")]
#[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_signed(self) -> i16 { self as i16 }
/// Saturating conversion of `self` to a signed integer of the same size.
///
/// The signed integer's maximum value is returned if `self` is larger
/// than the maximum positive value representable by the signed integer.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`checked_cast_signed`](Self::checked_cast_signed),
/// or [`strict_cast_signed`](Self::strict_cast_signed).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = u16::MAX;"]
///
#[doc = "assert_eq!(n.saturating_cast_signed(), i16::MAX);"]
#[doc = "assert_eq!(64u16.saturating_cast_signed(), 64i16);"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_cast_signed(self) -> i16 {
if self <= <i16>::MAX.cast_unsigned() {
self.cast_signed()
} else { <i16>::MAX }
}
/// Checked conversion of `self` to a signed integer of the same size,
/// returning `None` if `self` is larger than the signed integer's
/// maximum value.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`saturating_cast_signed`](Self::saturating_cast_signed),
/// or [`strict_cast_signed`](Self::strict_cast_signed).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = u16::MAX;"]
///
#[doc = "assert_eq!(n.checked_cast_signed(), None);"]
#[doc = "assert_eq!(64u16.checked_cast_signed(), Some(64i16));"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn checked_cast_signed(self) -> Option<i16> {
if self <= <i16>::MAX.cast_unsigned() {
Some(self.cast_signed())
} else { None }
}
/// Strict conversion of `self` to a signed integer of the same size,
/// which panics if `self` is larger than the signed integer's maximum
/// value.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`checked_cast_signed`](Self::checked_cast_signed),
/// or [`saturating_cast_signed`](Self::saturating_cast_signed).
///
/// # Examples
///
/// ```should_panic
/// #![feature(integer_cast_extras)]
#[doc = "let _ = u16::MAX.strict_cast_signed();"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_cast_signed(self) -> i16 {
match self.checked_cast_signed() {
Some(n) => n,
None => imp::overflow_panic::cast_integer(),
}
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `<<` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0xa003u16;"]
#[doc = "let m = 0x3a;"]
///
#[doc = "assert_eq!(n.rotate_left(4), m);"]
#[doc = "assert_eq!(n.rotate_left(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
pub const fn rotate_left(self, n: u32) -> Self {
return intrinsics::rotate_left(self, n);
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `>>` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x3au16;"]
#[doc = "let m = 0xa003;"]
///
#[doc = "assert_eq!(n.rotate_right(4), m);"]
#[doc = "assert_eq!(n.rotate_right(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
pub const fn rotate_right(self, n: u32) -> Self {
return intrinsics::rotate_right(self, n);
}
/// Performs a left funnel shift (concatenates `self` with `rhs`, with `self`
/// making up the most significant half, then shifts the combined value left
/// by `n`, and most significant half is extracted to produce the result).
///
/// Please note this isn't the same operation as the `<<` shifting operator or
/// [`rotate_left`](Self::rotate_left), although `a.funnel_shl(a, n)` is *equivalent*
/// to `a.rotate_left(n)`.
///
/// # Panics
///
/// If `n` is greater than or equal to the number of bits in `self`
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(funnel_shifts)]
#[doc = "let a = 0xa003u16;"]
#[doc = "let b = 0x2deu16;"]
#[doc = "let m = 0x30;"]
///
#[doc = "assert_eq!(a.funnel_shl(b, 4), m);"]
/// ```
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn funnel_shl(self, rhs: Self, n: u32) -> Self {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift left with overflow"));
}
};
unsafe { self.unchecked_funnel_shl(rhs, n) }
}
/// Performs a right funnel shift (concatenates `self` and `rhs`, with `self`
/// making up the most significant half, then shifts the combined value right
/// by `n`, and least significant half is extracted to produce the result).
///
/// Please note this isn't the same operation as the `>>` shifting operator or
/// [`rotate_right`](Self::rotate_right), although `a.funnel_shr(a, n)` is *equivalent*
/// to `a.rotate_right(n)`.
///
/// # Panics
///
/// If `n` is greater than or equal to the number of bits in `self`
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(funnel_shifts)]
#[doc = "let a = 0xa003u16;"]
#[doc = "let b = 0x2deu16;"]
#[doc = "let m = 0x302d;"]
///
#[doc = "assert_eq!(a.funnel_shr(b, 4), m);"]
/// ```
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn funnel_shr(self, rhs: Self, n: u32) -> Self {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift right with overflow"));
}
};
unsafe { self.unchecked_funnel_shr(rhs, n) }
}
/// Unchecked funnel shift left.
///
/// # Safety
///
/// This results in undefined behavior if `n` is greater than or equal to
#[doc = "`u16::BITS`,"]
/// i.e. when [`funnel_shl`](Self::funnel_shl) would panic.
///
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_funnel_shl(self, low: Self, n: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(n: u32) {
if !(n < <u16>::BITS) {
let msg =
"unsafe precondition(s) violated: u16::unchecked_funnel_shl cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(n); }
};
unsafe { intrinsics::unchecked_funnel_shl(self, low, n) }
}
/// Unchecked funnel shift right.
///
/// # Safety
///
/// This results in undefined behavior if `n` is greater than or equal to
#[doc = "`u16::BITS`,"]
/// i.e. when [`funnel_shr`](Self::funnel_shr) would panic.
///
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_funnel_shr(self, low: Self, n: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(n: u32) {
if !(n < <u16>::BITS) {
let msg =
"unsafe precondition(s) violated: u16::unchecked_funnel_shr cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(n); }
};
unsafe { intrinsics::unchecked_funnel_shr(self, low, n) }
}
/// Performs a carry-less multiplication, returning the lower bits.
///
/// This operation is similar to long multiplication in base 2, except that exclusive or is
/// used instead of addition. The implementation is equivalent to:
///
/// ```no_run
#[doc = "pub fn carryless_mul(lhs: u16, rhs: u16) -> u16{"]
/// let mut retval = 0;
#[doc = " for i in 0..u16::BITS {"]
/// if (rhs >> i) & 1 != 0 {
/// // long multiplication would use +=
/// retval ^= lhs << i;
/// }
/// }
/// retval
/// }
/// ```
///
/// The actual implementation is more efficient, and on some platforms lowers directly to a
/// dedicated instruction.
///
/// # Uses
///
/// Carryless multiplication can be used to turn a bitmask of quote characters into a
/// bit mask of characters surrounded by quotes:
///
/// ```no_run
/// r#"abc xxx "foobar" zzz "a"!"#; // input string
/// 0b0000000010000001000001010; // quote_mask
/// 0b0000000001111110000000100; // quote_mask.carryless_mul(!0) & !quote_mask
/// ```
///
/// Another use is in cryptography, where carryless multiplication allows for efficient
/// implementations of polynomial multiplication in `GF(2)[X]`, the polynomial ring
/// over `GF(2)`.
///
/// # Examples
///
/// ```
/// #![feature(uint_carryless_mul)]
///
#[doc = "let a = 0x9012u16;"]
#[doc = "let b = 0xcd34u16;"]
///
#[doc = "assert_eq!(a.carryless_mul(b), 0x928);"]
/// ```
#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
#[doc(alias = "clmul")]
#[unstable(feature = "uint_carryless_mul", issue = "152080")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn carryless_mul(self, rhs: Self) -> Self {
intrinsics::carryless_mul(self, rhs)
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1234u16;"]
/// let m = n.swap_bytes();
///
#[doc = "assert_eq!(m, 0x3412);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn swap_bytes(self) -> Self {
intrinsics::bswap(self as u16) as Self
}
/// Returns an integer with the bit locations specified by `mask` packed
/// contiguously into the least significant bits of the result.
/// ```
/// #![feature(uint_gather_scatter_bits)]
#[doc = "let n: u16 = 0b1011_1100;"]
///
/// assert_eq!(n.extract_bits(0b0010_0100), 0b0000_0011);
/// assert_eq!(n.extract_bits(0xF0), 0b0000_1011);
/// ```
#[doc(alias = "pext")]
#[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn extract_bits(self, mask: Self) -> Self {
imp::int_bits::u16::extract_impl(self as u16, mask as u16) as u16
}
/// Returns an integer with the least significant bits of `self`
/// distributed to the bit locations specified by `mask`.
/// ```
/// #![feature(uint_gather_scatter_bits)]
#[doc = "let n: u16 = 0b1010_1101;"]
///
/// assert_eq!(n.deposit_bits(0b0101_0101), 0b0101_0001);
/// assert_eq!(n.deposit_bits(0xF0), 0b1101_0000);
/// ```
#[doc(alias = "pdep")]
#[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn deposit_bits(self, mask: Self) -> Self {
imp::int_bits::u16::deposit_impl(self as u16, mask as u16) as u16
}
/// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
/// second least-significant bit becomes second most-significant bit, etc.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1234u16;"]
/// let m = n.reverse_bits();
///
#[doc = "assert_eq!(m, 0x2c48);"]
#[doc = "assert_eq!(0, 0u16.reverse_bits());"]
/// ```
#[stable(feature = "reverse_bits", since = "1.37.0")]
#[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn reverse_bits(self) -> Self {
intrinsics::bitreverse(self as u16) as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au16;"]
///
/// if cfg!(target_endian = "big") {
#[doc = " assert_eq!(u16::from_be(n), n)"]
/// } else {
#[doc = " assert_eq!(u16::from_be(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use]
#[inline(always)]
pub const fn from_be(x: Self) -> Self { x.swap_bytes() }
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au16;"]
///
/// if cfg!(target_endian = "little") {
#[doc = " assert_eq!(u16::from_le(n), n)"]
/// } else {
#[doc = " assert_eq!(u16::from_le(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use]
#[inline(always)]
pub const fn from_le(x: Self) -> Self { x }
/// Converts `self` to big endian from the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au16;"]
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn to_be(self) -> Self { self.swap_bytes() }
/// Converts `self` to little endian from the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au16;"]
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn to_le(self) -> Self { self }
/// Checked integer addition. Computes `self + rhs`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((u16::MAX - 2).checked_add(1), Some(u16::MAX - 1));"]
#[doc = "assert_eq!((u16::MAX - 2).checked_add(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(intrinsics::add_with_overflow(self, rhs).1) {
None
} else { Some(unsafe { intrinsics::unchecked_add(self, rhs) }) }
}
/// Strict integer addition. Computes `self + rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((u16::MAX - 2).strict_add(1), u16::MAX - 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (u16::MAX - 2).strict_add(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_add(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Unchecked integer addition. Computes `self + rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_add(y)` is semantically equivalent to calling
/// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_add`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self + rhs > u16::MAX`,"]
/// i.e. when [`checked_add`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_add`]: u16::checked_add"]
#[doc = "[`wrapping_add`]: u16::wrapping_add"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u16, rhs: u16) {
if !!lhs.overflowing_add(rhs).1 {
let msg =
"unsafe precondition(s) violated: u16::unchecked_add cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_add(self, rhs) }
}
/// Checked addition with a signed integer. Computes `self + rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u16.checked_add_signed(2), Some(3));"]
#[doc = "assert_eq!(1u16.checked_add_signed(-2), None);"]
#[doc = "assert_eq!((u16::MAX - 2).checked_add_signed(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add_signed(self, rhs: i16) -> Option<Self> {
let (a, b) = self.overflowing_add_signed(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict addition with a signed integer. Computes `self + rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u16.strict_add_signed(2), 3);"]
/// ```
///
/// The following panic because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1u16.strict_add_signed(-2);"]
/// ```
///
/// ```should_panic
#[doc = "let _ = (u16::MAX - 2).strict_add_signed(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add_signed(self, rhs: i16) -> Self {
let (a, b) = self.overflowing_add_signed(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Checked integer subtraction. Computes `self - rhs`, returning
/// `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u16.checked_sub(1), Some(0));"]
#[doc = "assert_eq!(0u16.checked_sub(1), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
if self < rhs {
None
} else { Some(unsafe { intrinsics::unchecked_sub(self, rhs) }) }
}
/// Strict integer subtraction. Computes `self - rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u16.strict_sub(1), 0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0u16.strict_sub(1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_sub(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
/// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_sub`].
///
/// If you find yourself writing code like this:
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if foo >= bar {
/// // SAFETY: just checked it will not overflow
/// let diff = unsafe { foo.unchecked_sub(bar) };
/// // ... use diff ...
/// }
/// ```
///
/// Consider changing it to
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if let Some(diff) = foo.checked_sub(bar) {
/// // ... use diff ...
/// }
/// ```
///
/// As that does exactly the same thing -- including telling the optimizer
/// that the subtraction cannot overflow -- but avoids needing `unsafe`.
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self - rhs < u16::MIN`,"]
/// i.e. when [`checked_sub`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_sub`]: u16::checked_sub"]
#[doc = "[`wrapping_sub`]: u16::wrapping_sub"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u16, rhs: u16) {
if !!lhs.overflowing_sub(rhs).1 {
let msg =
"unsafe precondition(s) violated: u16::unchecked_sub cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_sub(self, rhs) }
}
/// Checked subtraction with a signed integer. Computes `self - rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u16.checked_sub_signed(2), None);"]
#[doc = "assert_eq!(1u16.checked_sub_signed(-2), Some(3));"]
#[doc = "assert_eq!((u16::MAX - 2).checked_sub_signed(-4), None);"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub_signed(self, rhs: i16) -> Option<Self> {
let (res, overflow) = self.overflowing_sub_signed(rhs);
if !overflow { Some(res) } else { None }
}
/// Strict subtraction with a signed integer. Computes `self - rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3u16.strict_sub_signed(2), 1);"]
/// ```
///
/// The following panic because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1u16.strict_sub_signed(2);"]
/// ```
///
/// ```should_panic
#[doc = "let _ = (u16::MAX).strict_sub_signed(-1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub_signed(self, rhs: i16) -> Self {
let (a, b) = self.overflowing_sub_signed(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
#[doc =
"Checked integer subtraction. Computes `self - rhs` and checks if the result fits into an [`i16`], returning `None` if overflow occurred."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10u16.checked_signed_diff(2), Some(8));"]
#[doc = "assert_eq!(2u16.checked_signed_diff(10), Some(-8));"]
#[doc = "assert_eq!(u16::MAX.checked_signed_diff(i16::MAX as u16), None);"]
#[doc =
"assert_eq!((i16::MAX as u16).checked_signed_diff(u16::MAX), Some(i16::MIN));"]
#[doc = "assert_eq!((i16::MAX as u16 + 1).checked_signed_diff(0), None);"]
#[doc = "assert_eq!(u16::MAX.checked_signed_diff(u16::MAX), Some(0));"]
/// ```
#[stable(feature = "unsigned_signed_diff", since = "1.91.0")]
#[rustc_const_stable(feature = "unsigned_signed_diff", since = "1.91.0")]
#[inline]
pub const fn checked_signed_diff(self, rhs: Self) -> Option<i16> {
let res = self.wrapping_sub(rhs) as i16;
let overflow = (self >= rhs) == (res < 0);
if !overflow { Some(res) } else { None }
}
/// Checked integer multiplication. Computes `self * rhs`, returning
/// `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u16.checked_mul(1), Some(5));"]
#[doc = "assert_eq!(u16::MAX.checked_mul(2), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer multiplication. Computes `self * rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u16.strict_mul(1), 5);"]
/// ```
///
/// The following panics because of overflow:
///
/// ``` should_panic
#[doc = "let _ = u16::MAX.strict_mul(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_mul(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_mul(rhs);
if b { imp::overflow_panic::mul() } else { a }
}
/// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
/// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_mul`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self * rhs > u16::MAX`,"]
/// i.e. when [`checked_mul`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_mul`]: u16::checked_mul"]
#[doc = "[`wrapping_mul`]: u16::wrapping_mul"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u16, rhs: u16) {
if !!lhs.overflowing_mul(rhs).1 {
let msg =
"unsafe precondition(s) violated: u16::unchecked_mul cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_mul(self, rhs) }
}
/// Checked integer division. Computes `self / rhs`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128u16.checked_div(2), Some(64));"]
#[doc = "assert_eq!(1u16.checked_div(0), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(unsafe { intrinsics::unchecked_div(self, rhs) }) }
}
/// Strict integer division. Computes `self / rhs`.
///
/// Strict division on unsigned types is just normal division. There's no
/// way overflow could ever happen. This function exists so that all
/// operations are accounted for in the strict operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u16.strict_div(10), 10);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1u16).strict_div(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_div(self, rhs: Self) -> Self { self / rhs }
/// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128u16.checked_div_euclid(2), Some(64));"]
#[doc = "assert_eq!(1u16.checked_div_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(self.div_euclid(rhs)) }
}
/// Strict Euclidean division. Computes `self.div_euclid(rhs)`.
///
/// Strict division on unsigned types is just normal division. There's no
/// way overflow could ever happen. This function exists so that all
/// operations are accounted for in the strict operations. Since, for the
/// positive integers, all common definitions of division are equal, this
/// is exactly equal to `self.strict_div(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u16.strict_div_euclid(10), 10);"]
/// ```
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1u16).strict_div_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Checked integer division without remainder. Computes `self / rhs`,
/// returning `None` if `rhs == 0` or if `self % rhs != 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64u16.checked_div_exact(2), Some(32));"]
#[doc = "assert_eq!(64u16.checked_div_exact(32), Some(2));"]
#[doc = "assert_eq!(64u16.checked_div_exact(0), None);"]
#[doc = "assert_eq!(65u16.checked_div_exact(2), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_exact(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else {
unsafe {
if intrinsics::unlikely(intrinsics::unchecked_rem(self, rhs) != 0)
{
None
} else { Some(intrinsics::exact_div(self, rhs)) }
}
}
}
/// Integer division without remainder. Computes `self / rhs`, returning `None` if `self % rhs != 0`.
///
/// # Panics
///
/// This function will panic if `rhs == 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64u16.div_exact(2), Some(32));"]
#[doc = "assert_eq!(64u16.div_exact(32), Some(2));"]
#[doc = "assert_eq!(65u16.div_exact(2), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn div_exact(self, rhs: Self) -> Option<Self> {
if self % rhs != 0 { None } else { Some(self / rhs) }
}
/// Unchecked integer division without remainder. Computes `self / rhs`.
///
/// # Safety
///
/// This results in undefined behavior when `rhs == 0` or `self % rhs != 0`,
/// i.e. when [`checked_div_exact`](Self::checked_div_exact) would return `None`.
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_div_exact(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u16, rhs: u16) {
if !(rhs > 0 && lhs % rhs == 0) {
let msg =
"unsafe precondition(s) violated: u16::unchecked_div_exact divide by zero or leave a remainder\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::exact_div(self, rhs) }
}
/// Checked integer remainder. Computes `self % rhs`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u16.checked_rem(2), Some(1));"]
#[doc = "assert_eq!(5u16.checked_rem(0), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(unsafe { intrinsics::unchecked_rem(self, rhs) }) }
}
/// Strict integer remainder. Computes `self % rhs`.
///
/// Strict remainder calculation on unsigned types is just the regular
/// remainder calculation. There's no way overflow could ever happen.
/// This function exists so that all operations are accounted for in the
/// strict operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u16.strict_rem(10), 0);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5u16.strict_rem(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_rem(self, rhs: Self) -> Self { self % rhs }
/// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u16.checked_rem_euclid(2), Some(1));"]
#[doc = "assert_eq!(5u16.checked_rem_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(self.rem_euclid(rhs)) }
}
/// Strict Euclidean modulo. Computes `self.rem_euclid(rhs)`.
///
/// Strict modulo calculation on unsigned types is just the regular
/// remainder calculation. There's no way overflow could ever happen.
/// This function exists so that all operations are accounted for in the
/// strict operations. Since, for the positive integers, all common
/// definitions of division are equal, this is exactly equal to
/// `self.strict_rem(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u16.strict_rem_euclid(10), 0);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5u16.strict_rem_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Same value as `self | other`, but UB if any bit position is set in both inputs.
///
/// This is a situational micro-optimization for places where you'd rather
/// use addition on some platforms and bitwise or on other platforms, based
/// on exactly which instructions combine better with whatever else you're
/// doing. Note that there's no reason to bother using this for places
/// where it's clear from the operations involved that they can't overlap.
/// For example, if you're combining `u16`s into a `u32` with
/// `((a as u32) << 16) | (b as u32)`, that's fine, as the backend will
/// know those sides of the `|` are disjoint without needing help.
///
/// # Examples
///
/// ```
/// #![feature(disjoint_bitor)]
///
/// // SAFETY: `1` and `4` have no bits in common.
/// unsafe {
#[doc = " assert_eq!(1_u16.unchecked_disjoint_bitor(4), 5);"]
/// }
/// ```
///
/// # Safety
///
/// Requires that `(self & other) == 0`, otherwise it's immediate UB.
///
/// Equivalently, requires that `(self | other) == (self + other)`.
#[unstable(feature = "disjoint_bitor", issue = "135758")]
#[rustc_const_unstable(feature = "disjoint_bitor", issue = "135758")]
#[inline]
pub const unsafe fn unchecked_disjoint_bitor(self, other: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u16, rhs: u16) {
if !((lhs & rhs) == 0) {
let msg =
"unsafe precondition(s) violated: u16::unchecked_disjoint_bitor cannot have overlapping bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, other);
}
};
unsafe { intrinsics::disjoint_bitor(self, other) }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// This method might not be optimized owing to implementation details;
/// [`ilog2`](Self::ilog2) can produce results more efficiently for base 2,
/// and [`ilog10`](Self::ilog10) can produce results more efficiently for base 10.
///
/// # Panics
///
/// This function will panic if `self` is zero, or if `base` is less than 2.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u16.ilog(5), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog(self, base: Self) -> u32 {
if !(base >= 2) {
{
crate::panicking::panic_fmt(format_args!("base of integer logarithm must be at least 2"));
}
};
if let Some(log) = self.checked_ilog(base) {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the base 2 logarithm of the number, rounded down.
///
/// # Panics
///
/// This function will panic if `self` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u16.ilog2(), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog2(self) -> u32 {
if let Some(log) = self.checked_ilog2() {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// # Panics
///
/// This function will panic if `self` is zero.
///
/// # Example
///
/// ```
#[doc = "assert_eq!(10u16.ilog10(), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog10(self) -> u32 {
if let Some(log) = self.checked_ilog10() {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// Returns `None` if the number is zero, or if the base is not at least 2.
///
/// This method might not be optimized owing to implementation details;
/// `checked_ilog2` can produce results more efficiently for base 2, and
/// `checked_ilog10` can produce results more efficiently for base 10.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u16.checked_ilog(5), Some(1));"]
#[doc = "assert_eq!(4u16.checked_ilog(5), Some(0));"]
#[doc = "assert_eq!(5u16.checked_ilog(0), None);"]
#[doc = "assert_eq!(5u16.checked_ilog(1), None);"]
#[doc = "assert_eq!(0u16.checked_ilog(1), None);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog(self, base: Self) -> Option<u32> {
if core::intrinsics::is_val_statically_known(base) {
if base.is_power_of_two() && base > 1 {
let k = base.ilog2();
return Some(match self.checked_ilog2() {
Some(x) => x,
None => return None,
} / k);
}
if base == 10 { return self.checked_ilog10(); }
}
if self <= 0 || base <= 1 {
None
} else if self < base {
Some(0)
} else {
let mut n = 1;
let mut r = base;
if Self::BITS == 128 {
n = self.ilog2() / (base.ilog2() + 1);
r = base.pow(n);
}
while r <= self / base { n += 1; r *= base; }
Some(n)
}
}
/// Returns the base 2 logarithm of the number, rounded down.
///
/// Returns `None` if the number is zero.
///
/// Note that this is equivalent to [`highest_one`](Self::highest_one).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u16.checked_ilog2(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog2(self) -> Option<u32> {
match NonZero::new(self) { Some(x) => Some(x.ilog2()), None => None, }
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// Returns `None` if the number is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10u16.checked_ilog10(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog10(self) -> Option<u32> {
match NonZero::new(self) { Some(x) => Some(x.ilog10()), None => None, }
}
/// Checked negation. Computes `-self`, returning `None` unless `self ==
/// 0`.
///
/// Note that negating any positive integer will overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0u16.checked_neg(), Some(0));"]
#[doc = "assert_eq!(1u16.checked_neg(), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_neg(self) -> Option<Self> {
let (a, b) = self.overflowing_neg();
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict negation. Computes `-self`, panicking unless `self ==
/// 0`.
///
/// Note that negating any positive integer will overflow.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0u16.strict_neg(), 0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1u16.strict_neg();"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_neg(self) -> Self {
let (a, b) = self.overflowing_neg();
if b { imp::overflow_panic::neg() } else { a }
}
/// Checked shift left. Computes `self << rhs`, returning `None`
/// if `rhs` is larger than or equal to the number of bits in `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1u16.checked_shl(4), Some(0x10));"]
#[doc = "assert_eq!(0x10u16.checked_shl(129), None);"]
#[doc = "assert_eq!(0x10u16.checked_shl(15), Some(0));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
if rhs < Self::BITS {
Some(unsafe { self.unchecked_shl(rhs) })
} else { None }
}
/// Strict shift left. Computes `self << rhs`, panicking if `rhs` is larger
/// than or equal to the number of bits in `self`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1u16.strict_shl(4), 0x10);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0x10u16.strict_shl(129);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_shl(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_shl(rhs);
if b { imp::overflow_panic::shl() } else { a }
}
/// Unchecked shift left. Computes `self << rhs`, assuming that
/// `rhs` is less than the number of bits in `self`.
///
/// # Safety
///
/// This results in undefined behavior if `rhs` is larger than
/// or equal to the number of bits in `self`,
/// i.e. when [`checked_shl`] would return `None`.
///
#[doc = "[`checked_shl`]: u16::checked_shl"]
#[stable(feature = "unchecked_shifts", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_shl(self, rhs: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(rhs: u32) {
if !(rhs < <u16>::BITS) {
let msg =
"unsafe precondition(s) violated: u16::unchecked_shl cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(rhs); }
};
unsafe { intrinsics::unchecked_shl(self, rhs) }
}
/// Unbounded shift left. Computes `self << rhs`, without bounding the value of `rhs`.
///
/// If `rhs` is larger or equal to the number of bits in `self`,
/// the entire value is shifted out, and `0` is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1_u16.unbounded_shl(4), 0x10);"]
#[doc = "assert_eq!(0x1_u16.unbounded_shl(129), 0);"]
#[doc = "assert_eq!(0b101_u16.unbounded_shl(0), 0b101);"]
#[doc = "assert_eq!(0b101_u16.unbounded_shl(1), 0b1010);"]
#[doc = "assert_eq!(0b101_u16.unbounded_shl(2), 0b10100);"]
#[doc = "assert_eq!(42_u16.unbounded_shl(16), 0);"]
#[doc = "assert_eq!(42_u16.unbounded_shl(1).unbounded_shl(15), 0);"]
///
#[doc = "let start : u16 = 13;"]
/// let mut running = start;
/// for i in 0..160 {
/// // The unbounded shift left by i is the same as `<< 1` i times
/// assert_eq!(running, start.unbounded_shl(i));
/// // Which is not always the case for a wrapping shift
#[doc = " assert_eq!(running == start.wrapping_shl(i), i < 16);"]
///
/// running <<= 1;
/// }
/// ```
#[stable(feature = "unbounded_shifts", since = "1.87.0")]
#[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unbounded_shl(self, rhs: u32) -> u16 {
if rhs < Self::BITS { unsafe { self.unchecked_shl(rhs) } } else { 0 }
}
/// Exact shift left. Computes `self << rhs` as long as it can be reversed losslessly.
///
/// Returns `None` if any non-zero bits would be shifted out or if `rhs` >=
#[doc = "`u16::BITS`."]
/// Otherwise, returns `Some(self << rhs)`.
///
/// # Examples
///
/// ```
/// #![feature(exact_bitshifts)]
///
#[doc = "assert_eq!(0x1u16.shl_exact(4), Some(0x10));"]
#[doc = "assert_eq!(0x1u16.shl_exact(129), None);"]
/// ```
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn shl_exact(self, rhs: u32) -> Option<u16> {
if rhs <= self.leading_zeros() && rhs < <u16>::BITS {
Some(unsafe { self.unchecked_shl(rhs) })
} else { None }
}
/// Unchecked exact shift left. Computes `self << rhs`, assuming the operation can be
/// losslessly reversed `rhs` cannot be larger than
#[doc = "`u16::BITS`."]
///
/// # Safety
///
/// This results in undefined behavior when `rhs > self.leading_zeros() || rhs >=
#[doc = "u16::BITS`"]
/// i.e. when
#[doc = "[`u16::shl_exact`]"]
/// would return `None`.
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_shl_exact(self, rhs: u32) -> u16 {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(zeros: u32, bits: u32, rhs: u32) {
if !(rhs <= zeros && rhs < bits) {
let msg =
"unsafe precondition(s) violated: u16::unchecked_shl_exact cannot shift out non-zero bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_library_ub() {
precondition_check(self.leading_zeros(), <u16>::BITS, rhs);
}
};
unsafe { self.unchecked_shl(rhs) }
}
/// Checked shift right. Computes `self >> rhs`, returning `None`
/// if `rhs` is larger than or equal to the number of bits in `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10u16.checked_shr(4), Some(0x1));"]
#[doc = "assert_eq!(0x10u16.checked_shr(129), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
if rhs < Self::BITS {
Some(unsafe { self.unchecked_shr(rhs) })
} else { None }
}
/// Strict shift right. Computes `self >> rhs`, panicking if `rhs` is
/// larger than or equal to the number of bits in `self`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10u16.strict_shr(4), 0x1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0x10u16.strict_shr(129);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_shr(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_shr(rhs);
if b { imp::overflow_panic::shr() } else { a }
}
/// Unchecked shift right. Computes `self >> rhs`, assuming that
/// `rhs` is less than the number of bits in `self`.
///
/// # Safety
///
/// This results in undefined behavior if `rhs` is larger than
/// or equal to the number of bits in `self`,
/// i.e. when [`checked_shr`] would return `None`.
///
#[doc = "[`checked_shr`]: u16::checked_shr"]
#[stable(feature = "unchecked_shifts", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_shr(self, rhs: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(rhs: u32) {
if !(rhs < <u16>::BITS) {
let msg =
"unsafe precondition(s) violated: u16::unchecked_shr cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(rhs); }
};
unsafe { intrinsics::unchecked_shr(self, rhs) }
}
/// Unbounded shift right. Computes `self >> rhs`, without bounding the value of `rhs`.
///
/// If `rhs` is larger or equal to the number of bits in `self`,
/// the entire value is shifted out, and `0` is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10_u16.unbounded_shr(4), 0x1);"]
#[doc = "assert_eq!(0x10_u16.unbounded_shr(129), 0);"]
#[doc = "assert_eq!(0b1010_u16.unbounded_shr(0), 0b1010);"]
#[doc = "assert_eq!(0b1010_u16.unbounded_shr(1), 0b101);"]
#[doc = "assert_eq!(0b1010_u16.unbounded_shr(2), 0b10);"]
#[doc = "assert_eq!(42_u16.unbounded_shr(16), 0);"]
#[doc = "assert_eq!(42_u16.unbounded_shr(1).unbounded_shr(15), 0);"]
///
#[doc = "let start = u16::rotate_right(13, 4);"]
/// let mut running = start;
/// for i in 0..160 {
/// // The unbounded shift right by i is the same as `>> 1` i times
/// assert_eq!(running, start.unbounded_shr(i));
/// // Which is not always the case for a wrapping shift
#[doc = " assert_eq!(running == start.wrapping_shr(i), i < 16);"]
///
/// running >>= 1;
/// }
/// ```
#[stable(feature = "unbounded_shifts", since = "1.87.0")]
#[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unbounded_shr(self, rhs: u32) -> u16 {
if rhs < Self::BITS { unsafe { self.unchecked_shr(rhs) } } else { 0 }
}
/// Exact shift right. Computes `self >> rhs` as long as it can be reversed losslessly.
///
/// Returns `None` if any non-zero bits would be shifted out or if `rhs` >=
#[doc = "`u16::BITS`."]
/// Otherwise, returns `Some(self >> rhs)`.
///
/// # Examples
///
/// ```
/// #![feature(exact_bitshifts)]
///
#[doc = "assert_eq!(0x10u16.shr_exact(4), Some(0x1));"]
#[doc = "assert_eq!(0x10u16.shr_exact(5), None);"]
/// ```
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn shr_exact(self, rhs: u32) -> Option<u16> {
if rhs <= self.trailing_zeros() && rhs < <u16>::BITS {
Some(unsafe { self.unchecked_shr(rhs) })
} else { None }
}
/// Unchecked exact shift right. Computes `self >> rhs`, assuming the operation can be
/// losslessly reversed and `rhs` cannot be larger than
#[doc = "`u16::BITS`."]
///
/// # Safety
///
/// This results in undefined behavior when `rhs > self.trailing_zeros() || rhs >=
#[doc = "u16::BITS`"]
/// i.e. when
#[doc = "[`u16::shr_exact`]"]
/// would return `None`.
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_shr_exact(self, rhs: u32) -> u16 {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(zeros: u32, bits: u32, rhs: u32) {
if !(rhs <= zeros && rhs < bits) {
let msg =
"unsafe precondition(s) violated: u16::unchecked_shr_exact cannot shift out non-zero bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_library_ub() {
precondition_check(self.trailing_zeros(), <u16>::BITS, rhs);
}
};
unsafe { self.unchecked_shr(rhs) }
}
/// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u16.checked_pow(5), Some(32));"]
#[doc = "assert_eq!(0_u16.checked_pow(0), Some(1));"]
#[doc = "assert_eq!(u16::MAX.checked_pow(2), None);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
let mut base = self;
let mut acc: Self = 1;
if intrinsics::is_val_statically_known(base) && base.is_power_of_two() {
let k = base.ilog2();
let shift =
match k.checked_mul(exp) { Some(x) => x, None => return None, };
return (1 as Self).checked_shl(shift);
}
if exp == 0 { return Some(1); }
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 {
acc =
match acc.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
exp /= 2;
base =
match base.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
return acc.checked_mul(base);
}
loop {
if (exp & 1) == 1 {
acc =
match acc.checked_mul(base) {
Some(x) => x,
None => return None,
};
if exp == 1 { return Some(acc); }
}
exp /= 2;
base =
match base.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
}
/// Strict exponentiation. Computes `self.pow(exp)`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u16.strict_pow(5), 32);"]
#[doc = "assert_eq!(0_u16.strict_pow(0), 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = u16::MAX.strict_pow(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) {
None => imp::overflow_panic::pow(),
Some(a) => a,
}
}
/// Saturating integer addition. Computes `self + rhs`, saturating at
/// the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u16.saturating_add(1), 101);"]
#[doc = "assert_eq!(u16::MAX.saturating_add(127), u16::MAX);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[inline(always)]
pub const fn saturating_add(self, rhs: Self) -> Self {
intrinsics::saturating_add(self, rhs)
}
/// Saturating addition with a signed integer. Computes `self + rhs`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u16.saturating_add_signed(2), 3);"]
#[doc = "assert_eq!(1u16.saturating_add_signed(-2), 0);"]
#[doc = "assert_eq!((u16::MAX - 2).saturating_add_signed(4), u16::MAX);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_add_signed(self, rhs: i16) -> Self {
let (res, overflow) = self.overflowing_add(rhs as Self);
if overflow == (rhs < 0) { res } else if overflow { Self::MAX } else { 0 }
}
/// Saturating integer subtraction. Computes `self - rhs`, saturating
/// at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u16.saturating_sub(27), 73);"]
#[doc = "assert_eq!(13u16.saturating_sub(127), 0);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[inline(always)]
pub const fn saturating_sub(self, rhs: Self) -> Self {
intrinsics::saturating_sub(self, rhs)
}
/// Saturating integer subtraction. Computes `self` - `rhs`, saturating at
/// the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u16.saturating_sub_signed(2), 0);"]
#[doc = "assert_eq!(1u16.saturating_sub_signed(-2), 3);"]
#[doc = "assert_eq!((u16::MAX - 2).saturating_sub_signed(-4), u16::MAX);"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_sub_signed(self, rhs: i16) -> Self {
let (res, overflow) = self.overflowing_sub_signed(rhs);
if !overflow { res } else if rhs < 0 { Self::MAX } else { 0 }
}
/// Saturating integer multiplication. Computes `self * rhs`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u16.saturating_mul(10), 20);"]
#[doc = "assert_eq!((u16::MAX).saturating_mul(10), u16::MAX);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_mul(self, rhs: Self) -> Self {
match self.checked_mul(rhs) { Some(x) => x, None => Self::MAX, }
}
/// Saturating integer division. Computes `self / rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u16.saturating_div(2), 2);"]
///
/// ```
#[stable(feature = "saturating_div", since = "1.58.0")]
#[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn saturating_div(self, rhs: Self) -> Self {
self.wrapping_div(rhs)
}
/// Saturating integer exponentiation. Computes `self.pow(exp)`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(4u16.saturating_pow(3), 64);"]
#[doc = "assert_eq!(0_u16.saturating_pow(0), 1);"]
#[doc = "assert_eq!(u16::MAX.saturating_pow(2), u16::MAX);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) { Some(x) => x, None => Self::MAX, }
}
/// Wrapping (modular) addition. Computes `self + rhs`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(200u16.wrapping_add(55), 255);"]
#[doc = "assert_eq!(200u16.wrapping_add(u16::MAX), 199);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_add(self, rhs: Self) -> Self {
intrinsics::wrapping_add(self, rhs)
}
/// Wrapping (modular) addition with a signed integer. Computes
/// `self + rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u16.wrapping_add_signed(2), 3);"]
#[doc = "assert_eq!(1u16.wrapping_add_signed(-2), u16::MAX);"]
#[doc = "assert_eq!((u16::MAX - 2).wrapping_add_signed(4), 1);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_add_signed(self, rhs: i16) -> Self {
self.wrapping_add(rhs as Self)
}
/// Wrapping (modular) subtraction. Computes `self - rhs`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u16.wrapping_sub(100), 0);"]
#[doc = "assert_eq!(100u16.wrapping_sub(u16::MAX), 101);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_sub(self, rhs: Self) -> Self {
intrinsics::wrapping_sub(self, rhs)
}
/// Wrapping (modular) subtraction with a signed integer. Computes
/// `self - rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u16.wrapping_sub_signed(2), u16::MAX);"]
#[doc = "assert_eq!(1u16.wrapping_sub_signed(-2), 3);"]
#[doc = "assert_eq!((u16::MAX - 2).wrapping_sub_signed(-4), 1);"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_sub_signed(self, rhs: i16) -> Self {
self.wrapping_sub(rhs as Self)
}
/// Wrapping (modular) multiplication. Computes `self *
/// rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `u8` is used.
///
/// ```
/// assert_eq!(10u8.wrapping_mul(12), 120);
/// assert_eq!(25u8.wrapping_mul(12), 44);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_mul(self, rhs: Self) -> Self {
intrinsics::wrapping_mul(self, rhs)
}
/// Wrapping (modular) division. Computes `self / rhs`.
///
/// Wrapped division on unsigned types is just normal division. There's
/// no way wrapping could ever happen. This function exists so that all
/// operations are accounted for in the wrapping operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u16.wrapping_div(10), 10);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn wrapping_div(self, rhs: Self) -> Self { self / rhs }
/// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
///
/// Wrapped division on unsigned types is just normal division. There's
/// no way wrapping could ever happen. This function exists so that all
/// operations are accounted for in the wrapping operations. Since, for
/// the positive integers, all common definitions of division are equal,
/// this is exactly equal to `self.wrapping_div(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u16.wrapping_div_euclid(10), 10);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn wrapping_div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Wrapping (modular) remainder. Computes `self % rhs`.
///
/// Wrapped remainder calculation on unsigned types is just the regular
/// remainder calculation. There's no way wrapping could ever happen.
/// This function exists so that all operations are accounted for in the
/// wrapping operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u16.wrapping_rem(10), 0);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn wrapping_rem(self, rhs: Self) -> Self { self % rhs }
/// Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
///
/// Wrapped modulo calculation on unsigned types is just the regular
/// remainder calculation. There's no way wrapping could ever happen.
/// This function exists so that all operations are accounted for in the
/// wrapping operations. Since, for the positive integers, all common
/// definitions of division are equal, this is exactly equal to
/// `self.wrapping_rem(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u16.wrapping_rem_euclid(10), 0);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Wrapping (modular) negation. Computes `-self`,
/// wrapping around at the boundary of the type.
///
/// Since unsigned types do not have negative equivalents
/// all applications of this function will wrap (except for `-0`).
/// For values smaller than the corresponding signed type's maximum
/// the result is the same as casting the corresponding signed value.
/// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
/// `MAX` is the corresponding signed type's maximum.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0_u16.wrapping_neg(), 0);"]
#[doc = "assert_eq!(u16::MAX.wrapping_neg(), 1);"]
#[doc = "assert_eq!(13_u16.wrapping_neg(), (!13) + 1);"]
#[doc = "assert_eq!(42_u16.wrapping_neg(), !(42 - 1));"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_neg(self) -> Self { (0 as u16).wrapping_sub(self) }
/// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
/// where `mask` removes any high-order bits of `rhs` that
/// would cause the shift to exceed the bitwidth of the type.
///
/// Beware that, unlike most other `wrapping_*` methods on integers, this
/// does *not* give the same result as doing the shift in infinite precision
/// then truncating as needed. Instead, the behaviour of this method matches what shift instructions
/// do on many processors, and is what the `<<` operator does when overflow
/// checks are disabled, but numerically it's weird. Consider, instead,
/// using [`Self::unbounded_shl`] which has nicer behaviour.
///
/// Note that this is *not* the same as a rotate-left; the
/// RHS of a wrapping shift-left is restricted to the range
/// of the type, rather than the bits shifted out of the LHS
/// being returned to the other end. The primitive integer
/// types all implement a [`rotate_left`](Self::rotate_left) function,
/// which may be what you want instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1_u16.wrapping_shl(7), 128);"]
#[doc = "assert_eq!(0b101_u16.wrapping_shl(0), 0b101);"]
#[doc = "assert_eq!(0b101_u16.wrapping_shl(1), 0b1010);"]
#[doc = "assert_eq!(0b101_u16.wrapping_shl(2), 0b10100);"]
#[doc = "assert_eq!(u16::MAX.wrapping_shl(2), u16::MAX - 3);"]
#[doc = "assert_eq!(42_u16.wrapping_shl(16), 42);"]
#[doc = "assert_eq!(42_u16.wrapping_shl(1).wrapping_shl(15), 0);"]
#[doc = "assert_eq!(1_u16.wrapping_shl(128), 1);"]
#[doc = "assert_eq!(5_u16.wrapping_shl(1025), 10);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_shl(self, rhs: u32) -> Self {
unsafe { self.unchecked_shl(rhs & (Self::BITS - 1)) }
}
/// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
/// where `mask` removes any high-order bits of `rhs` that
/// would cause the shift to exceed the bitwidth of the type.
///
/// Beware that, unlike most other `wrapping_*` methods on integers, this
/// does *not* give the same result as doing the shift in infinite precision
/// then truncating as needed. Instead, the behaviour of this method matches what shift instructions
/// do on many processors, and is what the `>>` operator does when overflow
/// checks are disabled, but numerically it's weird. Consider, instead,
/// using [`Self::unbounded_shr`] which has nicer behaviour.
///
/// Note that this is *not* the same as a rotate-right; the
/// RHS of a wrapping shift-right is restricted to the range
/// of the type, rather than the bits shifted out of the LHS
/// being returned to the other end. The primitive integer
/// types all implement a [`rotate_right`](Self::rotate_right) function,
/// which may be what you want instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128_u16.wrapping_shr(7), 1);"]
#[doc = "assert_eq!(0b1010_u16.wrapping_shr(0), 0b1010);"]
#[doc = "assert_eq!(0b1010_u16.wrapping_shr(1), 0b101);"]
#[doc = "assert_eq!(0b1010_u16.wrapping_shr(2), 0b10);"]
#[doc = "assert_eq!(u16::MAX.wrapping_shr(1), i16::MAX.cast_unsigned());"]
#[doc = "assert_eq!(42_u16.wrapping_shr(16), 42);"]
#[doc = "assert_eq!(42_u16.wrapping_shr(1).wrapping_shr(15), 0);"]
#[doc = "assert_eq!(128_u16.wrapping_shr(128), 128);"]
#[doc = "assert_eq!(10_u16.wrapping_shr(1025), 5);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_shr(self, rhs: u32) -> Self {
unsafe { self.unchecked_shr(rhs & (Self::BITS - 1)) }
}
/// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3u16.wrapping_pow(5), 243);"]
/// assert_eq!(3u8.wrapping_pow(6), 217);
#[doc = "assert_eq!(0_u16.wrapping_pow(0), 1);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_pow(self, exp: u32) -> Self {
let (a, _) = self.overflowing_pow(exp);
a
}
/// Calculates `self` + `rhs`.
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u16.overflowing_add(2), (7, false));"]
#[doc = "assert_eq!(u16::MAX.overflowing_add(1), (0, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::add_with_overflow(self as u16, rhs as u16);
(a as Self, b)
}
/// Calculates `self` + `rhs` + `carry` and returns a tuple containing
/// the sum and the output carry (in that order).
///
/// Performs "ternary addition" of two integer operands and a carry-in
/// bit, and returns an output integer and a carry-out bit. This allows
/// chaining together multiple additions to create a wider addition, and
/// can be useful for bignum addition.
///
#[doc =
"This can be thought of as a 16-bit \"full adder\", in the electronics sense."]
///
/// If the input carry is false, this method is equivalent to
/// [`overflowing_add`](Self::overflowing_add), and the output carry is
/// equal to the overflow flag. Note that although carry and overflow
/// flags are similar for unsigned integers, they are different for
/// signed integers.
///
/// # Examples
///
/// ```
#[doc = "// 3 MAX (a = 3 \u{d7} 2^16 + 2^16 - 1)"]
#[doc = "// + 5 7 (b = 5 \u{d7} 2^16 + 7)"]
/// // ---------
#[doc = "// 9 6 (sum = 9 \u{d7} 2^16 + 6)"]
///
#[doc = "let (a1, a0): (u16, u16) = (3, u16::MAX);"]
#[doc = "let (b1, b0): (u16, u16) = (5, 7);"]
/// let carry0 = false;
///
/// let (sum0, carry1) = a0.carrying_add(b0, carry0);
/// assert_eq!(carry1, true);
/// let (sum1, carry2) = a1.carrying_add(b1, carry1);
/// assert_eq!(carry2, false);
///
/// assert_eq!((sum1, sum0), (9, 6));
/// ```
#[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
#[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue =
"152015")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
let (a, c1) = self.overflowing_add(rhs);
let (b, c2) = a.overflowing_add(carry as u16);
(b, unsafe { intrinsics::disjoint_bitor(c1, c2) })
}
/// Calculates `self` + `rhs` with a signed `rhs`.
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u16.overflowing_add_signed(2), (3, false));"]
#[doc = "assert_eq!(1u16.overflowing_add_signed(-2), (u16::MAX, true));"]
#[doc = "assert_eq!((u16::MAX - 2).overflowing_add_signed(4), (1, true));"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_add_signed(self, rhs: i16) -> (Self, bool) {
let (res, overflowed) = self.overflowing_add(rhs as Self);
(res, overflowed ^ (rhs < 0))
}
/// Calculates `self` - `rhs`.
///
/// Returns a tuple of the subtraction along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u16.overflowing_sub(2), (3, false));"]
#[doc = "assert_eq!(0u16.overflowing_sub(1), (u16::MAX, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::sub_with_overflow(self as u16, rhs as u16);
(a as Self, b)
}
/// Calculates `self` − `rhs` − `borrow` and returns a tuple
/// containing the difference and the output borrow.
///
/// Performs "ternary subtraction" by subtracting both an integer
/// operand and a borrow-in bit from `self`, and returns an output
/// integer and a borrow-out bit. This allows chaining together multiple
/// subtractions to create a wider subtraction, and can be useful for
/// bignum subtraction.
///
/// # Examples
///
/// ```
#[doc = "// 9 6 (a = 9 \u{d7} 2^16 + 6)"]
#[doc = "// - 5 7 (b = 5 \u{d7} 2^16 + 7)"]
/// // ---------
#[doc = "// 3 MAX (diff = 3 \u{d7} 2^16 + 2^16 - 1)"]
///
#[doc = "let (a1, a0): (u16, u16) = (9, 6);"]
#[doc = "let (b1, b0): (u16, u16) = (5, 7);"]
/// let borrow0 = false;
///
/// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);
/// assert_eq!(borrow1, true);
/// let (diff1, borrow2) = a1.borrowing_sub(b1, borrow1);
/// assert_eq!(borrow2, false);
///
#[doc = "assert_eq!((diff1, diff0), (3, u16::MAX));"]
/// ```
#[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
#[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue =
"152015")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
let (a, c1) = self.overflowing_sub(rhs);
let (b, c2) = a.overflowing_sub(borrow as u16);
(b, unsafe { intrinsics::disjoint_bitor(c1, c2) })
}
/// Calculates `self` - `rhs` with a signed `rhs`
///
/// Returns a tuple of the subtraction along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u16.overflowing_sub_signed(2), (u16::MAX, true));"]
#[doc = "assert_eq!(1u16.overflowing_sub_signed(-2), (3, false));"]
#[doc = "assert_eq!((u16::MAX - 2).overflowing_sub_signed(-4), (1, true));"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_sub_signed(self, rhs: i16) -> (Self, bool) {
let (res, overflow) = self.overflowing_sub(rhs as Self);
(res, overflow ^ (rhs < 0))
}
/// Computes the absolute difference between `self` and `other`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u16.abs_diff(80), 20u16);"]
#[doc = "assert_eq!(100u16.abs_diff(110), 10u16);"]
/// ```
#[stable(feature = "int_abs_diff", since = "1.60.0")]
#[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn abs_diff(self, other: Self) -> Self {
if size_of::<Self>() == 1 {
(self as i32).wrapping_sub(other as i32).unsigned_abs() as Self
} else { if self < other { other - self } else { self - other } }
}
/// Calculates the multiplication of `self` and `rhs`.
///
/// Returns a tuple of the multiplication along with a boolean
/// indicating whether an arithmetic overflow would occur. If an
/// overflow would have occurred then the wrapped value is returned.
///
/// If you want the *value* of the overflow, rather than just *whether*
/// an overflow occurred, see [`Self::carrying_mul`].
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `u32` is used.
///
/// ```
/// assert_eq!(5u32.overflowing_mul(2), (10, false));
/// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::mul_with_overflow(self as u16, rhs as u16);
(a as Self, b)
}
/// Calculates the "full multiplication" `self * rhs + carry`
/// without the possibility to overflow.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// Performs "long multiplication" which takes in an extra amount to add, and may return an
/// additional amount of overflow. This allows for chaining together multiple
/// multiplications to create "big integers" which represent larger values.
///
/// If you also need to add a value, then use [`Self::carrying_mul_add`].
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `u32` is used.
///
/// ```
/// assert_eq!(5u32.carrying_mul(2, 0), (10, 0));
/// assert_eq!(5u32.carrying_mul(2, 10), (20, 0));
/// assert_eq!(1_000_000_000u32.carrying_mul(10, 0), (1410065408, 2));
/// assert_eq!(1_000_000_000u32.carrying_mul(10, 10), (1410065418, 2));
#[doc =
"assert_eq!(u16::MAX.carrying_mul(u16::MAX, u16::MAX), (0, u16::MAX));"]
/// ```
///
/// This is the core operation needed for scalar multiplication when
/// implementing it for wider-than-native types.
///
/// ```
/// fn scalar_mul_eq(little_endian_digits: &mut Vec<u16>, multiplicand: u16) {
/// let mut carry = 0;
/// for d in little_endian_digits.iter_mut() {
/// (*d, carry) = d.carrying_mul(multiplicand, carry);
/// }
/// if carry != 0 {
/// little_endian_digits.push(carry);
/// }
/// }
///
/// let mut v = vec![10, 20];
/// scalar_mul_eq(&mut v, 3);
/// assert_eq!(v, [30, 60]);
///
/// assert_eq!(0x87654321_u64 * 0xFEED, 0x86D3D159E38D);
/// let mut v = vec![0x4321, 0x8765];
/// scalar_mul_eq(&mut v, 0xFEED);
/// assert_eq!(v, [0xE38D, 0xD159, 0x86D3]);
/// ```
///
/// If `carry` is zero, this is similar to [`overflowing_mul`](Self::overflowing_mul),
/// except that it gives the value of the overflow instead of just whether one happened:
///
/// ```
/// # #![allow(unused_features)]
/// #![feature(const_unsigned_bigint_helpers)]
/// let r = u8::carrying_mul(7, 13, 0);
/// assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(7, 13));
/// let r = u8::carrying_mul(13, 42, 0);
/// assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(13, 42));
/// ```
///
/// The value of the first field in the returned tuple matches what you'd get
/// by combining the [`wrapping_mul`](Self::wrapping_mul) and
/// [`wrapping_add`](Self::wrapping_add) methods:
///
/// ```
/// # #![allow(unused_features)]
/// #![feature(const_unsigned_bigint_helpers)]
/// assert_eq!(
/// 789_u16.carrying_mul(456, 123).0,
/// 789_u16.wrapping_mul(456).wrapping_add(123),
/// );
/// ```
#[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
#[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue =
"152015")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_mul(self, rhs: Self, carry: Self) -> (Self, Self) {
Self::carrying_mul_add(self, rhs, carry, 0)
}
/// Calculates the "full multiplication" `self * rhs + carry + add`.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// This cannot overflow, as the double-width result has exactly enough
/// space for the largest possible result. This is equivalent to how, in
/// decimal, 9 × 9 + 9 + 9 = 81 + 18 = 99 = 9×10⁰ + 9×10¹ = 10² - 1.
///
/// Performs "long multiplication" which takes in an extra amount to add, and may return an
/// additional amount of overflow. This allows for chaining together multiple
/// multiplications to create "big integers" which represent larger values.
///
/// If you don't need the `add` part, then you can use [`Self::carrying_mul`] instead.
///
/// # Examples
///
/// Please note that this example is shared between integer types,
/// which explains why `u32` is used here.
///
/// ```
/// assert_eq!(5u32.carrying_mul_add(2, 0, 0), (10, 0));
/// assert_eq!(5u32.carrying_mul_add(2, 10, 10), (30, 0));
/// assert_eq!(1_000_000_000u32.carrying_mul_add(10, 0, 0), (1410065408, 2));
/// assert_eq!(1_000_000_000u32.carrying_mul_add(10, 10, 10), (1410065428, 2));
#[doc =
"assert_eq!(u16::MAX.carrying_mul_add(u16::MAX, u16::MAX, u16::MAX), (u16::MAX, u16::MAX));"]
/// ```
///
/// This is the core per-digit operation for "grade school" O(n²) multiplication.
///
/// Please note that this example is shared between integer types,
/// using `u8` for simplicity of the demonstration.
///
/// ```
/// fn quadratic_mul<const N: usize>(a: [u8; N], b: [u8; N]) -> [u8; N] {
/// let mut out = [0; N];
/// for j in 0..N {
/// let mut carry = 0;
/// for i in 0..(N - j) {
/// (out[j + i], carry) = u8::carrying_mul_add(a[i], b[j], out[j + i], carry);
/// }
/// }
/// out
/// }
///
/// // -1 * -1 == 1
/// assert_eq!(quadratic_mul([0xFF; 3], [0xFF; 3]), [1, 0, 0]);
///
/// assert_eq!(u32::wrapping_mul(0x9e3779b9, 0x7f4a7c15), 0xcffc982d);
/// assert_eq!(
/// quadratic_mul(u32::to_le_bytes(0x9e3779b9), u32::to_le_bytes(0x7f4a7c15)),
/// u32::to_le_bytes(0xcffc982d)
/// );
/// ```
#[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
#[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue =
"152015")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_mul_add(self, rhs: Self, carry: Self, add: Self)
-> (Self, Self) {
intrinsics::carrying_mul_add(self, rhs, carry, add)
}
/// Calculates the divisor when `self` is divided by `rhs`.
///
/// Returns a tuple of the divisor along with a boolean indicating
/// whether an arithmetic overflow would occur. Note that for unsigned
/// integers overflow never occurs, so the second value is always
/// `false`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u16.overflowing_div(2), (2, false));"]
/// ```
#[inline(always)]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_overflowing_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[track_caller]
pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
(self / rhs, false)
}
/// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
///
/// Returns a tuple of the divisor along with a boolean indicating
/// whether an arithmetic overflow would occur. Note that for unsigned
/// integers overflow never occurs, so the second value is always
/// `false`.
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self.overflowing_div(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u16.overflowing_div_euclid(2), (2, false));"]
/// ```
#[inline(always)]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[track_caller]
pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
(self / rhs, false)
}
/// Calculates the remainder when `self` is divided by `rhs`.
///
/// Returns a tuple of the remainder after dividing along with a boolean
/// indicating whether an arithmetic overflow would occur. Note that for
/// unsigned integers overflow never occurs, so the second value is
/// always `false`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u16.overflowing_rem(2), (1, false));"]
/// ```
#[inline(always)]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_overflowing_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[track_caller]
pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
(self % rhs, false)
}
/// Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
///
/// Returns a tuple of the modulo after dividing along with a boolean
/// indicating whether an arithmetic overflow would occur. Note that for
/// unsigned integers overflow never occurs, so the second value is
/// always `false`.
/// Since, for the positive integers, all common
/// definitions of division are equal, this operation
/// is exactly equal to `self.overflowing_rem(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u16.overflowing_rem_euclid(2), (1, false));"]
/// ```
#[inline(always)]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[track_caller]
pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
(self % rhs, false)
}
/// Negates self in an overflowing fashion.
///
/// Returns `!self + 1` using wrapping operations to return the value
/// that represents the negation of this unsigned value. Note that for
/// positive unsigned values overflow always occurs, but negating 0 does
/// not overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0u16.overflowing_neg(), (0, false));"]
#[doc = "assert_eq!(2u16.overflowing_neg(), (-2i32 as u16, true));"]
/// ```
#[inline(always)]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn overflowing_neg(self) -> (Self, bool) {
((!self).wrapping_add(1), self != 0)
}
/// Shifts self left by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean
/// indicating whether the shift value was larger than or equal to the
/// number of bits. If the shift value is too large, then value is
/// masked (N-1) where N is the number of bits, and this value is then
/// used to perform the shift.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1u16.overflowing_shl(4), (0x10, false));"]
#[doc = "assert_eq!(0x1u16.overflowing_shl(132), (0x10, true));"]
#[doc = "assert_eq!(0x10u16.overflowing_shl(15), (0, false));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shl(rhs), rhs >= Self::BITS)
}
/// Shifts self right by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean
/// indicating whether the shift value was larger than or equal to the
/// number of bits. If the shift value is too large, then value is
/// masked (N-1) where N is the number of bits, and this value is then
/// used to perform the shift.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10u16.overflowing_shr(4), (0x1, false));"]
#[doc = "assert_eq!(0x10u16.overflowing_shr(132), (0x1, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shr(rhs), rhs >= Self::BITS)
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// Returns a tuple of the exponentiation along with a bool indicating
/// whether an overflow happened.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3u16.overflowing_pow(5), (243, false));"]
#[doc = "assert_eq!(0_u16.overflowing_pow(0), (1, false));"]
/// assert_eq!(3u8.overflowing_pow(6), (217, true));
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
let mut base = self;
let mut acc: Self = 1;
let mut overflow = false;
let mut tmp_overflow;
if intrinsics::is_val_statically_known(base) && base.is_power_of_two() {
let k = base.ilog2();
let Some(shift) = k.checked_mul(exp) else { return (0, true) };
return ((1 as Self).unbounded_shl(shift), shift >= Self::BITS)
}
if exp == 0 { return (1, false); }
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 {
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
}
exp /= 2;
(base, tmp_overflow) = base.overflowing_mul(base);
overflow |= tmp_overflow;
}
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
return (acc, overflow);
}
loop {
if (exp & 1) == 1 {
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
if exp == 1 { return (acc, overflow); }
}
exp /= 2;
(base, tmp_overflow) = base.overflowing_mul(base);
overflow |= tmp_overflow;
}
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u16.pow(5), 32);"]
#[doc = "assert_eq!(0_u16.pow(0), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn pow(self, exp: u32) -> Self {
if intrinsics::overflow_checks() {
self.strict_pow(exp)
} else { self.wrapping_pow(exp) }
}
/// Returns the square root of the number, rounded down.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10u16.isqrt(), 3);"]
/// ```
#[stable(feature = "isqrt", since = "1.84.0")]
#[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn isqrt(self) -> Self {
let result = imp::int_sqrt::u16(self as u16) as Self;
unsafe {
const MAX_RESULT: u16 = imp::int_sqrt::u16(<u16>::MAX) as u16;
crate::hint::assert_unchecked(result <= MAX_RESULT)
}
if self >= 1 { unsafe { crate::hint::assert_unchecked(result >= 1) } }
unsafe {
crate::hint::assert_unchecked(result.unchecked_mul(result) <= self);
crate::hint::assert_unchecked(result <= self);
}
result
}
/// Performs Euclidean division.
///
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self / rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7u16.div_euclid(4), 1); // or any other integer type"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Calculates the least remainder of `self` when divided by
/// `rhs`.
///
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self % rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7u16.rem_euclid(4), 3); // or any other integer type"]
/// ```
#[doc(alias = "modulo", alias = "mod")]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
///
/// This is the same as performing `self / rhs` for all unsigned integers.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "assert_eq!(7_u16.div_floor(4), 1);"]
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn div_floor(self, rhs: Self) -> Self { self / rhs }
/// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7_u16.div_ceil(4), 2);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_ceil(self, rhs: Self) -> Self {
let d = self / rhs;
let r = self % rhs;
if r > 0 { d + 1 } else { d }
}
/// Calculates the smallest value greater than or equal to `self` that
/// is a multiple of `rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// On overflow, this function will panic if overflow checks are enabled (default in debug
/// mode) and wrap if overflow checks are disabled (default in release mode).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(16_u16.next_multiple_of(8), 16);"]
#[doc = "assert_eq!(23_u16.next_multiple_of(8), 24);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_multiple_of(self, rhs: Self) -> Self {
match self % rhs { 0 => self, r => self + (rhs - r), }
}
/// Calculates the smallest value greater than or equal to `self` that
/// is a multiple of `rhs`. Returns `None` if `rhs` is zero or the
/// operation would result in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(16_u16.checked_next_multiple_of(8), Some(16));"]
#[doc = "assert_eq!(23_u16.checked_next_multiple_of(8), Some(24));"]
#[doc = "assert_eq!(1_u16.checked_next_multiple_of(0), None);"]
#[doc = "assert_eq!(u16::MAX.checked_next_multiple_of(2), None);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
match match self.checked_rem(rhs) { Some(x) => x, None => return None, } {
0 => Some(self),
r => self.checked_add(rhs - r),
}
}
/// Returns `true` if `self` is an integer multiple of `rhs`, and false otherwise.
///
/// This function is equivalent to `self % rhs == 0`, except that it will not panic
/// for `rhs == 0`. Instead, `0.is_multiple_of(0) == true`, and for any non-zero `n`,
/// `n.is_multiple_of(0) == false`.
///
/// # Examples
///
/// ```
#[doc = "assert!(6_u16.is_multiple_of(2));"]
#[doc = "assert!(!5_u16.is_multiple_of(2));"]
///
#[doc = "assert!(0_u16.is_multiple_of(0));"]
#[doc = "assert!(!6_u16.is_multiple_of(0));"]
/// ```
#[stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
#[rustc_const_stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
#[must_use]
#[inline]
pub const fn is_multiple_of(self, rhs: Self) -> bool {
match rhs { 0 => self == 0, _ => self % rhs == 0, }
}
/// Returns `true` if and only if `self == 2^k` for some unsigned integer `k`.
///
/// # Examples
///
/// ```
#[doc = "assert!(16u16.is_power_of_two());"]
#[doc = "assert!(!10u16.is_power_of_two());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
#[inline(always)]
pub const fn is_power_of_two(self) -> bool { self.count_ones() == 1 }
#[inline]
const fn one_less_than_next_power_of_two(self) -> Self {
if self <= 1 { return 0; }
let p = self - 1;
let z = unsafe { intrinsics::ctlz_nonzero(p) };
<u16>::MAX >> z
}
/// Returns the smallest power of two greater than or equal to `self`.
///
/// When return value overflows (i.e., `self > (1 << (N-1))` for type
/// `uN`), it panics in debug mode and the return value is wrapped to 0 in
/// release mode (the only situation in which this method can return 0).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u16.next_power_of_two(), 2);"]
#[doc = "assert_eq!(3u16.next_power_of_two(), 4);"]
#[doc = "assert_eq!(0u16.next_power_of_two(), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_power_of_two(self) -> Self {
self.one_less_than_next_power_of_two() + 1
}
/// Returns the smallest power of two greater than or equal to `self`. If
/// the next power of two is greater than the type's maximum value,
/// `None` is returned, otherwise the power of two is wrapped in `Some`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u16.checked_next_power_of_two(), Some(2));"]
#[doc = "assert_eq!(3u16.checked_next_power_of_two(), Some(4));"]
#[doc = "assert_eq!(u16::MAX.checked_next_power_of_two(), None);"]
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn checked_next_power_of_two(self) -> Option<Self> {
self.one_less_than_next_power_of_two().checked_add(1)
}
/// Returns the smallest power of two greater than or equal to `n`. If
/// the next power of two is greater than the type's maximum value,
/// the return value is wrapped to `0`.
///
/// # Examples
///
/// ```
/// #![feature(wrapping_next_power_of_two)]
///
#[doc = "assert_eq!(2u16.wrapping_next_power_of_two(), 2);"]
#[doc = "assert_eq!(3u16.wrapping_next_power_of_two(), 4);"]
#[doc = "assert_eq!(u16::MAX.wrapping_next_power_of_two(), 0);"]
/// ```
#[inline]
#[unstable(feature = "wrapping_next_power_of_two", issue = "32463", reason =
"needs decision on wrapping behavior")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn wrapping_next_power_of_two(self) -> Self {
self.one_less_than_next_power_of_two().wrapping_add(1)
}
/// Returns the memory representation of this integer as a byte array in
/// big-endian (network) byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234u16.to_be_bytes();"]
#[doc = "assert_eq!(bytes, [0x12, 0x34]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
self.to_be().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// little-endian byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234u16.to_le_bytes();"]
#[doc = "assert_eq!(bytes, [0x34, 0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
self.to_le().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code
/// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
/// instead.
///
#[doc = ""]
///
/// [`to_be_bytes`]: Self::to_be_bytes
/// [`to_le_bytes`]: Self::to_le_bytes
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234u16.to_ne_bytes();"]
/// assert_eq!(
/// bytes,
/// if cfg!(target_endian = "big") {
#[doc = " [0x12, 0x34]"]
/// } else {
#[doc = " [0x34, 0x12]"]
/// }
/// );
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[allow(unnecessary_transmutes)]
#[inline]
pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
unsafe { mem::transmute(self) }
}
/// Creates a native endian integer value from its representation
/// as a byte array in big endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = u16::from_be_bytes([0x12, 0x34]);"]
#[doc = "assert_eq!(value, 0x1234);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_be_u16(input: &mut &[u8]) -> u16 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u16>());"]
/// *input = rest;
#[doc = " u16::from_be_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_be(Self::from_ne_bytes(bytes))
}
/// Creates a native endian integer value from its representation
/// as a byte array in little endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = u16::from_le_bytes([0x34, 0x12]);"]
#[doc = "assert_eq!(value, 0x1234);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_le_u16(input: &mut &[u8]) -> u16 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u16>());"]
/// *input = rest;
#[doc = " u16::from_le_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_le(Self::from_ne_bytes(bytes))
}
/// Creates a native endian integer value from its memory representation
/// as a byte array in native endianness.
///
/// As the target platform's native endianness is used, portable code
/// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
/// appropriate instead.
///
/// [`from_be_bytes`]: Self::from_be_bytes
/// [`from_le_bytes`]: Self::from_le_bytes
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = u16::from_ne_bytes(if cfg!(target_endian = \"big\") {"]
#[doc = " [0x12, 0x34]"]
/// } else {
#[doc = " [0x34, 0x12]"]
/// });
#[doc = "assert_eq!(value, 0x1234);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_ne_u16(input: &mut &[u8]) -> u16 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u16>());"]
/// *input = rest;
#[doc = " u16::from_ne_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use]
#[inline]
pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
unsafe { mem::transmute(bytes) }
}
/// New code should prefer to use
#[doc = "[`u16::MIN`] instead."]
///
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_promotable]
#[inline(always)]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MIN` associated constant on this type")]
#[rustc_diagnostic_item = "u16_legacy_fn_min_value"]
pub const fn min_value() -> Self { Self::MIN }
/// New code should prefer to use
#[doc = "[`u16::MAX`] instead."]
///
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_promotable]
#[inline(always)]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MAX` associated constant on this type")]
#[rustc_diagnostic_item = "u16_legacy_fn_max_value"]
pub const fn max_value() -> Self { Self::MAX }
/// Truncate an integer to an integer of the same size or smaller, preserving the least
/// significant bits.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u8, 120u16.truncate());"]
/// assert_eq!(120u8, 376u32.truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
/// instead of truncating.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u8, 120u16.saturating_truncate());"]
/// assert_eq!(255u8, 376u32.saturating_truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn saturating_truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_saturating_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
/// is outside the bounds of the smaller type.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(Some(120u8), 120u16.checked_truncate());"]
/// assert_eq!(None, 376u32.checked_truncate::<u8>());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn checked_truncate<Target>(self) -> Option<Target> where
Self: [const] traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_checked_truncate(self)
}
/// Widen to an integer of the same size or larger, preserving its value.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u128, 120u8.widen());"]
/// ```
#[must_use =
"this returns the widened value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn widen<Target>(self) -> Target where Self: [const]
traits::WidenTarget<Target> {
traits::WidenTarget::internal_widen(self)
}
/// Converts `self` to the target integer type, saturating at the numeric
/// bounds instead of overflowing.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(255u8, u16::MAX.saturating_cast());"]
#[doc = "assert_eq!(127i8, u16::MAX.saturating_cast());"]
#[doc = "assert_eq!(42i8, 42u16.saturating_cast());"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn saturating_cast<T: [const] BoundedCastFromInt<Self>>(self) -> T {
T::saturating_cast_from(self)
}
/// Converts `self` to the target integer type, wrapping around at the
/// boundary of the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(255u8, u16::MAX.wrapping_cast());"]
#[doc = "assert_eq!(42i8, 42u16.wrapping_cast());"]
#[doc = "assert_eq!(u16::MAX as i8, u16::MAX.wrapping_cast());"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn wrapping_cast<T: [const] BoundedCastFromInt<Self>>(self) -> T {
T::wrapping_cast_from(self)
}
/// Converts `self` to the target integer type, returning `None` if the value
/// is not representable by the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(Some(42u8), 42u16.checked_cast());"]
#[doc = "assert_eq!(128u16.checked_cast::<i8>(), None);"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn checked_cast<T: [const] CheckedCastFromInt<Self>>(self)
-> Option<T> {
T::checked_cast_from(self)
}
/// Converts `self` to the target integer type, panicking if the value
/// is not representable by the target type.
///
/// # Panics
///
/// This function will panic if the value is not representable by the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(42u8, 42u16.strict_cast());"]
/// ```
///
/// The following will panic:
///
/// ```should_panic
/// #![feature(integer_casts)]
#[doc = "let _ = 128u16.strict_cast::<i8>();"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
#[track_caller]
pub const fn strict_cast<T: [const] CheckedCastFromInt<Self>>(self) -> T {
T::strict_cast_from(self)
}
/// Converts `self` to the target integer type, assuming the value is
/// representable by the target type.
///
/// # Safety
///
/// This results in undefined behavior if the integer value of `self` is bigger than `T::MAX`,
/// or smaller than `T::MIN`, where `T` is the target type.
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const unsafe fn unchecked_cast<T: [const] CheckedCastFromInt<Self>>(self)
-> T {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(in_bounds: bool) {
if !in_bounds {
let msg =
"unsafe precondition(s) violated: u16::unchecked_cast must fit in the target type\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check({
let cast_val = self.checked_cast::<T>();
let ret = cast_val.is_some();
core::mem::forget(cast_val);
ret
});
}
};
unsafe { T::unchecked_cast_from(self) }
}uint_impl! {
1232Self = u16,
1233 ActualT = u16,
1234 SignedT = i16,
1235 BITS = 16,
1236 BITS_MINUS_ONE = 15,
1237 MAX = 65535,
1238 rot = 4,
1239 rot_op = "0xa003",
1240 rot_result = "0x3a",
1241 fsh_op = "0x2de",
1242 fshl_result = "0x30",
1243 fshr_result = "0x302d",
1244 clmul_lhs = "0x9012",
1245 clmul_rhs = "0xcd34",
1246 clmul_result = "0x928",
1247 swap_op = "0x1234",
1248 swapped = "0x3412",
1249 reversed = "0x2c48",
1250 le_bytes = "[0x34, 0x12]",
1251 be_bytes = "[0x12, 0x34]",
1252 to_xe_bytes_doc = "",
1253 from_xe_bytes_doc = "",
1254 bound_condition = "",
1255 }1256/// Calculates the midpoint (average) between `self` and `rhs`.
///
/// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
/// sufficiently-large unsigned integral type. This implies that the result is
/// always rounded towards zero and that no overflow will ever occur.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0u16.midpoint(4), 2);"]
#[doc = "assert_eq!(1u16.midpoint(4), 2);"]
/// ```
#[stable(feature = "num_midpoint", since = "1.85.0")]
#[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[doc(alias = "average_floor")]
#[doc(alias = "average")]
#[inline]
pub const fn midpoint(self, rhs: u16) -> u16 {
((self as u32 + rhs as u32) / 2) as u16
}midpoint_impl! { u16, u32, unsigned }1257/// Widening multiplication. Computes `self * rhs`, widening to a larger integer.
///
/// The returned value is always exact and can never overflow.
///
/// Note that this method is semantically equivalent to [`carrying_mul`] with a
/// carry of zero, with the latter instead returning a tuple denoting the low and
/// high parts of the result. Consider using it instead if you need
/// interoperability with other big int helper functions, or if this method isn't
/// available for a given type.
///
/// [`carrying_mul`]: Self::carrying_mul
///
/// # Examples
///
/// ```
/// #![feature(widening_mul)]
///
#[doc = "assert_eq!(u16::MAX.widening_mul(0_u16), 0);"]
#[doc =
"assert_eq!(u16::MAX.widening_mul(u16::MAX), u16::MAX as u32 * u16::MAX as u32);"]
/// ```
#[unstable(feature = "widening_mul", issue = "152016")]
#[rustc_const_unstable(feature = "widening_mul", issue = "152016")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn widening_mul(self, rhs: Self) -> u32 { self as u32 * rhs as u32 }widening_mul_impl! { u16, u32 }1258/// Performs a widening carry-less multiplication.
///
/// # Examples
///
/// ```
/// #![feature(uint_carryless_mul)]
///
#[doc =
"assert_eq!(u16::MAX.widening_carryless_mul(u16::MAX), u32::MAX / 3);"]
/// ```
#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
#[doc(alias = "clmul")]
#[unstable(feature = "uint_carryless_mul", issue = "152080")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn widening_carryless_mul(self, rhs: u16) -> u32 {
(self as u32).carryless_mul(rhs as u32)
}widening_carryless_mul_impl! { u16, u32 }1259/// Calculates the "full carryless multiplication" without the possibility to overflow.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `u8` is used.
///
/// ```
/// #![feature(uint_carryless_mul)]
///
/// assert_eq!(0b1000_0000u8.carrying_carryless_mul(0b1000_0000, 0b0000), (0, 0b0100_0000));
/// assert_eq!(0b1000_0000u8.carrying_carryless_mul(0b1000_0000, 0b1111), (0b1111, 0b0100_0000));
#[doc =
"assert_eq!(u16::MAX.carrying_carryless_mul(u16::MAX, u16::MAX), (!(u16::MAX / 3), u16::MAX / 3));"]
/// ```
#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
#[doc(alias = "clmul")]
#[unstable(feature = "uint_carryless_mul", issue = "152080")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_carryless_mul(self, rhs: Self, carry: Self)
-> (Self, Self) {
let p = (self as u32).carryless_mul(rhs as u32);
let lo = (p as u16);
let hi = (p >> Self::BITS) as u16;
(lo ^ carry, hi)
}carrying_carryless_mul_impl! { u16, u32 }12601261/// Checks if the value is a Unicode surrogate code point, which are disallowed values for [`char`].
1262 ///
1263 /// # Examples
1264 ///
1265 /// ```
1266 /// #![feature(utf16_extra)]
1267 ///
1268 /// let low_non_surrogate = 0xA000u16;
1269 /// let low_surrogate = 0xD800u16;
1270 /// let high_surrogate = 0xDC00u16;
1271 /// let high_non_surrogate = 0xE000u16;
1272 ///
1273 /// assert!(!low_non_surrogate.is_utf16_surrogate());
1274 /// assert!(low_surrogate.is_utf16_surrogate());
1275 /// assert!(high_surrogate.is_utf16_surrogate());
1276 /// assert!(!high_non_surrogate.is_utf16_surrogate());
1277 /// ```
1278#[must_use]
1279 #[unstable(feature = "utf16_extra", issue = "94919")]
1280 #[inline]
1281pub const fn is_utf16_surrogate(self) -> bool {
1282#[allow(non_exhaustive_omitted_patterns)] match self {
0xD800..=0xDFFF => true,
_ => false,
}matches!(self, 0xD800..=0xDFFF)1283 }
1284}
12851286impl u32 {
1287/// The smallest value that can be represented by this integer type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(u32::MIN, 0);"]
/// ```
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MIN: Self = 0;
/// The largest value that can be represented by this integer type
#[doc = "(2<sup>32</sup> − 1)."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(u32::MAX, 4294967295);"]
/// ```
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MAX: Self = !0;
/// The size of this integer type in bits.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(u32::BITS, 32);"]
/// ```
#[stable(feature = "int_bits_const", since = "1.53.0")]
pub const BITS: u32 = Self::MAX.count_ones();
/// Returns the number of ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 0b01001100u32;"]
/// assert_eq!(n.count_ones(), 3);
///
#[doc = "let max = u32::MAX;"]
#[doc = "assert_eq!(max.count_ones(), 32);"]
///
#[doc = "let zero = 0u32;"]
/// assert_eq!(zero.count_ones(), 0);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[doc(alias = "popcount")]
#[doc(alias = "popcnt")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn count_ones(self) -> u32 { return intrinsics::ctpop(self); }
/// Returns the number of zeros in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let zero = 0u32;"]
#[doc = "assert_eq!(zero.count_zeros(), 32);"]
///
#[doc = "let max = u32::MAX;"]
/// assert_eq!(max.count_zeros(), 0);
/// ```
///
/// This is heavily dependent on the width of the type, and thus
/// might give surprising results depending on type inference:
/// ```
/// # fn foo(_: u8) {}
/// # fn bar(_: u16) {}
/// let lucky = 7;
/// foo(lucky);
/// assert_eq!(lucky.count_zeros(), 5);
/// assert_eq!(lucky.count_ones(), 3);
///
/// let lucky = 7;
/// bar(lucky);
/// assert_eq!(lucky.count_zeros(), 13);
/// assert_eq!(lucky.count_ones(), 3);
/// ```
/// You might want to use [`Self::count_ones`] instead, or emphasize
/// the type you're using in the call rather than method syntax:
/// ```
/// let small = 1;
#[doc = "assert_eq!(u32::count_zeros(small), 31);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn count_zeros(self) -> u32 { (!self).count_ones() }
/// Returns the number of leading zeros in the binary representation of `self`.
///
/// Depending on what you're doing with the value, you might also be interested in the
/// [`ilog2`] function which returns a consistent number, even if the type widens.
///
/// # Examples
///
/// ```
#[doc = "let n = u32::MAX >> 2;"]
/// assert_eq!(n.leading_zeros(), 2);
///
#[doc = "let zero = 0u32;"]
#[doc = "assert_eq!(zero.leading_zeros(), 32);"]
///
#[doc = "let max = u32::MAX;"]
/// assert_eq!(max.leading_zeros(), 0);
/// ```
#[doc = "[`ilog2`]: u32::ilog2"]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn leading_zeros(self) -> u32 {
return intrinsics::ctlz(self as u32);
}
/// Returns the number of trailing zeros in the binary representation
/// of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 0b0101000u32;"]
/// assert_eq!(n.trailing_zeros(), 3);
///
#[doc = "let zero = 0u32;"]
#[doc = "assert_eq!(zero.trailing_zeros(), 32);"]
///
#[doc = "let max = u32::MAX;"]
#[doc = "assert_eq!(max.trailing_zeros(), 0);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn trailing_zeros(self) -> u32 { return intrinsics::cttz(self); }
/// Returns the number of leading ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = !(u32::MAX >> 2);"]
/// assert_eq!(n.leading_ones(), 2);
///
#[doc = "let zero = 0u32;"]
/// assert_eq!(zero.leading_ones(), 0);
///
#[doc = "let max = u32::MAX;"]
#[doc = "assert_eq!(max.leading_ones(), 32);"]
/// ```
#[stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn leading_ones(self) -> u32 { (!self).leading_zeros() }
/// Returns the number of trailing ones in the binary representation
/// of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 0b1010111u32;"]
/// assert_eq!(n.trailing_ones(), 3);
///
#[doc = "let zero = 0u32;"]
/// assert_eq!(zero.trailing_ones(), 0);
///
#[doc = "let max = u32::MAX;"]
#[doc = "assert_eq!(max.trailing_ones(), 32);"]
/// ```
#[stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn trailing_ones(self) -> u32 { (!self).trailing_zeros() }
/// Returns the minimum number of bits required to represent `self`.
///
/// This method returns zero if `self` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0_u32.bit_width(), 0);"]
#[doc = "assert_eq!(0b111_u32.bit_width(), 3);"]
#[doc = "assert_eq!(0b1110_u32.bit_width(), 4);"]
#[doc = "assert_eq!(u32::MAX.bit_width(), 32);"]
/// ```
#[stable(feature = "uint_bit_width", since = "1.97.0")]
#[rustc_const_stable(feature = "uint_bit_width", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn bit_width(self) -> u32 { Self::BITS - self.leading_zeros() }
/// Returns `self` with only the most significant bit set, or `0` if
/// the input is `0`.
///
/// # Examples
///
/// ```
#[doc = "let n: u32 = 0b_01100100;"]
///
/// assert_eq!(n.isolate_highest_one(), 0b_01000000);
#[doc = "assert_eq!(0_u32.isolate_highest_one(), 0);"]
/// ```
#[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn isolate_highest_one(self) -> Self {
self &
(((1 as u32) << (<u32>::BITS - 1)).wrapping_shr(self.leading_zeros()))
}
/// Returns `self` with only the least significant bit set, or `0` if
/// the input is `0`.
///
/// # Examples
///
/// ```
#[doc = "let n: u32 = 0b_01100100;"]
///
/// assert_eq!(n.isolate_lowest_one(), 0b_00000100);
#[doc = "assert_eq!(0_u32.isolate_lowest_one(), 0);"]
/// ```
#[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn isolate_lowest_one(self) -> Self { self & self.wrapping_neg() }
/// Returns the index of the highest bit set to one in `self`, or `None`
/// if `self` is `0`.
///
/// Note that this is equivalent to [`checked_ilog2`](Self::checked_ilog2).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0b0_u32.highest_one(), None);"]
#[doc = "assert_eq!(0b1_u32.highest_one(), Some(0));"]
#[doc = "assert_eq!(0b1_0000_u32.highest_one(), Some(4));"]
#[doc = "assert_eq!(0b1_1111_u32.highest_one(), Some(4));"]
/// ```
#[stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn highest_one(self) -> Option<u32> {
match NonZero::new(self) {
Some(v) => Some(v.highest_one()),
None => None,
}
}
/// Returns the index of the lowest bit set to one in `self`, or `None`
/// if `self` is `0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0b0_u32.lowest_one(), None);"]
#[doc = "assert_eq!(0b1_u32.lowest_one(), Some(0));"]
#[doc = "assert_eq!(0b1_0000_u32.lowest_one(), Some(4));"]
#[doc = "assert_eq!(0b1_1111_u32.lowest_one(), Some(0));"]
/// ```
#[stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn lowest_one(self) -> Option<u32> {
match NonZero::new(self) {
Some(v) => Some(v.lowest_one()),
None => None,
}
}
/// Returns the bit pattern of `self` reinterpreted as a signed integer of the same size.
///
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
/// the same.
///
/// # Examples
///
/// ```
#[doc = "let n = u32::MAX;"]
///
#[doc = "assert_eq!(n.cast_signed(), -1i32);"]
/// ```
#[stable(feature = "integer_sign_cast", since = "1.87.0")]
#[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_signed(self) -> i32 { self as i32 }
/// Saturating conversion of `self` to a signed integer of the same size.
///
/// The signed integer's maximum value is returned if `self` is larger
/// than the maximum positive value representable by the signed integer.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`checked_cast_signed`](Self::checked_cast_signed),
/// or [`strict_cast_signed`](Self::strict_cast_signed).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = u32::MAX;"]
///
#[doc = "assert_eq!(n.saturating_cast_signed(), i32::MAX);"]
#[doc = "assert_eq!(64u32.saturating_cast_signed(), 64i32);"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_cast_signed(self) -> i32 {
if self <= <i32>::MAX.cast_unsigned() {
self.cast_signed()
} else { <i32>::MAX }
}
/// Checked conversion of `self` to a signed integer of the same size,
/// returning `None` if `self` is larger than the signed integer's
/// maximum value.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`saturating_cast_signed`](Self::saturating_cast_signed),
/// or [`strict_cast_signed`](Self::strict_cast_signed).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = u32::MAX;"]
///
#[doc = "assert_eq!(n.checked_cast_signed(), None);"]
#[doc = "assert_eq!(64u32.checked_cast_signed(), Some(64i32));"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn checked_cast_signed(self) -> Option<i32> {
if self <= <i32>::MAX.cast_unsigned() {
Some(self.cast_signed())
} else { None }
}
/// Strict conversion of `self` to a signed integer of the same size,
/// which panics if `self` is larger than the signed integer's maximum
/// value.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`checked_cast_signed`](Self::checked_cast_signed),
/// or [`saturating_cast_signed`](Self::saturating_cast_signed).
///
/// # Examples
///
/// ```should_panic
/// #![feature(integer_cast_extras)]
#[doc = "let _ = u32::MAX.strict_cast_signed();"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_cast_signed(self) -> i32 {
match self.checked_cast_signed() {
Some(n) => n,
None => imp::overflow_panic::cast_integer(),
}
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `<<` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x10000b3u32;"]
#[doc = "let m = 0xb301;"]
///
#[doc = "assert_eq!(n.rotate_left(8), m);"]
#[doc = "assert_eq!(n.rotate_left(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
pub const fn rotate_left(self, n: u32) -> Self {
return intrinsics::rotate_left(self, n);
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `>>` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0xb301u32;"]
#[doc = "let m = 0x10000b3;"]
///
#[doc = "assert_eq!(n.rotate_right(8), m);"]
#[doc = "assert_eq!(n.rotate_right(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
pub const fn rotate_right(self, n: u32) -> Self {
return intrinsics::rotate_right(self, n);
}
/// Performs a left funnel shift (concatenates `self` with `rhs`, with `self`
/// making up the most significant half, then shifts the combined value left
/// by `n`, and most significant half is extracted to produce the result).
///
/// Please note this isn't the same operation as the `<<` shifting operator or
/// [`rotate_left`](Self::rotate_left), although `a.funnel_shl(a, n)` is *equivalent*
/// to `a.rotate_left(n)`.
///
/// # Panics
///
/// If `n` is greater than or equal to the number of bits in `self`
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(funnel_shifts)]
#[doc = "let a = 0x10000b3u32;"]
#[doc = "let b = 0x2fe78e45u32;"]
#[doc = "let m = 0xb32f;"]
///
#[doc = "assert_eq!(a.funnel_shl(b, 8), m);"]
/// ```
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn funnel_shl(self, rhs: Self, n: u32) -> Self {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift left with overflow"));
}
};
unsafe { self.unchecked_funnel_shl(rhs, n) }
}
/// Performs a right funnel shift (concatenates `self` and `rhs`, with `self`
/// making up the most significant half, then shifts the combined value right
/// by `n`, and least significant half is extracted to produce the result).
///
/// Please note this isn't the same operation as the `>>` shifting operator or
/// [`rotate_right`](Self::rotate_right), although `a.funnel_shr(a, n)` is *equivalent*
/// to `a.rotate_right(n)`.
///
/// # Panics
///
/// If `n` is greater than or equal to the number of bits in `self`
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(funnel_shifts)]
#[doc = "let a = 0x10000b3u32;"]
#[doc = "let b = 0x2fe78e45u32;"]
#[doc = "let m = 0xb32fe78e;"]
///
#[doc = "assert_eq!(a.funnel_shr(b, 8), m);"]
/// ```
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn funnel_shr(self, rhs: Self, n: u32) -> Self {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift right with overflow"));
}
};
unsafe { self.unchecked_funnel_shr(rhs, n) }
}
/// Unchecked funnel shift left.
///
/// # Safety
///
/// This results in undefined behavior if `n` is greater than or equal to
#[doc = "`u32::BITS`,"]
/// i.e. when [`funnel_shl`](Self::funnel_shl) would panic.
///
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_funnel_shl(self, low: Self, n: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(n: u32) {
if !(n < <u32>::BITS) {
let msg =
"unsafe precondition(s) violated: u32::unchecked_funnel_shl cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(n); }
};
unsafe { intrinsics::unchecked_funnel_shl(self, low, n) }
}
/// Unchecked funnel shift right.
///
/// # Safety
///
/// This results in undefined behavior if `n` is greater than or equal to
#[doc = "`u32::BITS`,"]
/// i.e. when [`funnel_shr`](Self::funnel_shr) would panic.
///
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_funnel_shr(self, low: Self, n: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(n: u32) {
if !(n < <u32>::BITS) {
let msg =
"unsafe precondition(s) violated: u32::unchecked_funnel_shr cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(n); }
};
unsafe { intrinsics::unchecked_funnel_shr(self, low, n) }
}
/// Performs a carry-less multiplication, returning the lower bits.
///
/// This operation is similar to long multiplication in base 2, except that exclusive or is
/// used instead of addition. The implementation is equivalent to:
///
/// ```no_run
#[doc = "pub fn carryless_mul(lhs: u32, rhs: u32) -> u32{"]
/// let mut retval = 0;
#[doc = " for i in 0..u32::BITS {"]
/// if (rhs >> i) & 1 != 0 {
/// // long multiplication would use +=
/// retval ^= lhs << i;
/// }
/// }
/// retval
/// }
/// ```
///
/// The actual implementation is more efficient, and on some platforms lowers directly to a
/// dedicated instruction.
///
/// # Uses
///
/// Carryless multiplication can be used to turn a bitmask of quote characters into a
/// bit mask of characters surrounded by quotes:
///
/// ```no_run
/// r#"abc xxx "foobar" zzz "a"!"#; // input string
/// 0b0000000010000001000001010; // quote_mask
/// 0b0000000001111110000000100; // quote_mask.carryless_mul(!0) & !quote_mask
/// ```
///
/// Another use is in cryptography, where carryless multiplication allows for efficient
/// implementations of polynomial multiplication in `GF(2)[X]`, the polynomial ring
/// over `GF(2)`.
///
/// # Examples
///
/// ```
/// #![feature(uint_carryless_mul)]
///
#[doc = "let a = 0x56789012u32;"]
#[doc = "let b = 0xf52ecd34u32;"]
///
#[doc = "assert_eq!(a.carryless_mul(b), 0x9b980928);"]
/// ```
#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
#[doc(alias = "clmul")]
#[unstable(feature = "uint_carryless_mul", issue = "152080")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn carryless_mul(self, rhs: Self) -> Self {
intrinsics::carryless_mul(self, rhs)
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x12345678u32;"]
/// let m = n.swap_bytes();
///
#[doc = "assert_eq!(m, 0x78563412);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn swap_bytes(self) -> Self {
intrinsics::bswap(self as u32) as Self
}
/// Returns an integer with the bit locations specified by `mask` packed
/// contiguously into the least significant bits of the result.
/// ```
/// #![feature(uint_gather_scatter_bits)]
#[doc = "let n: u32 = 0b1011_1100;"]
///
/// assert_eq!(n.extract_bits(0b0010_0100), 0b0000_0011);
/// assert_eq!(n.extract_bits(0xF0), 0b0000_1011);
/// ```
#[doc(alias = "pext")]
#[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn extract_bits(self, mask: Self) -> Self {
imp::int_bits::u32::extract_impl(self as u32, mask as u32) as u32
}
/// Returns an integer with the least significant bits of `self`
/// distributed to the bit locations specified by `mask`.
/// ```
/// #![feature(uint_gather_scatter_bits)]
#[doc = "let n: u32 = 0b1010_1101;"]
///
/// assert_eq!(n.deposit_bits(0b0101_0101), 0b0101_0001);
/// assert_eq!(n.deposit_bits(0xF0), 0b1101_0000);
/// ```
#[doc(alias = "pdep")]
#[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn deposit_bits(self, mask: Self) -> Self {
imp::int_bits::u32::deposit_impl(self as u32, mask as u32) as u32
}
/// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
/// second least-significant bit becomes second most-significant bit, etc.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x12345678u32;"]
/// let m = n.reverse_bits();
///
#[doc = "assert_eq!(m, 0x1e6a2c48);"]
#[doc = "assert_eq!(0, 0u32.reverse_bits());"]
/// ```
#[stable(feature = "reverse_bits", since = "1.37.0")]
#[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn reverse_bits(self) -> Self {
intrinsics::bitreverse(self as u32) as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au32;"]
///
/// if cfg!(target_endian = "big") {
#[doc = " assert_eq!(u32::from_be(n), n)"]
/// } else {
#[doc = " assert_eq!(u32::from_be(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use]
#[inline(always)]
pub const fn from_be(x: Self) -> Self { x.swap_bytes() }
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au32;"]
///
/// if cfg!(target_endian = "little") {
#[doc = " assert_eq!(u32::from_le(n), n)"]
/// } else {
#[doc = " assert_eq!(u32::from_le(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use]
#[inline(always)]
pub const fn from_le(x: Self) -> Self { x }
/// Converts `self` to big endian from the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au32;"]
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn to_be(self) -> Self { self.swap_bytes() }
/// Converts `self` to little endian from the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au32;"]
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn to_le(self) -> Self { self }
/// Checked integer addition. Computes `self + rhs`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((u32::MAX - 2).checked_add(1), Some(u32::MAX - 1));"]
#[doc = "assert_eq!((u32::MAX - 2).checked_add(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(intrinsics::add_with_overflow(self, rhs).1) {
None
} else { Some(unsafe { intrinsics::unchecked_add(self, rhs) }) }
}
/// Strict integer addition. Computes `self + rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((u32::MAX - 2).strict_add(1), u32::MAX - 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (u32::MAX - 2).strict_add(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_add(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Unchecked integer addition. Computes `self + rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_add(y)` is semantically equivalent to calling
/// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_add`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self + rhs > u32::MAX`,"]
/// i.e. when [`checked_add`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_add`]: u32::checked_add"]
#[doc = "[`wrapping_add`]: u32::wrapping_add"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u32, rhs: u32) {
if !!lhs.overflowing_add(rhs).1 {
let msg =
"unsafe precondition(s) violated: u32::unchecked_add cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_add(self, rhs) }
}
/// Checked addition with a signed integer. Computes `self + rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u32.checked_add_signed(2), Some(3));"]
#[doc = "assert_eq!(1u32.checked_add_signed(-2), None);"]
#[doc = "assert_eq!((u32::MAX - 2).checked_add_signed(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add_signed(self, rhs: i32) -> Option<Self> {
let (a, b) = self.overflowing_add_signed(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict addition with a signed integer. Computes `self + rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u32.strict_add_signed(2), 3);"]
/// ```
///
/// The following panic because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1u32.strict_add_signed(-2);"]
/// ```
///
/// ```should_panic
#[doc = "let _ = (u32::MAX - 2).strict_add_signed(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add_signed(self, rhs: i32) -> Self {
let (a, b) = self.overflowing_add_signed(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Checked integer subtraction. Computes `self - rhs`, returning
/// `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u32.checked_sub(1), Some(0));"]
#[doc = "assert_eq!(0u32.checked_sub(1), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
if self < rhs {
None
} else { Some(unsafe { intrinsics::unchecked_sub(self, rhs) }) }
}
/// Strict integer subtraction. Computes `self - rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u32.strict_sub(1), 0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0u32.strict_sub(1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_sub(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
/// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_sub`].
///
/// If you find yourself writing code like this:
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if foo >= bar {
/// // SAFETY: just checked it will not overflow
/// let diff = unsafe { foo.unchecked_sub(bar) };
/// // ... use diff ...
/// }
/// ```
///
/// Consider changing it to
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if let Some(diff) = foo.checked_sub(bar) {
/// // ... use diff ...
/// }
/// ```
///
/// As that does exactly the same thing -- including telling the optimizer
/// that the subtraction cannot overflow -- but avoids needing `unsafe`.
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self - rhs < u32::MIN`,"]
/// i.e. when [`checked_sub`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_sub`]: u32::checked_sub"]
#[doc = "[`wrapping_sub`]: u32::wrapping_sub"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u32, rhs: u32) {
if !!lhs.overflowing_sub(rhs).1 {
let msg =
"unsafe precondition(s) violated: u32::unchecked_sub cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_sub(self, rhs) }
}
/// Checked subtraction with a signed integer. Computes `self - rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u32.checked_sub_signed(2), None);"]
#[doc = "assert_eq!(1u32.checked_sub_signed(-2), Some(3));"]
#[doc = "assert_eq!((u32::MAX - 2).checked_sub_signed(-4), None);"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub_signed(self, rhs: i32) -> Option<Self> {
let (res, overflow) = self.overflowing_sub_signed(rhs);
if !overflow { Some(res) } else { None }
}
/// Strict subtraction with a signed integer. Computes `self - rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3u32.strict_sub_signed(2), 1);"]
/// ```
///
/// The following panic because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1u32.strict_sub_signed(2);"]
/// ```
///
/// ```should_panic
#[doc = "let _ = (u32::MAX).strict_sub_signed(-1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub_signed(self, rhs: i32) -> Self {
let (a, b) = self.overflowing_sub_signed(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
#[doc =
"Checked integer subtraction. Computes `self - rhs` and checks if the result fits into an [`i32`], returning `None` if overflow occurred."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10u32.checked_signed_diff(2), Some(8));"]
#[doc = "assert_eq!(2u32.checked_signed_diff(10), Some(-8));"]
#[doc = "assert_eq!(u32::MAX.checked_signed_diff(i32::MAX as u32), None);"]
#[doc =
"assert_eq!((i32::MAX as u32).checked_signed_diff(u32::MAX), Some(i32::MIN));"]
#[doc = "assert_eq!((i32::MAX as u32 + 1).checked_signed_diff(0), None);"]
#[doc = "assert_eq!(u32::MAX.checked_signed_diff(u32::MAX), Some(0));"]
/// ```
#[stable(feature = "unsigned_signed_diff", since = "1.91.0")]
#[rustc_const_stable(feature = "unsigned_signed_diff", since = "1.91.0")]
#[inline]
pub const fn checked_signed_diff(self, rhs: Self) -> Option<i32> {
let res = self.wrapping_sub(rhs) as i32;
let overflow = (self >= rhs) == (res < 0);
if !overflow { Some(res) } else { None }
}
/// Checked integer multiplication. Computes `self * rhs`, returning
/// `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u32.checked_mul(1), Some(5));"]
#[doc = "assert_eq!(u32::MAX.checked_mul(2), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer multiplication. Computes `self * rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u32.strict_mul(1), 5);"]
/// ```
///
/// The following panics because of overflow:
///
/// ``` should_panic
#[doc = "let _ = u32::MAX.strict_mul(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_mul(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_mul(rhs);
if b { imp::overflow_panic::mul() } else { a }
}
/// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
/// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_mul`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self * rhs > u32::MAX`,"]
/// i.e. when [`checked_mul`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_mul`]: u32::checked_mul"]
#[doc = "[`wrapping_mul`]: u32::wrapping_mul"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u32, rhs: u32) {
if !!lhs.overflowing_mul(rhs).1 {
let msg =
"unsafe precondition(s) violated: u32::unchecked_mul cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_mul(self, rhs) }
}
/// Checked integer division. Computes `self / rhs`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128u32.checked_div(2), Some(64));"]
#[doc = "assert_eq!(1u32.checked_div(0), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(unsafe { intrinsics::unchecked_div(self, rhs) }) }
}
/// Strict integer division. Computes `self / rhs`.
///
/// Strict division on unsigned types is just normal division. There's no
/// way overflow could ever happen. This function exists so that all
/// operations are accounted for in the strict operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u32.strict_div(10), 10);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1u32).strict_div(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_div(self, rhs: Self) -> Self { self / rhs }
/// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128u32.checked_div_euclid(2), Some(64));"]
#[doc = "assert_eq!(1u32.checked_div_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(self.div_euclid(rhs)) }
}
/// Strict Euclidean division. Computes `self.div_euclid(rhs)`.
///
/// Strict division on unsigned types is just normal division. There's no
/// way overflow could ever happen. This function exists so that all
/// operations are accounted for in the strict operations. Since, for the
/// positive integers, all common definitions of division are equal, this
/// is exactly equal to `self.strict_div(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u32.strict_div_euclid(10), 10);"]
/// ```
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1u32).strict_div_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Checked integer division without remainder. Computes `self / rhs`,
/// returning `None` if `rhs == 0` or if `self % rhs != 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64u32.checked_div_exact(2), Some(32));"]
#[doc = "assert_eq!(64u32.checked_div_exact(32), Some(2));"]
#[doc = "assert_eq!(64u32.checked_div_exact(0), None);"]
#[doc = "assert_eq!(65u32.checked_div_exact(2), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_exact(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else {
unsafe {
if intrinsics::unlikely(intrinsics::unchecked_rem(self, rhs) != 0)
{
None
} else { Some(intrinsics::exact_div(self, rhs)) }
}
}
}
/// Integer division without remainder. Computes `self / rhs`, returning `None` if `self % rhs != 0`.
///
/// # Panics
///
/// This function will panic if `rhs == 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64u32.div_exact(2), Some(32));"]
#[doc = "assert_eq!(64u32.div_exact(32), Some(2));"]
#[doc = "assert_eq!(65u32.div_exact(2), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn div_exact(self, rhs: Self) -> Option<Self> {
if self % rhs != 0 { None } else { Some(self / rhs) }
}
/// Unchecked integer division without remainder. Computes `self / rhs`.
///
/// # Safety
///
/// This results in undefined behavior when `rhs == 0` or `self % rhs != 0`,
/// i.e. when [`checked_div_exact`](Self::checked_div_exact) would return `None`.
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_div_exact(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u32, rhs: u32) {
if !(rhs > 0 && lhs % rhs == 0) {
let msg =
"unsafe precondition(s) violated: u32::unchecked_div_exact divide by zero or leave a remainder\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::exact_div(self, rhs) }
}
/// Checked integer remainder. Computes `self % rhs`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u32.checked_rem(2), Some(1));"]
#[doc = "assert_eq!(5u32.checked_rem(0), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(unsafe { intrinsics::unchecked_rem(self, rhs) }) }
}
/// Strict integer remainder. Computes `self % rhs`.
///
/// Strict remainder calculation on unsigned types is just the regular
/// remainder calculation. There's no way overflow could ever happen.
/// This function exists so that all operations are accounted for in the
/// strict operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u32.strict_rem(10), 0);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5u32.strict_rem(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_rem(self, rhs: Self) -> Self { self % rhs }
/// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u32.checked_rem_euclid(2), Some(1));"]
#[doc = "assert_eq!(5u32.checked_rem_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(self.rem_euclid(rhs)) }
}
/// Strict Euclidean modulo. Computes `self.rem_euclid(rhs)`.
///
/// Strict modulo calculation on unsigned types is just the regular
/// remainder calculation. There's no way overflow could ever happen.
/// This function exists so that all operations are accounted for in the
/// strict operations. Since, for the positive integers, all common
/// definitions of division are equal, this is exactly equal to
/// `self.strict_rem(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u32.strict_rem_euclid(10), 0);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5u32.strict_rem_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Same value as `self | other`, but UB if any bit position is set in both inputs.
///
/// This is a situational micro-optimization for places where you'd rather
/// use addition on some platforms and bitwise or on other platforms, based
/// on exactly which instructions combine better with whatever else you're
/// doing. Note that there's no reason to bother using this for places
/// where it's clear from the operations involved that they can't overlap.
/// For example, if you're combining `u16`s into a `u32` with
/// `((a as u32) << 16) | (b as u32)`, that's fine, as the backend will
/// know those sides of the `|` are disjoint without needing help.
///
/// # Examples
///
/// ```
/// #![feature(disjoint_bitor)]
///
/// // SAFETY: `1` and `4` have no bits in common.
/// unsafe {
#[doc = " assert_eq!(1_u32.unchecked_disjoint_bitor(4), 5);"]
/// }
/// ```
///
/// # Safety
///
/// Requires that `(self & other) == 0`, otherwise it's immediate UB.
///
/// Equivalently, requires that `(self | other) == (self + other)`.
#[unstable(feature = "disjoint_bitor", issue = "135758")]
#[rustc_const_unstable(feature = "disjoint_bitor", issue = "135758")]
#[inline]
pub const unsafe fn unchecked_disjoint_bitor(self, other: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u32, rhs: u32) {
if !((lhs & rhs) == 0) {
let msg =
"unsafe precondition(s) violated: u32::unchecked_disjoint_bitor cannot have overlapping bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, other);
}
};
unsafe { intrinsics::disjoint_bitor(self, other) }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// This method might not be optimized owing to implementation details;
/// [`ilog2`](Self::ilog2) can produce results more efficiently for base 2,
/// and [`ilog10`](Self::ilog10) can produce results more efficiently for base 10.
///
/// # Panics
///
/// This function will panic if `self` is zero, or if `base` is less than 2.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u32.ilog(5), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog(self, base: Self) -> u32 {
if !(base >= 2) {
{
crate::panicking::panic_fmt(format_args!("base of integer logarithm must be at least 2"));
}
};
if let Some(log) = self.checked_ilog(base) {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the base 2 logarithm of the number, rounded down.
///
/// # Panics
///
/// This function will panic if `self` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u32.ilog2(), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog2(self) -> u32 {
if let Some(log) = self.checked_ilog2() {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// # Panics
///
/// This function will panic if `self` is zero.
///
/// # Example
///
/// ```
#[doc = "assert_eq!(10u32.ilog10(), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog10(self) -> u32 {
if let Some(log) = self.checked_ilog10() {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// Returns `None` if the number is zero, or if the base is not at least 2.
///
/// This method might not be optimized owing to implementation details;
/// `checked_ilog2` can produce results more efficiently for base 2, and
/// `checked_ilog10` can produce results more efficiently for base 10.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u32.checked_ilog(5), Some(1));"]
#[doc = "assert_eq!(4u32.checked_ilog(5), Some(0));"]
#[doc = "assert_eq!(5u32.checked_ilog(0), None);"]
#[doc = "assert_eq!(5u32.checked_ilog(1), None);"]
#[doc = "assert_eq!(0u32.checked_ilog(1), None);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog(self, base: Self) -> Option<u32> {
if core::intrinsics::is_val_statically_known(base) {
if base.is_power_of_two() && base > 1 {
let k = base.ilog2();
return Some(match self.checked_ilog2() {
Some(x) => x,
None => return None,
} / k);
}
if base == 10 { return self.checked_ilog10(); }
}
if self <= 0 || base <= 1 {
None
} else if self < base {
Some(0)
} else {
let mut n = 1;
let mut r = base;
if Self::BITS == 128 {
n = self.ilog2() / (base.ilog2() + 1);
r = base.pow(n);
}
while r <= self / base { n += 1; r *= base; }
Some(n)
}
}
/// Returns the base 2 logarithm of the number, rounded down.
///
/// Returns `None` if the number is zero.
///
/// Note that this is equivalent to [`highest_one`](Self::highest_one).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u32.checked_ilog2(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog2(self) -> Option<u32> {
match NonZero::new(self) { Some(x) => Some(x.ilog2()), None => None, }
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// Returns `None` if the number is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10u32.checked_ilog10(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog10(self) -> Option<u32> {
match NonZero::new(self) { Some(x) => Some(x.ilog10()), None => None, }
}
/// Checked negation. Computes `-self`, returning `None` unless `self ==
/// 0`.
///
/// Note that negating any positive integer will overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0u32.checked_neg(), Some(0));"]
#[doc = "assert_eq!(1u32.checked_neg(), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_neg(self) -> Option<Self> {
let (a, b) = self.overflowing_neg();
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict negation. Computes `-self`, panicking unless `self ==
/// 0`.
///
/// Note that negating any positive integer will overflow.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0u32.strict_neg(), 0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1u32.strict_neg();"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_neg(self) -> Self {
let (a, b) = self.overflowing_neg();
if b { imp::overflow_panic::neg() } else { a }
}
/// Checked shift left. Computes `self << rhs`, returning `None`
/// if `rhs` is larger than or equal to the number of bits in `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1u32.checked_shl(4), Some(0x10));"]
#[doc = "assert_eq!(0x10u32.checked_shl(129), None);"]
#[doc = "assert_eq!(0x10u32.checked_shl(31), Some(0));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
if rhs < Self::BITS {
Some(unsafe { self.unchecked_shl(rhs) })
} else { None }
}
/// Strict shift left. Computes `self << rhs`, panicking if `rhs` is larger
/// than or equal to the number of bits in `self`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1u32.strict_shl(4), 0x10);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0x10u32.strict_shl(129);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_shl(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_shl(rhs);
if b { imp::overflow_panic::shl() } else { a }
}
/// Unchecked shift left. Computes `self << rhs`, assuming that
/// `rhs` is less than the number of bits in `self`.
///
/// # Safety
///
/// This results in undefined behavior if `rhs` is larger than
/// or equal to the number of bits in `self`,
/// i.e. when [`checked_shl`] would return `None`.
///
#[doc = "[`checked_shl`]: u32::checked_shl"]
#[stable(feature = "unchecked_shifts", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_shl(self, rhs: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(rhs: u32) {
if !(rhs < <u32>::BITS) {
let msg =
"unsafe precondition(s) violated: u32::unchecked_shl cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(rhs); }
};
unsafe { intrinsics::unchecked_shl(self, rhs) }
}
/// Unbounded shift left. Computes `self << rhs`, without bounding the value of `rhs`.
///
/// If `rhs` is larger or equal to the number of bits in `self`,
/// the entire value is shifted out, and `0` is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1_u32.unbounded_shl(4), 0x10);"]
#[doc = "assert_eq!(0x1_u32.unbounded_shl(129), 0);"]
#[doc = "assert_eq!(0b101_u32.unbounded_shl(0), 0b101);"]
#[doc = "assert_eq!(0b101_u32.unbounded_shl(1), 0b1010);"]
#[doc = "assert_eq!(0b101_u32.unbounded_shl(2), 0b10100);"]
#[doc = "assert_eq!(42_u32.unbounded_shl(32), 0);"]
#[doc = "assert_eq!(42_u32.unbounded_shl(1).unbounded_shl(31), 0);"]
///
#[doc = "let start : u32 = 13;"]
/// let mut running = start;
/// for i in 0..160 {
/// // The unbounded shift left by i is the same as `<< 1` i times
/// assert_eq!(running, start.unbounded_shl(i));
/// // Which is not always the case for a wrapping shift
#[doc = " assert_eq!(running == start.wrapping_shl(i), i < 32);"]
///
/// running <<= 1;
/// }
/// ```
#[stable(feature = "unbounded_shifts", since = "1.87.0")]
#[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unbounded_shl(self, rhs: u32) -> u32 {
if rhs < Self::BITS { unsafe { self.unchecked_shl(rhs) } } else { 0 }
}
/// Exact shift left. Computes `self << rhs` as long as it can be reversed losslessly.
///
/// Returns `None` if any non-zero bits would be shifted out or if `rhs` >=
#[doc = "`u32::BITS`."]
/// Otherwise, returns `Some(self << rhs)`.
///
/// # Examples
///
/// ```
/// #![feature(exact_bitshifts)]
///
#[doc = "assert_eq!(0x1u32.shl_exact(4), Some(0x10));"]
#[doc = "assert_eq!(0x1u32.shl_exact(129), None);"]
/// ```
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn shl_exact(self, rhs: u32) -> Option<u32> {
if rhs <= self.leading_zeros() && rhs < <u32>::BITS {
Some(unsafe { self.unchecked_shl(rhs) })
} else { None }
}
/// Unchecked exact shift left. Computes `self << rhs`, assuming the operation can be
/// losslessly reversed `rhs` cannot be larger than
#[doc = "`u32::BITS`."]
///
/// # Safety
///
/// This results in undefined behavior when `rhs > self.leading_zeros() || rhs >=
#[doc = "u32::BITS`"]
/// i.e. when
#[doc = "[`u32::shl_exact`]"]
/// would return `None`.
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_shl_exact(self, rhs: u32) -> u32 {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(zeros: u32, bits: u32, rhs: u32) {
if !(rhs <= zeros && rhs < bits) {
let msg =
"unsafe precondition(s) violated: u32::unchecked_shl_exact cannot shift out non-zero bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_library_ub() {
precondition_check(self.leading_zeros(), <u32>::BITS, rhs);
}
};
unsafe { self.unchecked_shl(rhs) }
}
/// Checked shift right. Computes `self >> rhs`, returning `None`
/// if `rhs` is larger than or equal to the number of bits in `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10u32.checked_shr(4), Some(0x1));"]
#[doc = "assert_eq!(0x10u32.checked_shr(129), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
if rhs < Self::BITS {
Some(unsafe { self.unchecked_shr(rhs) })
} else { None }
}
/// Strict shift right. Computes `self >> rhs`, panicking if `rhs` is
/// larger than or equal to the number of bits in `self`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10u32.strict_shr(4), 0x1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0x10u32.strict_shr(129);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_shr(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_shr(rhs);
if b { imp::overflow_panic::shr() } else { a }
}
/// Unchecked shift right. Computes `self >> rhs`, assuming that
/// `rhs` is less than the number of bits in `self`.
///
/// # Safety
///
/// This results in undefined behavior if `rhs` is larger than
/// or equal to the number of bits in `self`,
/// i.e. when [`checked_shr`] would return `None`.
///
#[doc = "[`checked_shr`]: u32::checked_shr"]
#[stable(feature = "unchecked_shifts", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_shr(self, rhs: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(rhs: u32) {
if !(rhs < <u32>::BITS) {
let msg =
"unsafe precondition(s) violated: u32::unchecked_shr cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(rhs); }
};
unsafe { intrinsics::unchecked_shr(self, rhs) }
}
/// Unbounded shift right. Computes `self >> rhs`, without bounding the value of `rhs`.
///
/// If `rhs` is larger or equal to the number of bits in `self`,
/// the entire value is shifted out, and `0` is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10_u32.unbounded_shr(4), 0x1);"]
#[doc = "assert_eq!(0x10_u32.unbounded_shr(129), 0);"]
#[doc = "assert_eq!(0b1010_u32.unbounded_shr(0), 0b1010);"]
#[doc = "assert_eq!(0b1010_u32.unbounded_shr(1), 0b101);"]
#[doc = "assert_eq!(0b1010_u32.unbounded_shr(2), 0b10);"]
#[doc = "assert_eq!(42_u32.unbounded_shr(32), 0);"]
#[doc = "assert_eq!(42_u32.unbounded_shr(1).unbounded_shr(31), 0);"]
///
#[doc = "let start = u32::rotate_right(13, 4);"]
/// let mut running = start;
/// for i in 0..160 {
/// // The unbounded shift right by i is the same as `>> 1` i times
/// assert_eq!(running, start.unbounded_shr(i));
/// // Which is not always the case for a wrapping shift
#[doc = " assert_eq!(running == start.wrapping_shr(i), i < 32);"]
///
/// running >>= 1;
/// }
/// ```
#[stable(feature = "unbounded_shifts", since = "1.87.0")]
#[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unbounded_shr(self, rhs: u32) -> u32 {
if rhs < Self::BITS { unsafe { self.unchecked_shr(rhs) } } else { 0 }
}
/// Exact shift right. Computes `self >> rhs` as long as it can be reversed losslessly.
///
/// Returns `None` if any non-zero bits would be shifted out or if `rhs` >=
#[doc = "`u32::BITS`."]
/// Otherwise, returns `Some(self >> rhs)`.
///
/// # Examples
///
/// ```
/// #![feature(exact_bitshifts)]
///
#[doc = "assert_eq!(0x10u32.shr_exact(4), Some(0x1));"]
#[doc = "assert_eq!(0x10u32.shr_exact(5), None);"]
/// ```
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn shr_exact(self, rhs: u32) -> Option<u32> {
if rhs <= self.trailing_zeros() && rhs < <u32>::BITS {
Some(unsafe { self.unchecked_shr(rhs) })
} else { None }
}
/// Unchecked exact shift right. Computes `self >> rhs`, assuming the operation can be
/// losslessly reversed and `rhs` cannot be larger than
#[doc = "`u32::BITS`."]
///
/// # Safety
///
/// This results in undefined behavior when `rhs > self.trailing_zeros() || rhs >=
#[doc = "u32::BITS`"]
/// i.e. when
#[doc = "[`u32::shr_exact`]"]
/// would return `None`.
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_shr_exact(self, rhs: u32) -> u32 {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(zeros: u32, bits: u32, rhs: u32) {
if !(rhs <= zeros && rhs < bits) {
let msg =
"unsafe precondition(s) violated: u32::unchecked_shr_exact cannot shift out non-zero bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_library_ub() {
precondition_check(self.trailing_zeros(), <u32>::BITS, rhs);
}
};
unsafe { self.unchecked_shr(rhs) }
}
/// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u32.checked_pow(5), Some(32));"]
#[doc = "assert_eq!(0_u32.checked_pow(0), Some(1));"]
#[doc = "assert_eq!(u32::MAX.checked_pow(2), None);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
let mut base = self;
let mut acc: Self = 1;
if intrinsics::is_val_statically_known(base) && base.is_power_of_two() {
let k = base.ilog2();
let shift =
match k.checked_mul(exp) { Some(x) => x, None => return None, };
return (1 as Self).checked_shl(shift);
}
if exp == 0 { return Some(1); }
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 {
acc =
match acc.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
exp /= 2;
base =
match base.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
return acc.checked_mul(base);
}
loop {
if (exp & 1) == 1 {
acc =
match acc.checked_mul(base) {
Some(x) => x,
None => return None,
};
if exp == 1 { return Some(acc); }
}
exp /= 2;
base =
match base.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
}
/// Strict exponentiation. Computes `self.pow(exp)`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u32.strict_pow(5), 32);"]
#[doc = "assert_eq!(0_u32.strict_pow(0), 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = u32::MAX.strict_pow(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) {
None => imp::overflow_panic::pow(),
Some(a) => a,
}
}
/// Saturating integer addition. Computes `self + rhs`, saturating at
/// the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u32.saturating_add(1), 101);"]
#[doc = "assert_eq!(u32::MAX.saturating_add(127), u32::MAX);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[inline(always)]
pub const fn saturating_add(self, rhs: Self) -> Self {
intrinsics::saturating_add(self, rhs)
}
/// Saturating addition with a signed integer. Computes `self + rhs`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u32.saturating_add_signed(2), 3);"]
#[doc = "assert_eq!(1u32.saturating_add_signed(-2), 0);"]
#[doc = "assert_eq!((u32::MAX - 2).saturating_add_signed(4), u32::MAX);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_add_signed(self, rhs: i32) -> Self {
let (res, overflow) = self.overflowing_add(rhs as Self);
if overflow == (rhs < 0) { res } else if overflow { Self::MAX } else { 0 }
}
/// Saturating integer subtraction. Computes `self - rhs`, saturating
/// at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u32.saturating_sub(27), 73);"]
#[doc = "assert_eq!(13u32.saturating_sub(127), 0);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[inline(always)]
pub const fn saturating_sub(self, rhs: Self) -> Self {
intrinsics::saturating_sub(self, rhs)
}
/// Saturating integer subtraction. Computes `self` - `rhs`, saturating at
/// the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u32.saturating_sub_signed(2), 0);"]
#[doc = "assert_eq!(1u32.saturating_sub_signed(-2), 3);"]
#[doc = "assert_eq!((u32::MAX - 2).saturating_sub_signed(-4), u32::MAX);"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_sub_signed(self, rhs: i32) -> Self {
let (res, overflow) = self.overflowing_sub_signed(rhs);
if !overflow { res } else if rhs < 0 { Self::MAX } else { 0 }
}
/// Saturating integer multiplication. Computes `self * rhs`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u32.saturating_mul(10), 20);"]
#[doc = "assert_eq!((u32::MAX).saturating_mul(10), u32::MAX);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_mul(self, rhs: Self) -> Self {
match self.checked_mul(rhs) { Some(x) => x, None => Self::MAX, }
}
/// Saturating integer division. Computes `self / rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u32.saturating_div(2), 2);"]
///
/// ```
#[stable(feature = "saturating_div", since = "1.58.0")]
#[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn saturating_div(self, rhs: Self) -> Self {
self.wrapping_div(rhs)
}
/// Saturating integer exponentiation. Computes `self.pow(exp)`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(4u32.saturating_pow(3), 64);"]
#[doc = "assert_eq!(0_u32.saturating_pow(0), 1);"]
#[doc = "assert_eq!(u32::MAX.saturating_pow(2), u32::MAX);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) { Some(x) => x, None => Self::MAX, }
}
/// Wrapping (modular) addition. Computes `self + rhs`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(200u32.wrapping_add(55), 255);"]
#[doc = "assert_eq!(200u32.wrapping_add(u32::MAX), 199);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_add(self, rhs: Self) -> Self {
intrinsics::wrapping_add(self, rhs)
}
/// Wrapping (modular) addition with a signed integer. Computes
/// `self + rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u32.wrapping_add_signed(2), 3);"]
#[doc = "assert_eq!(1u32.wrapping_add_signed(-2), u32::MAX);"]
#[doc = "assert_eq!((u32::MAX - 2).wrapping_add_signed(4), 1);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_add_signed(self, rhs: i32) -> Self {
self.wrapping_add(rhs as Self)
}
/// Wrapping (modular) subtraction. Computes `self - rhs`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u32.wrapping_sub(100), 0);"]
#[doc = "assert_eq!(100u32.wrapping_sub(u32::MAX), 101);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_sub(self, rhs: Self) -> Self {
intrinsics::wrapping_sub(self, rhs)
}
/// Wrapping (modular) subtraction with a signed integer. Computes
/// `self - rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u32.wrapping_sub_signed(2), u32::MAX);"]
#[doc = "assert_eq!(1u32.wrapping_sub_signed(-2), 3);"]
#[doc = "assert_eq!((u32::MAX - 2).wrapping_sub_signed(-4), 1);"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_sub_signed(self, rhs: i32) -> Self {
self.wrapping_sub(rhs as Self)
}
/// Wrapping (modular) multiplication. Computes `self *
/// rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `u8` is used.
///
/// ```
/// assert_eq!(10u8.wrapping_mul(12), 120);
/// assert_eq!(25u8.wrapping_mul(12), 44);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_mul(self, rhs: Self) -> Self {
intrinsics::wrapping_mul(self, rhs)
}
/// Wrapping (modular) division. Computes `self / rhs`.
///
/// Wrapped division on unsigned types is just normal division. There's
/// no way wrapping could ever happen. This function exists so that all
/// operations are accounted for in the wrapping operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u32.wrapping_div(10), 10);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn wrapping_div(self, rhs: Self) -> Self { self / rhs }
/// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
///
/// Wrapped division on unsigned types is just normal division. There's
/// no way wrapping could ever happen. This function exists so that all
/// operations are accounted for in the wrapping operations. Since, for
/// the positive integers, all common definitions of division are equal,
/// this is exactly equal to `self.wrapping_div(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u32.wrapping_div_euclid(10), 10);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn wrapping_div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Wrapping (modular) remainder. Computes `self % rhs`.
///
/// Wrapped remainder calculation on unsigned types is just the regular
/// remainder calculation. There's no way wrapping could ever happen.
/// This function exists so that all operations are accounted for in the
/// wrapping operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u32.wrapping_rem(10), 0);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn wrapping_rem(self, rhs: Self) -> Self { self % rhs }
/// Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
///
/// Wrapped modulo calculation on unsigned types is just the regular
/// remainder calculation. There's no way wrapping could ever happen.
/// This function exists so that all operations are accounted for in the
/// wrapping operations. Since, for the positive integers, all common
/// definitions of division are equal, this is exactly equal to
/// `self.wrapping_rem(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u32.wrapping_rem_euclid(10), 0);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Wrapping (modular) negation. Computes `-self`,
/// wrapping around at the boundary of the type.
///
/// Since unsigned types do not have negative equivalents
/// all applications of this function will wrap (except for `-0`).
/// For values smaller than the corresponding signed type's maximum
/// the result is the same as casting the corresponding signed value.
/// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
/// `MAX` is the corresponding signed type's maximum.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0_u32.wrapping_neg(), 0);"]
#[doc = "assert_eq!(u32::MAX.wrapping_neg(), 1);"]
#[doc = "assert_eq!(13_u32.wrapping_neg(), (!13) + 1);"]
#[doc = "assert_eq!(42_u32.wrapping_neg(), !(42 - 1));"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_neg(self) -> Self { (0 as u32).wrapping_sub(self) }
/// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
/// where `mask` removes any high-order bits of `rhs` that
/// would cause the shift to exceed the bitwidth of the type.
///
/// Beware that, unlike most other `wrapping_*` methods on integers, this
/// does *not* give the same result as doing the shift in infinite precision
/// then truncating as needed. Instead, the behaviour of this method matches what shift instructions
/// do on many processors, and is what the `<<` operator does when overflow
/// checks are disabled, but numerically it's weird. Consider, instead,
/// using [`Self::unbounded_shl`] which has nicer behaviour.
///
/// Note that this is *not* the same as a rotate-left; the
/// RHS of a wrapping shift-left is restricted to the range
/// of the type, rather than the bits shifted out of the LHS
/// being returned to the other end. The primitive integer
/// types all implement a [`rotate_left`](Self::rotate_left) function,
/// which may be what you want instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1_u32.wrapping_shl(7), 128);"]
#[doc = "assert_eq!(0b101_u32.wrapping_shl(0), 0b101);"]
#[doc = "assert_eq!(0b101_u32.wrapping_shl(1), 0b1010);"]
#[doc = "assert_eq!(0b101_u32.wrapping_shl(2), 0b10100);"]
#[doc = "assert_eq!(u32::MAX.wrapping_shl(2), u32::MAX - 3);"]
#[doc = "assert_eq!(42_u32.wrapping_shl(32), 42);"]
#[doc = "assert_eq!(42_u32.wrapping_shl(1).wrapping_shl(31), 0);"]
#[doc = "assert_eq!(1_u32.wrapping_shl(128), 1);"]
#[doc = "assert_eq!(5_u32.wrapping_shl(1025), 10);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_shl(self, rhs: u32) -> Self {
unsafe { self.unchecked_shl(rhs & (Self::BITS - 1)) }
}
/// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
/// where `mask` removes any high-order bits of `rhs` that
/// would cause the shift to exceed the bitwidth of the type.
///
/// Beware that, unlike most other `wrapping_*` methods on integers, this
/// does *not* give the same result as doing the shift in infinite precision
/// then truncating as needed. Instead, the behaviour of this method matches what shift instructions
/// do on many processors, and is what the `>>` operator does when overflow
/// checks are disabled, but numerically it's weird. Consider, instead,
/// using [`Self::unbounded_shr`] which has nicer behaviour.
///
/// Note that this is *not* the same as a rotate-right; the
/// RHS of a wrapping shift-right is restricted to the range
/// of the type, rather than the bits shifted out of the LHS
/// being returned to the other end. The primitive integer
/// types all implement a [`rotate_right`](Self::rotate_right) function,
/// which may be what you want instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128_u32.wrapping_shr(7), 1);"]
#[doc = "assert_eq!(0b1010_u32.wrapping_shr(0), 0b1010);"]
#[doc = "assert_eq!(0b1010_u32.wrapping_shr(1), 0b101);"]
#[doc = "assert_eq!(0b1010_u32.wrapping_shr(2), 0b10);"]
#[doc = "assert_eq!(u32::MAX.wrapping_shr(1), i32::MAX.cast_unsigned());"]
#[doc = "assert_eq!(42_u32.wrapping_shr(32), 42);"]
#[doc = "assert_eq!(42_u32.wrapping_shr(1).wrapping_shr(31), 0);"]
#[doc = "assert_eq!(128_u32.wrapping_shr(128), 128);"]
#[doc = "assert_eq!(10_u32.wrapping_shr(1025), 5);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_shr(self, rhs: u32) -> Self {
unsafe { self.unchecked_shr(rhs & (Self::BITS - 1)) }
}
/// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3u32.wrapping_pow(5), 243);"]
/// assert_eq!(3u8.wrapping_pow(6), 217);
#[doc = "assert_eq!(0_u32.wrapping_pow(0), 1);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_pow(self, exp: u32) -> Self {
let (a, _) = self.overflowing_pow(exp);
a
}
/// Calculates `self` + `rhs`.
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u32.overflowing_add(2), (7, false));"]
#[doc = "assert_eq!(u32::MAX.overflowing_add(1), (0, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::add_with_overflow(self as u32, rhs as u32);
(a as Self, b)
}
/// Calculates `self` + `rhs` + `carry` and returns a tuple containing
/// the sum and the output carry (in that order).
///
/// Performs "ternary addition" of two integer operands and a carry-in
/// bit, and returns an output integer and a carry-out bit. This allows
/// chaining together multiple additions to create a wider addition, and
/// can be useful for bignum addition.
///
#[doc =
"This can be thought of as a 32-bit \"full adder\", in the electronics sense."]
///
/// If the input carry is false, this method is equivalent to
/// [`overflowing_add`](Self::overflowing_add), and the output carry is
/// equal to the overflow flag. Note that although carry and overflow
/// flags are similar for unsigned integers, they are different for
/// signed integers.
///
/// # Examples
///
/// ```
#[doc = "// 3 MAX (a = 3 \u{d7} 2^32 + 2^32 - 1)"]
#[doc = "// + 5 7 (b = 5 \u{d7} 2^32 + 7)"]
/// // ---------
#[doc = "// 9 6 (sum = 9 \u{d7} 2^32 + 6)"]
///
#[doc = "let (a1, a0): (u32, u32) = (3, u32::MAX);"]
#[doc = "let (b1, b0): (u32, u32) = (5, 7);"]
/// let carry0 = false;
///
/// let (sum0, carry1) = a0.carrying_add(b0, carry0);
/// assert_eq!(carry1, true);
/// let (sum1, carry2) = a1.carrying_add(b1, carry1);
/// assert_eq!(carry2, false);
///
/// assert_eq!((sum1, sum0), (9, 6));
/// ```
#[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
#[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue =
"152015")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
let (a, c1) = self.overflowing_add(rhs);
let (b, c2) = a.overflowing_add(carry as u32);
(b, unsafe { intrinsics::disjoint_bitor(c1, c2) })
}
/// Calculates `self` + `rhs` with a signed `rhs`.
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u32.overflowing_add_signed(2), (3, false));"]
#[doc = "assert_eq!(1u32.overflowing_add_signed(-2), (u32::MAX, true));"]
#[doc = "assert_eq!((u32::MAX - 2).overflowing_add_signed(4), (1, true));"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_add_signed(self, rhs: i32) -> (Self, bool) {
let (res, overflowed) = self.overflowing_add(rhs as Self);
(res, overflowed ^ (rhs < 0))
}
/// Calculates `self` - `rhs`.
///
/// Returns a tuple of the subtraction along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u32.overflowing_sub(2), (3, false));"]
#[doc = "assert_eq!(0u32.overflowing_sub(1), (u32::MAX, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::sub_with_overflow(self as u32, rhs as u32);
(a as Self, b)
}
/// Calculates `self` − `rhs` − `borrow` and returns a tuple
/// containing the difference and the output borrow.
///
/// Performs "ternary subtraction" by subtracting both an integer
/// operand and a borrow-in bit from `self`, and returns an output
/// integer and a borrow-out bit. This allows chaining together multiple
/// subtractions to create a wider subtraction, and can be useful for
/// bignum subtraction.
///
/// # Examples
///
/// ```
#[doc = "// 9 6 (a = 9 \u{d7} 2^32 + 6)"]
#[doc = "// - 5 7 (b = 5 \u{d7} 2^32 + 7)"]
/// // ---------
#[doc = "// 3 MAX (diff = 3 \u{d7} 2^32 + 2^32 - 1)"]
///
#[doc = "let (a1, a0): (u32, u32) = (9, 6);"]
#[doc = "let (b1, b0): (u32, u32) = (5, 7);"]
/// let borrow0 = false;
///
/// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);
/// assert_eq!(borrow1, true);
/// let (diff1, borrow2) = a1.borrowing_sub(b1, borrow1);
/// assert_eq!(borrow2, false);
///
#[doc = "assert_eq!((diff1, diff0), (3, u32::MAX));"]
/// ```
#[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
#[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue =
"152015")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
let (a, c1) = self.overflowing_sub(rhs);
let (b, c2) = a.overflowing_sub(borrow as u32);
(b, unsafe { intrinsics::disjoint_bitor(c1, c2) })
}
/// Calculates `self` - `rhs` with a signed `rhs`
///
/// Returns a tuple of the subtraction along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u32.overflowing_sub_signed(2), (u32::MAX, true));"]
#[doc = "assert_eq!(1u32.overflowing_sub_signed(-2), (3, false));"]
#[doc = "assert_eq!((u32::MAX - 2).overflowing_sub_signed(-4), (1, true));"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_sub_signed(self, rhs: i32) -> (Self, bool) {
let (res, overflow) = self.overflowing_sub(rhs as Self);
(res, overflow ^ (rhs < 0))
}
/// Computes the absolute difference between `self` and `other`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u32.abs_diff(80), 20u32);"]
#[doc = "assert_eq!(100u32.abs_diff(110), 10u32);"]
/// ```
#[stable(feature = "int_abs_diff", since = "1.60.0")]
#[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn abs_diff(self, other: Self) -> Self {
if size_of::<Self>() == 1 {
(self as i32).wrapping_sub(other as i32).unsigned_abs() as Self
} else { if self < other { other - self } else { self - other } }
}
/// Calculates the multiplication of `self` and `rhs`.
///
/// Returns a tuple of the multiplication along with a boolean
/// indicating whether an arithmetic overflow would occur. If an
/// overflow would have occurred then the wrapped value is returned.
///
/// If you want the *value* of the overflow, rather than just *whether*
/// an overflow occurred, see [`Self::carrying_mul`].
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `u32` is used.
///
/// ```
/// assert_eq!(5u32.overflowing_mul(2), (10, false));
/// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::mul_with_overflow(self as u32, rhs as u32);
(a as Self, b)
}
/// Calculates the "full multiplication" `self * rhs + carry`
/// without the possibility to overflow.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// Performs "long multiplication" which takes in an extra amount to add, and may return an
/// additional amount of overflow. This allows for chaining together multiple
/// multiplications to create "big integers" which represent larger values.
///
/// If you also need to add a value, then use [`Self::carrying_mul_add`].
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `u32` is used.
///
/// ```
/// assert_eq!(5u32.carrying_mul(2, 0), (10, 0));
/// assert_eq!(5u32.carrying_mul(2, 10), (20, 0));
/// assert_eq!(1_000_000_000u32.carrying_mul(10, 0), (1410065408, 2));
/// assert_eq!(1_000_000_000u32.carrying_mul(10, 10), (1410065418, 2));
#[doc =
"assert_eq!(u32::MAX.carrying_mul(u32::MAX, u32::MAX), (0, u32::MAX));"]
/// ```
///
/// This is the core operation needed for scalar multiplication when
/// implementing it for wider-than-native types.
///
/// ```
/// fn scalar_mul_eq(little_endian_digits: &mut Vec<u16>, multiplicand: u16) {
/// let mut carry = 0;
/// for d in little_endian_digits.iter_mut() {
/// (*d, carry) = d.carrying_mul(multiplicand, carry);
/// }
/// if carry != 0 {
/// little_endian_digits.push(carry);
/// }
/// }
///
/// let mut v = vec![10, 20];
/// scalar_mul_eq(&mut v, 3);
/// assert_eq!(v, [30, 60]);
///
/// assert_eq!(0x87654321_u64 * 0xFEED, 0x86D3D159E38D);
/// let mut v = vec![0x4321, 0x8765];
/// scalar_mul_eq(&mut v, 0xFEED);
/// assert_eq!(v, [0xE38D, 0xD159, 0x86D3]);
/// ```
///
/// If `carry` is zero, this is similar to [`overflowing_mul`](Self::overflowing_mul),
/// except that it gives the value of the overflow instead of just whether one happened:
///
/// ```
/// # #![allow(unused_features)]
/// #![feature(const_unsigned_bigint_helpers)]
/// let r = u8::carrying_mul(7, 13, 0);
/// assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(7, 13));
/// let r = u8::carrying_mul(13, 42, 0);
/// assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(13, 42));
/// ```
///
/// The value of the first field in the returned tuple matches what you'd get
/// by combining the [`wrapping_mul`](Self::wrapping_mul) and
/// [`wrapping_add`](Self::wrapping_add) methods:
///
/// ```
/// # #![allow(unused_features)]
/// #![feature(const_unsigned_bigint_helpers)]
/// assert_eq!(
/// 789_u16.carrying_mul(456, 123).0,
/// 789_u16.wrapping_mul(456).wrapping_add(123),
/// );
/// ```
#[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
#[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue =
"152015")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_mul(self, rhs: Self, carry: Self) -> (Self, Self) {
Self::carrying_mul_add(self, rhs, carry, 0)
}
/// Calculates the "full multiplication" `self * rhs + carry + add`.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// This cannot overflow, as the double-width result has exactly enough
/// space for the largest possible result. This is equivalent to how, in
/// decimal, 9 × 9 + 9 + 9 = 81 + 18 = 99 = 9×10⁰ + 9×10¹ = 10² - 1.
///
/// Performs "long multiplication" which takes in an extra amount to add, and may return an
/// additional amount of overflow. This allows for chaining together multiple
/// multiplications to create "big integers" which represent larger values.
///
/// If you don't need the `add` part, then you can use [`Self::carrying_mul`] instead.
///
/// # Examples
///
/// Please note that this example is shared between integer types,
/// which explains why `u32` is used here.
///
/// ```
/// assert_eq!(5u32.carrying_mul_add(2, 0, 0), (10, 0));
/// assert_eq!(5u32.carrying_mul_add(2, 10, 10), (30, 0));
/// assert_eq!(1_000_000_000u32.carrying_mul_add(10, 0, 0), (1410065408, 2));
/// assert_eq!(1_000_000_000u32.carrying_mul_add(10, 10, 10), (1410065428, 2));
#[doc =
"assert_eq!(u32::MAX.carrying_mul_add(u32::MAX, u32::MAX, u32::MAX), (u32::MAX, u32::MAX));"]
/// ```
///
/// This is the core per-digit operation for "grade school" O(n²) multiplication.
///
/// Please note that this example is shared between integer types,
/// using `u8` for simplicity of the demonstration.
///
/// ```
/// fn quadratic_mul<const N: usize>(a: [u8; N], b: [u8; N]) -> [u8; N] {
/// let mut out = [0; N];
/// for j in 0..N {
/// let mut carry = 0;
/// for i in 0..(N - j) {
/// (out[j + i], carry) = u8::carrying_mul_add(a[i], b[j], out[j + i], carry);
/// }
/// }
/// out
/// }
///
/// // -1 * -1 == 1
/// assert_eq!(quadratic_mul([0xFF; 3], [0xFF; 3]), [1, 0, 0]);
///
/// assert_eq!(u32::wrapping_mul(0x9e3779b9, 0x7f4a7c15), 0xcffc982d);
/// assert_eq!(
/// quadratic_mul(u32::to_le_bytes(0x9e3779b9), u32::to_le_bytes(0x7f4a7c15)),
/// u32::to_le_bytes(0xcffc982d)
/// );
/// ```
#[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
#[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue =
"152015")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_mul_add(self, rhs: Self, carry: Self, add: Self)
-> (Self, Self) {
intrinsics::carrying_mul_add(self, rhs, carry, add)
}
/// Calculates the divisor when `self` is divided by `rhs`.
///
/// Returns a tuple of the divisor along with a boolean indicating
/// whether an arithmetic overflow would occur. Note that for unsigned
/// integers overflow never occurs, so the second value is always
/// `false`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u32.overflowing_div(2), (2, false));"]
/// ```
#[inline(always)]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_overflowing_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[track_caller]
pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
(self / rhs, false)
}
/// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
///
/// Returns a tuple of the divisor along with a boolean indicating
/// whether an arithmetic overflow would occur. Note that for unsigned
/// integers overflow never occurs, so the second value is always
/// `false`.
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self.overflowing_div(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u32.overflowing_div_euclid(2), (2, false));"]
/// ```
#[inline(always)]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[track_caller]
pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
(self / rhs, false)
}
/// Calculates the remainder when `self` is divided by `rhs`.
///
/// Returns a tuple of the remainder after dividing along with a boolean
/// indicating whether an arithmetic overflow would occur. Note that for
/// unsigned integers overflow never occurs, so the second value is
/// always `false`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u32.overflowing_rem(2), (1, false));"]
/// ```
#[inline(always)]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_overflowing_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[track_caller]
pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
(self % rhs, false)
}
/// Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
///
/// Returns a tuple of the modulo after dividing along with a boolean
/// indicating whether an arithmetic overflow would occur. Note that for
/// unsigned integers overflow never occurs, so the second value is
/// always `false`.
/// Since, for the positive integers, all common
/// definitions of division are equal, this operation
/// is exactly equal to `self.overflowing_rem(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u32.overflowing_rem_euclid(2), (1, false));"]
/// ```
#[inline(always)]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[track_caller]
pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
(self % rhs, false)
}
/// Negates self in an overflowing fashion.
///
/// Returns `!self + 1` using wrapping operations to return the value
/// that represents the negation of this unsigned value. Note that for
/// positive unsigned values overflow always occurs, but negating 0 does
/// not overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0u32.overflowing_neg(), (0, false));"]
#[doc = "assert_eq!(2u32.overflowing_neg(), (-2i32 as u32, true));"]
/// ```
#[inline(always)]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn overflowing_neg(self) -> (Self, bool) {
((!self).wrapping_add(1), self != 0)
}
/// Shifts self left by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean
/// indicating whether the shift value was larger than or equal to the
/// number of bits. If the shift value is too large, then value is
/// masked (N-1) where N is the number of bits, and this value is then
/// used to perform the shift.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1u32.overflowing_shl(4), (0x10, false));"]
#[doc = "assert_eq!(0x1u32.overflowing_shl(132), (0x10, true));"]
#[doc = "assert_eq!(0x10u32.overflowing_shl(31), (0, false));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shl(rhs), rhs >= Self::BITS)
}
/// Shifts self right by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean
/// indicating whether the shift value was larger than or equal to the
/// number of bits. If the shift value is too large, then value is
/// masked (N-1) where N is the number of bits, and this value is then
/// used to perform the shift.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10u32.overflowing_shr(4), (0x1, false));"]
#[doc = "assert_eq!(0x10u32.overflowing_shr(132), (0x1, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shr(rhs), rhs >= Self::BITS)
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// Returns a tuple of the exponentiation along with a bool indicating
/// whether an overflow happened.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3u32.overflowing_pow(5), (243, false));"]
#[doc = "assert_eq!(0_u32.overflowing_pow(0), (1, false));"]
/// assert_eq!(3u8.overflowing_pow(6), (217, true));
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
let mut base = self;
let mut acc: Self = 1;
let mut overflow = false;
let mut tmp_overflow;
if intrinsics::is_val_statically_known(base) && base.is_power_of_two() {
let k = base.ilog2();
let Some(shift) = k.checked_mul(exp) else { return (0, true) };
return ((1 as Self).unbounded_shl(shift), shift >= Self::BITS)
}
if exp == 0 { return (1, false); }
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 {
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
}
exp /= 2;
(base, tmp_overflow) = base.overflowing_mul(base);
overflow |= tmp_overflow;
}
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
return (acc, overflow);
}
loop {
if (exp & 1) == 1 {
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
if exp == 1 { return (acc, overflow); }
}
exp /= 2;
(base, tmp_overflow) = base.overflowing_mul(base);
overflow |= tmp_overflow;
}
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u32.pow(5), 32);"]
#[doc = "assert_eq!(0_u32.pow(0), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn pow(self, exp: u32) -> Self {
if intrinsics::overflow_checks() {
self.strict_pow(exp)
} else { self.wrapping_pow(exp) }
}
/// Returns the square root of the number, rounded down.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10u32.isqrt(), 3);"]
/// ```
#[stable(feature = "isqrt", since = "1.84.0")]
#[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn isqrt(self) -> Self {
let result = imp::int_sqrt::u32(self as u32) as Self;
unsafe {
const MAX_RESULT: u32 = imp::int_sqrt::u32(<u32>::MAX) as u32;
crate::hint::assert_unchecked(result <= MAX_RESULT)
}
if self >= 1 { unsafe { crate::hint::assert_unchecked(result >= 1) } }
unsafe {
crate::hint::assert_unchecked(result.unchecked_mul(result) <= self);
crate::hint::assert_unchecked(result <= self);
}
result
}
/// Performs Euclidean division.
///
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self / rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7u32.div_euclid(4), 1); // or any other integer type"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Calculates the least remainder of `self` when divided by
/// `rhs`.
///
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self % rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7u32.rem_euclid(4), 3); // or any other integer type"]
/// ```
#[doc(alias = "modulo", alias = "mod")]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
///
/// This is the same as performing `self / rhs` for all unsigned integers.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "assert_eq!(7_u32.div_floor(4), 1);"]
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn div_floor(self, rhs: Self) -> Self { self / rhs }
/// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7_u32.div_ceil(4), 2);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_ceil(self, rhs: Self) -> Self {
let d = self / rhs;
let r = self % rhs;
if r > 0 { d + 1 } else { d }
}
/// Calculates the smallest value greater than or equal to `self` that
/// is a multiple of `rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// On overflow, this function will panic if overflow checks are enabled (default in debug
/// mode) and wrap if overflow checks are disabled (default in release mode).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(16_u32.next_multiple_of(8), 16);"]
#[doc = "assert_eq!(23_u32.next_multiple_of(8), 24);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_multiple_of(self, rhs: Self) -> Self {
match self % rhs { 0 => self, r => self + (rhs - r), }
}
/// Calculates the smallest value greater than or equal to `self` that
/// is a multiple of `rhs`. Returns `None` if `rhs` is zero or the
/// operation would result in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(16_u32.checked_next_multiple_of(8), Some(16));"]
#[doc = "assert_eq!(23_u32.checked_next_multiple_of(8), Some(24));"]
#[doc = "assert_eq!(1_u32.checked_next_multiple_of(0), None);"]
#[doc = "assert_eq!(u32::MAX.checked_next_multiple_of(2), None);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
match match self.checked_rem(rhs) { Some(x) => x, None => return None, } {
0 => Some(self),
r => self.checked_add(rhs - r),
}
}
/// Returns `true` if `self` is an integer multiple of `rhs`, and false otherwise.
///
/// This function is equivalent to `self % rhs == 0`, except that it will not panic
/// for `rhs == 0`. Instead, `0.is_multiple_of(0) == true`, and for any non-zero `n`,
/// `n.is_multiple_of(0) == false`.
///
/// # Examples
///
/// ```
#[doc = "assert!(6_u32.is_multiple_of(2));"]
#[doc = "assert!(!5_u32.is_multiple_of(2));"]
///
#[doc = "assert!(0_u32.is_multiple_of(0));"]
#[doc = "assert!(!6_u32.is_multiple_of(0));"]
/// ```
#[stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
#[rustc_const_stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
#[must_use]
#[inline]
pub const fn is_multiple_of(self, rhs: Self) -> bool {
match rhs { 0 => self == 0, _ => self % rhs == 0, }
}
/// Returns `true` if and only if `self == 2^k` for some unsigned integer `k`.
///
/// # Examples
///
/// ```
#[doc = "assert!(16u32.is_power_of_two());"]
#[doc = "assert!(!10u32.is_power_of_two());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
#[inline(always)]
pub const fn is_power_of_two(self) -> bool { self.count_ones() == 1 }
#[inline]
const fn one_less_than_next_power_of_two(self) -> Self {
if self <= 1 { return 0; }
let p = self - 1;
let z = unsafe { intrinsics::ctlz_nonzero(p) };
<u32>::MAX >> z
}
/// Returns the smallest power of two greater than or equal to `self`.
///
/// When return value overflows (i.e., `self > (1 << (N-1))` for type
/// `uN`), it panics in debug mode and the return value is wrapped to 0 in
/// release mode (the only situation in which this method can return 0).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u32.next_power_of_two(), 2);"]
#[doc = "assert_eq!(3u32.next_power_of_two(), 4);"]
#[doc = "assert_eq!(0u32.next_power_of_two(), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_power_of_two(self) -> Self {
self.one_less_than_next_power_of_two() + 1
}
/// Returns the smallest power of two greater than or equal to `self`. If
/// the next power of two is greater than the type's maximum value,
/// `None` is returned, otherwise the power of two is wrapped in `Some`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u32.checked_next_power_of_two(), Some(2));"]
#[doc = "assert_eq!(3u32.checked_next_power_of_two(), Some(4));"]
#[doc = "assert_eq!(u32::MAX.checked_next_power_of_two(), None);"]
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn checked_next_power_of_two(self) -> Option<Self> {
self.one_less_than_next_power_of_two().checked_add(1)
}
/// Returns the smallest power of two greater than or equal to `n`. If
/// the next power of two is greater than the type's maximum value,
/// the return value is wrapped to `0`.
///
/// # Examples
///
/// ```
/// #![feature(wrapping_next_power_of_two)]
///
#[doc = "assert_eq!(2u32.wrapping_next_power_of_two(), 2);"]
#[doc = "assert_eq!(3u32.wrapping_next_power_of_two(), 4);"]
#[doc = "assert_eq!(u32::MAX.wrapping_next_power_of_two(), 0);"]
/// ```
#[inline]
#[unstable(feature = "wrapping_next_power_of_two", issue = "32463", reason =
"needs decision on wrapping behavior")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn wrapping_next_power_of_two(self) -> Self {
self.one_less_than_next_power_of_two().wrapping_add(1)
}
/// Returns the memory representation of this integer as a byte array in
/// big-endian (network) byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12345678u32.to_be_bytes();"]
#[doc = "assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
self.to_be().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// little-endian byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12345678u32.to_le_bytes();"]
#[doc = "assert_eq!(bytes, [0x78, 0x56, 0x34, 0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
self.to_le().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code
/// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
/// instead.
///
#[doc = ""]
///
/// [`to_be_bytes`]: Self::to_be_bytes
/// [`to_le_bytes`]: Self::to_le_bytes
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12345678u32.to_ne_bytes();"]
/// assert_eq!(
/// bytes,
/// if cfg!(target_endian = "big") {
#[doc = " [0x12, 0x34, 0x56, 0x78]"]
/// } else {
#[doc = " [0x78, 0x56, 0x34, 0x12]"]
/// }
/// );
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[allow(unnecessary_transmutes)]
#[inline]
pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
unsafe { mem::transmute(self) }
}
/// Creates a native endian integer value from its representation
/// as a byte array in big endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = u32::from_be_bytes([0x12, 0x34, 0x56, 0x78]);"]
#[doc = "assert_eq!(value, 0x12345678);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_be_u32(input: &mut &[u8]) -> u32 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u32>());"]
/// *input = rest;
#[doc = " u32::from_be_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_be(Self::from_ne_bytes(bytes))
}
/// Creates a native endian integer value from its representation
/// as a byte array in little endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = u32::from_le_bytes([0x78, 0x56, 0x34, 0x12]);"]
#[doc = "assert_eq!(value, 0x12345678);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_le_u32(input: &mut &[u8]) -> u32 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u32>());"]
/// *input = rest;
#[doc = " u32::from_le_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_le(Self::from_ne_bytes(bytes))
}
/// Creates a native endian integer value from its memory representation
/// as a byte array in native endianness.
///
/// As the target platform's native endianness is used, portable code
/// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
/// appropriate instead.
///
/// [`from_be_bytes`]: Self::from_be_bytes
/// [`from_le_bytes`]: Self::from_le_bytes
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = u32::from_ne_bytes(if cfg!(target_endian = \"big\") {"]
#[doc = " [0x12, 0x34, 0x56, 0x78]"]
/// } else {
#[doc = " [0x78, 0x56, 0x34, 0x12]"]
/// });
#[doc = "assert_eq!(value, 0x12345678);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_ne_u32(input: &mut &[u8]) -> u32 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u32>());"]
/// *input = rest;
#[doc = " u32::from_ne_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use]
#[inline]
pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
unsafe { mem::transmute(bytes) }
}
/// New code should prefer to use
#[doc = "[`u32::MIN`] instead."]
///
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_promotable]
#[inline(always)]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MIN` associated constant on this type")]
#[rustc_diagnostic_item = "u32_legacy_fn_min_value"]
pub const fn min_value() -> Self { Self::MIN }
/// New code should prefer to use
#[doc = "[`u32::MAX`] instead."]
///
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_promotable]
#[inline(always)]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MAX` associated constant on this type")]
#[rustc_diagnostic_item = "u32_legacy_fn_max_value"]
pub const fn max_value() -> Self { Self::MAX }
/// Truncate an integer to an integer of the same size or smaller, preserving the least
/// significant bits.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u8, 120u32.truncate());"]
/// assert_eq!(120u8, 376u32.truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
/// instead of truncating.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u8, 120u32.saturating_truncate());"]
/// assert_eq!(255u8, 376u32.saturating_truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn saturating_truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_saturating_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
/// is outside the bounds of the smaller type.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(Some(120u8), 120u32.checked_truncate());"]
/// assert_eq!(None, 376u32.checked_truncate::<u8>());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn checked_truncate<Target>(self) -> Option<Target> where
Self: [const] traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_checked_truncate(self)
}
/// Widen to an integer of the same size or larger, preserving its value.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u128, 120u8.widen());"]
/// ```
#[must_use =
"this returns the widened value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn widen<Target>(self) -> Target where Self: [const]
traits::WidenTarget<Target> {
traits::WidenTarget::internal_widen(self)
}
/// Converts `self` to the target integer type, saturating at the numeric
/// bounds instead of overflowing.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(255u8, u32::MAX.saturating_cast());"]
#[doc = "assert_eq!(127i8, u32::MAX.saturating_cast());"]
#[doc = "assert_eq!(42i8, 42u32.saturating_cast());"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn saturating_cast<T: [const] BoundedCastFromInt<Self>>(self) -> T {
T::saturating_cast_from(self)
}
/// Converts `self` to the target integer type, wrapping around at the
/// boundary of the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(255u8, u32::MAX.wrapping_cast());"]
#[doc = "assert_eq!(42i8, 42u32.wrapping_cast());"]
#[doc = "assert_eq!(u32::MAX as i8, u32::MAX.wrapping_cast());"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn wrapping_cast<T: [const] BoundedCastFromInt<Self>>(self) -> T {
T::wrapping_cast_from(self)
}
/// Converts `self` to the target integer type, returning `None` if the value
/// is not representable by the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(Some(42u8), 42u32.checked_cast());"]
#[doc = "assert_eq!(128u32.checked_cast::<i8>(), None);"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn checked_cast<T: [const] CheckedCastFromInt<Self>>(self)
-> Option<T> {
T::checked_cast_from(self)
}
/// Converts `self` to the target integer type, panicking if the value
/// is not representable by the target type.
///
/// # Panics
///
/// This function will panic if the value is not representable by the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(42u8, 42u32.strict_cast());"]
/// ```
///
/// The following will panic:
///
/// ```should_panic
/// #![feature(integer_casts)]
#[doc = "let _ = 128u32.strict_cast::<i8>();"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
#[track_caller]
pub const fn strict_cast<T: [const] CheckedCastFromInt<Self>>(self) -> T {
T::strict_cast_from(self)
}
/// Converts `self` to the target integer type, assuming the value is
/// representable by the target type.
///
/// # Safety
///
/// This results in undefined behavior if the integer value of `self` is bigger than `T::MAX`,
/// or smaller than `T::MIN`, where `T` is the target type.
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const unsafe fn unchecked_cast<T: [const] CheckedCastFromInt<Self>>(self)
-> T {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(in_bounds: bool) {
if !in_bounds {
let msg =
"unsafe precondition(s) violated: u32::unchecked_cast must fit in the target type\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check({
let cast_val = self.checked_cast::<T>();
let ret = cast_val.is_some();
core::mem::forget(cast_val);
ret
});
}
};
unsafe { T::unchecked_cast_from(self) }
}uint_impl! {
1288Self = u32,
1289 ActualT = u32,
1290 SignedT = i32,
1291 BITS = 32,
1292 BITS_MINUS_ONE = 31,
1293 MAX = 4294967295,
1294 rot = 8,
1295 rot_op = "0x10000b3",
1296 rot_result = "0xb301",
1297 fsh_op = "0x2fe78e45",
1298 fshl_result = "0xb32f",
1299 fshr_result = "0xb32fe78e",
1300 clmul_lhs = "0x56789012",
1301 clmul_rhs = "0xf52ecd34",
1302 clmul_result = "0x9b980928",
1303 swap_op = "0x12345678",
1304 swapped = "0x78563412",
1305 reversed = "0x1e6a2c48",
1306 le_bytes = "[0x78, 0x56, 0x34, 0x12]",
1307 be_bytes = "[0x12, 0x34, 0x56, 0x78]",
1308 to_xe_bytes_doc = "",
1309 from_xe_bytes_doc = "",
1310 bound_condition = "",
1311 }1312/// Calculates the midpoint (average) between `self` and `rhs`.
///
/// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
/// sufficiently-large unsigned integral type. This implies that the result is
/// always rounded towards zero and that no overflow will ever occur.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0u32.midpoint(4), 2);"]
#[doc = "assert_eq!(1u32.midpoint(4), 2);"]
/// ```
#[stable(feature = "num_midpoint", since = "1.85.0")]
#[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[doc(alias = "average_floor")]
#[doc(alias = "average")]
#[inline]
pub const fn midpoint(self, rhs: u32) -> u32 {
((self as u64 + rhs as u64) / 2) as u32
}midpoint_impl! { u32, u64, unsigned }1313/// Widening multiplication. Computes `self * rhs`, widening to a larger integer.
///
/// The returned value is always exact and can never overflow.
///
/// Note that this method is semantically equivalent to [`carrying_mul`] with a
/// carry of zero, with the latter instead returning a tuple denoting the low and
/// high parts of the result. Consider using it instead if you need
/// interoperability with other big int helper functions, or if this method isn't
/// available for a given type.
///
/// [`carrying_mul`]: Self::carrying_mul
///
/// # Examples
///
/// ```
/// #![feature(widening_mul)]
///
#[doc = "assert_eq!(u32::MAX.widening_mul(0_u32), 0);"]
#[doc =
"assert_eq!(u32::MAX.widening_mul(u32::MAX), u32::MAX as u64 * u32::MAX as u64);"]
/// ```
#[unstable(feature = "widening_mul", issue = "152016")]
#[rustc_const_unstable(feature = "widening_mul", issue = "152016")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn widening_mul(self, rhs: Self) -> u64 { self as u64 * rhs as u64 }widening_mul_impl! { u32, u64 }1314/// Performs a widening carry-less multiplication.
///
/// # Examples
///
/// ```
/// #![feature(uint_carryless_mul)]
///
#[doc =
"assert_eq!(u32::MAX.widening_carryless_mul(u32::MAX), u64::MAX / 3);"]
/// ```
#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
#[doc(alias = "clmul")]
#[unstable(feature = "uint_carryless_mul", issue = "152080")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn widening_carryless_mul(self, rhs: u32) -> u64 {
(self as u64).carryless_mul(rhs as u64)
}widening_carryless_mul_impl! { u32, u64 }1315/// Calculates the "full carryless multiplication" without the possibility to overflow.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `u8` is used.
///
/// ```
/// #![feature(uint_carryless_mul)]
///
/// assert_eq!(0b1000_0000u8.carrying_carryless_mul(0b1000_0000, 0b0000), (0, 0b0100_0000));
/// assert_eq!(0b1000_0000u8.carrying_carryless_mul(0b1000_0000, 0b1111), (0b1111, 0b0100_0000));
#[doc =
"assert_eq!(u32::MAX.carrying_carryless_mul(u32::MAX, u32::MAX), (!(u32::MAX / 3), u32::MAX / 3));"]
/// ```
#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
#[doc(alias = "clmul")]
#[unstable(feature = "uint_carryless_mul", issue = "152080")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_carryless_mul(self, rhs: Self, carry: Self)
-> (Self, Self) {
let p = (self as u64).carryless_mul(rhs as u64);
let lo = (p as u32);
let hi = (p >> Self::BITS) as u32;
(lo ^ carry, hi)
}carrying_carryless_mul_impl! { u32, u64 }1316}
13171318impl u64 {
1319/// The smallest value that can be represented by this integer type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(u64::MIN, 0);"]
/// ```
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MIN: Self = 0;
/// The largest value that can be represented by this integer type
#[doc = "(2<sup>64</sup> − 1)."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(u64::MAX, 18446744073709551615);"]
/// ```
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MAX: Self = !0;
/// The size of this integer type in bits.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(u64::BITS, 64);"]
/// ```
#[stable(feature = "int_bits_const", since = "1.53.0")]
pub const BITS: u32 = Self::MAX.count_ones();
/// Returns the number of ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 0b01001100u64;"]
/// assert_eq!(n.count_ones(), 3);
///
#[doc = "let max = u64::MAX;"]
#[doc = "assert_eq!(max.count_ones(), 64);"]
///
#[doc = "let zero = 0u64;"]
/// assert_eq!(zero.count_ones(), 0);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[doc(alias = "popcount")]
#[doc(alias = "popcnt")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn count_ones(self) -> u32 { return intrinsics::ctpop(self); }
/// Returns the number of zeros in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let zero = 0u64;"]
#[doc = "assert_eq!(zero.count_zeros(), 64);"]
///
#[doc = "let max = u64::MAX;"]
/// assert_eq!(max.count_zeros(), 0);
/// ```
///
/// This is heavily dependent on the width of the type, and thus
/// might give surprising results depending on type inference:
/// ```
/// # fn foo(_: u8) {}
/// # fn bar(_: u16) {}
/// let lucky = 7;
/// foo(lucky);
/// assert_eq!(lucky.count_zeros(), 5);
/// assert_eq!(lucky.count_ones(), 3);
///
/// let lucky = 7;
/// bar(lucky);
/// assert_eq!(lucky.count_zeros(), 13);
/// assert_eq!(lucky.count_ones(), 3);
/// ```
/// You might want to use [`Self::count_ones`] instead, or emphasize
/// the type you're using in the call rather than method syntax:
/// ```
/// let small = 1;
#[doc = "assert_eq!(u64::count_zeros(small), 63);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn count_zeros(self) -> u32 { (!self).count_ones() }
/// Returns the number of leading zeros in the binary representation of `self`.
///
/// Depending on what you're doing with the value, you might also be interested in the
/// [`ilog2`] function which returns a consistent number, even if the type widens.
///
/// # Examples
///
/// ```
#[doc = "let n = u64::MAX >> 2;"]
/// assert_eq!(n.leading_zeros(), 2);
///
#[doc = "let zero = 0u64;"]
#[doc = "assert_eq!(zero.leading_zeros(), 64);"]
///
#[doc = "let max = u64::MAX;"]
/// assert_eq!(max.leading_zeros(), 0);
/// ```
#[doc = "[`ilog2`]: u64::ilog2"]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn leading_zeros(self) -> u32 {
return intrinsics::ctlz(self as u64);
}
/// Returns the number of trailing zeros in the binary representation
/// of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 0b0101000u64;"]
/// assert_eq!(n.trailing_zeros(), 3);
///
#[doc = "let zero = 0u64;"]
#[doc = "assert_eq!(zero.trailing_zeros(), 64);"]
///
#[doc = "let max = u64::MAX;"]
#[doc = "assert_eq!(max.trailing_zeros(), 0);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn trailing_zeros(self) -> u32 { return intrinsics::cttz(self); }
/// Returns the number of leading ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = !(u64::MAX >> 2);"]
/// assert_eq!(n.leading_ones(), 2);
///
#[doc = "let zero = 0u64;"]
/// assert_eq!(zero.leading_ones(), 0);
///
#[doc = "let max = u64::MAX;"]
#[doc = "assert_eq!(max.leading_ones(), 64);"]
/// ```
#[stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn leading_ones(self) -> u32 { (!self).leading_zeros() }
/// Returns the number of trailing ones in the binary representation
/// of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 0b1010111u64;"]
/// assert_eq!(n.trailing_ones(), 3);
///
#[doc = "let zero = 0u64;"]
/// assert_eq!(zero.trailing_ones(), 0);
///
#[doc = "let max = u64::MAX;"]
#[doc = "assert_eq!(max.trailing_ones(), 64);"]
/// ```
#[stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn trailing_ones(self) -> u32 { (!self).trailing_zeros() }
/// Returns the minimum number of bits required to represent `self`.
///
/// This method returns zero if `self` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0_u64.bit_width(), 0);"]
#[doc = "assert_eq!(0b111_u64.bit_width(), 3);"]
#[doc = "assert_eq!(0b1110_u64.bit_width(), 4);"]
#[doc = "assert_eq!(u64::MAX.bit_width(), 64);"]
/// ```
#[stable(feature = "uint_bit_width", since = "1.97.0")]
#[rustc_const_stable(feature = "uint_bit_width", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn bit_width(self) -> u32 { Self::BITS - self.leading_zeros() }
/// Returns `self` with only the most significant bit set, or `0` if
/// the input is `0`.
///
/// # Examples
///
/// ```
#[doc = "let n: u64 = 0b_01100100;"]
///
/// assert_eq!(n.isolate_highest_one(), 0b_01000000);
#[doc = "assert_eq!(0_u64.isolate_highest_one(), 0);"]
/// ```
#[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn isolate_highest_one(self) -> Self {
self &
(((1 as u64) << (<u64>::BITS - 1)).wrapping_shr(self.leading_zeros()))
}
/// Returns `self` with only the least significant bit set, or `0` if
/// the input is `0`.
///
/// # Examples
///
/// ```
#[doc = "let n: u64 = 0b_01100100;"]
///
/// assert_eq!(n.isolate_lowest_one(), 0b_00000100);
#[doc = "assert_eq!(0_u64.isolate_lowest_one(), 0);"]
/// ```
#[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn isolate_lowest_one(self) -> Self { self & self.wrapping_neg() }
/// Returns the index of the highest bit set to one in `self`, or `None`
/// if `self` is `0`.
///
/// Note that this is equivalent to [`checked_ilog2`](Self::checked_ilog2).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0b0_u64.highest_one(), None);"]
#[doc = "assert_eq!(0b1_u64.highest_one(), Some(0));"]
#[doc = "assert_eq!(0b1_0000_u64.highest_one(), Some(4));"]
#[doc = "assert_eq!(0b1_1111_u64.highest_one(), Some(4));"]
/// ```
#[stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn highest_one(self) -> Option<u32> {
match NonZero::new(self) {
Some(v) => Some(v.highest_one()),
None => None,
}
}
/// Returns the index of the lowest bit set to one in `self`, or `None`
/// if `self` is `0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0b0_u64.lowest_one(), None);"]
#[doc = "assert_eq!(0b1_u64.lowest_one(), Some(0));"]
#[doc = "assert_eq!(0b1_0000_u64.lowest_one(), Some(4));"]
#[doc = "assert_eq!(0b1_1111_u64.lowest_one(), Some(0));"]
/// ```
#[stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn lowest_one(self) -> Option<u32> {
match NonZero::new(self) {
Some(v) => Some(v.lowest_one()),
None => None,
}
}
/// Returns the bit pattern of `self` reinterpreted as a signed integer of the same size.
///
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
/// the same.
///
/// # Examples
///
/// ```
#[doc = "let n = u64::MAX;"]
///
#[doc = "assert_eq!(n.cast_signed(), -1i64);"]
/// ```
#[stable(feature = "integer_sign_cast", since = "1.87.0")]
#[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_signed(self) -> i64 { self as i64 }
/// Saturating conversion of `self` to a signed integer of the same size.
///
/// The signed integer's maximum value is returned if `self` is larger
/// than the maximum positive value representable by the signed integer.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`checked_cast_signed`](Self::checked_cast_signed),
/// or [`strict_cast_signed`](Self::strict_cast_signed).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = u64::MAX;"]
///
#[doc = "assert_eq!(n.saturating_cast_signed(), i64::MAX);"]
#[doc = "assert_eq!(64u64.saturating_cast_signed(), 64i64);"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_cast_signed(self) -> i64 {
if self <= <i64>::MAX.cast_unsigned() {
self.cast_signed()
} else { <i64>::MAX }
}
/// Checked conversion of `self` to a signed integer of the same size,
/// returning `None` if `self` is larger than the signed integer's
/// maximum value.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`saturating_cast_signed`](Self::saturating_cast_signed),
/// or [`strict_cast_signed`](Self::strict_cast_signed).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = u64::MAX;"]
///
#[doc = "assert_eq!(n.checked_cast_signed(), None);"]
#[doc = "assert_eq!(64u64.checked_cast_signed(), Some(64i64));"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn checked_cast_signed(self) -> Option<i64> {
if self <= <i64>::MAX.cast_unsigned() {
Some(self.cast_signed())
} else { None }
}
/// Strict conversion of `self` to a signed integer of the same size,
/// which panics if `self` is larger than the signed integer's maximum
/// value.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`checked_cast_signed`](Self::checked_cast_signed),
/// or [`saturating_cast_signed`](Self::saturating_cast_signed).
///
/// # Examples
///
/// ```should_panic
/// #![feature(integer_cast_extras)]
#[doc = "let _ = u64::MAX.strict_cast_signed();"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_cast_signed(self) -> i64 {
match self.checked_cast_signed() {
Some(n) => n,
None => imp::overflow_panic::cast_integer(),
}
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `<<` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0xaa00000000006e1u64;"]
#[doc = "let m = 0x6e10aa;"]
///
#[doc = "assert_eq!(n.rotate_left(12), m);"]
#[doc = "assert_eq!(n.rotate_left(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
pub const fn rotate_left(self, n: u32) -> Self {
return intrinsics::rotate_left(self, n);
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `>>` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x6e10aau64;"]
#[doc = "let m = 0xaa00000000006e1;"]
///
#[doc = "assert_eq!(n.rotate_right(12), m);"]
#[doc = "assert_eq!(n.rotate_right(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
pub const fn rotate_right(self, n: u32) -> Self {
return intrinsics::rotate_right(self, n);
}
/// Performs a left funnel shift (concatenates `self` with `rhs`, with `self`
/// making up the most significant half, then shifts the combined value left
/// by `n`, and most significant half is extracted to produce the result).
///
/// Please note this isn't the same operation as the `<<` shifting operator or
/// [`rotate_left`](Self::rotate_left), although `a.funnel_shl(a, n)` is *equivalent*
/// to `a.rotate_left(n)`.
///
/// # Panics
///
/// If `n` is greater than or equal to the number of bits in `self`
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(funnel_shifts)]
#[doc = "let a = 0xaa00000000006e1u64;"]
#[doc = "let b = 0x2fe78e45983acd98u64;"]
#[doc = "let m = 0x6e12fe;"]
///
#[doc = "assert_eq!(a.funnel_shl(b, 12), m);"]
/// ```
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn funnel_shl(self, rhs: Self, n: u32) -> Self {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift left with overflow"));
}
};
unsafe { self.unchecked_funnel_shl(rhs, n) }
}
/// Performs a right funnel shift (concatenates `self` and `rhs`, with `self`
/// making up the most significant half, then shifts the combined value right
/// by `n`, and least significant half is extracted to produce the result).
///
/// Please note this isn't the same operation as the `>>` shifting operator or
/// [`rotate_right`](Self::rotate_right), although `a.funnel_shr(a, n)` is *equivalent*
/// to `a.rotate_right(n)`.
///
/// # Panics
///
/// If `n` is greater than or equal to the number of bits in `self`
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(funnel_shifts)]
#[doc = "let a = 0xaa00000000006e1u64;"]
#[doc = "let b = 0x2fe78e45983acd98u64;"]
#[doc = "let m = 0x6e12fe78e45983ac;"]
///
#[doc = "assert_eq!(a.funnel_shr(b, 12), m);"]
/// ```
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn funnel_shr(self, rhs: Self, n: u32) -> Self {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift right with overflow"));
}
};
unsafe { self.unchecked_funnel_shr(rhs, n) }
}
/// Unchecked funnel shift left.
///
/// # Safety
///
/// This results in undefined behavior if `n` is greater than or equal to
#[doc = "`u64::BITS`,"]
/// i.e. when [`funnel_shl`](Self::funnel_shl) would panic.
///
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_funnel_shl(self, low: Self, n: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(n: u32) {
if !(n < <u64>::BITS) {
let msg =
"unsafe precondition(s) violated: u64::unchecked_funnel_shl cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(n); }
};
unsafe { intrinsics::unchecked_funnel_shl(self, low, n) }
}
/// Unchecked funnel shift right.
///
/// # Safety
///
/// This results in undefined behavior if `n` is greater than or equal to
#[doc = "`u64::BITS`,"]
/// i.e. when [`funnel_shr`](Self::funnel_shr) would panic.
///
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_funnel_shr(self, low: Self, n: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(n: u32) {
if !(n < <u64>::BITS) {
let msg =
"unsafe precondition(s) violated: u64::unchecked_funnel_shr cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(n); }
};
unsafe { intrinsics::unchecked_funnel_shr(self, low, n) }
}
/// Performs a carry-less multiplication, returning the lower bits.
///
/// This operation is similar to long multiplication in base 2, except that exclusive or is
/// used instead of addition. The implementation is equivalent to:
///
/// ```no_run
#[doc = "pub fn carryless_mul(lhs: u64, rhs: u64) -> u64{"]
/// let mut retval = 0;
#[doc = " for i in 0..u64::BITS {"]
/// if (rhs >> i) & 1 != 0 {
/// // long multiplication would use +=
/// retval ^= lhs << i;
/// }
/// }
/// retval
/// }
/// ```
///
/// The actual implementation is more efficient, and on some platforms lowers directly to a
/// dedicated instruction.
///
/// # Uses
///
/// Carryless multiplication can be used to turn a bitmask of quote characters into a
/// bit mask of characters surrounded by quotes:
///
/// ```no_run
/// r#"abc xxx "foobar" zzz "a"!"#; // input string
/// 0b0000000010000001000001010; // quote_mask
/// 0b0000000001111110000000100; // quote_mask.carryless_mul(!0) & !quote_mask
/// ```
///
/// Another use is in cryptography, where carryless multiplication allows for efficient
/// implementations of polynomial multiplication in `GF(2)[X]`, the polynomial ring
/// over `GF(2)`.
///
/// # Examples
///
/// ```
/// #![feature(uint_carryless_mul)]
///
#[doc = "let a = 0x7890123456789012u64;"]
#[doc = "let b = 0xdd358416f52ecd34u64;"]
///
#[doc = "assert_eq!(a.carryless_mul(b), 0xa6299579b980928);"]
/// ```
#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
#[doc(alias = "clmul")]
#[unstable(feature = "uint_carryless_mul", issue = "152080")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn carryless_mul(self, rhs: Self) -> Self {
intrinsics::carryless_mul(self, rhs)
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1234567890123456u64;"]
/// let m = n.swap_bytes();
///
#[doc = "assert_eq!(m, 0x5634129078563412);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn swap_bytes(self) -> Self {
intrinsics::bswap(self as u64) as Self
}
/// Returns an integer with the bit locations specified by `mask` packed
/// contiguously into the least significant bits of the result.
/// ```
/// #![feature(uint_gather_scatter_bits)]
#[doc = "let n: u64 = 0b1011_1100;"]
///
/// assert_eq!(n.extract_bits(0b0010_0100), 0b0000_0011);
/// assert_eq!(n.extract_bits(0xF0), 0b0000_1011);
/// ```
#[doc(alias = "pext")]
#[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn extract_bits(self, mask: Self) -> Self {
imp::int_bits::u64::extract_impl(self as u64, mask as u64) as u64
}
/// Returns an integer with the least significant bits of `self`
/// distributed to the bit locations specified by `mask`.
/// ```
/// #![feature(uint_gather_scatter_bits)]
#[doc = "let n: u64 = 0b1010_1101;"]
///
/// assert_eq!(n.deposit_bits(0b0101_0101), 0b0101_0001);
/// assert_eq!(n.deposit_bits(0xF0), 0b1101_0000);
/// ```
#[doc(alias = "pdep")]
#[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn deposit_bits(self, mask: Self) -> Self {
imp::int_bits::u64::deposit_impl(self as u64, mask as u64) as u64
}
/// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
/// second least-significant bit becomes second most-significant bit, etc.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1234567890123456u64;"]
/// let m = n.reverse_bits();
///
#[doc = "assert_eq!(m, 0x6a2c48091e6a2c48);"]
#[doc = "assert_eq!(0, 0u64.reverse_bits());"]
/// ```
#[stable(feature = "reverse_bits", since = "1.37.0")]
#[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn reverse_bits(self) -> Self {
intrinsics::bitreverse(self as u64) as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au64;"]
///
/// if cfg!(target_endian = "big") {
#[doc = " assert_eq!(u64::from_be(n), n)"]
/// } else {
#[doc = " assert_eq!(u64::from_be(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use]
#[inline(always)]
pub const fn from_be(x: Self) -> Self { x.swap_bytes() }
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au64;"]
///
/// if cfg!(target_endian = "little") {
#[doc = " assert_eq!(u64::from_le(n), n)"]
/// } else {
#[doc = " assert_eq!(u64::from_le(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use]
#[inline(always)]
pub const fn from_le(x: Self) -> Self { x }
/// Converts `self` to big endian from the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au64;"]
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn to_be(self) -> Self { self.swap_bytes() }
/// Converts `self` to little endian from the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au64;"]
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn to_le(self) -> Self { self }
/// Checked integer addition. Computes `self + rhs`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((u64::MAX - 2).checked_add(1), Some(u64::MAX - 1));"]
#[doc = "assert_eq!((u64::MAX - 2).checked_add(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(intrinsics::add_with_overflow(self, rhs).1) {
None
} else { Some(unsafe { intrinsics::unchecked_add(self, rhs) }) }
}
/// Strict integer addition. Computes `self + rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((u64::MAX - 2).strict_add(1), u64::MAX - 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (u64::MAX - 2).strict_add(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_add(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Unchecked integer addition. Computes `self + rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_add(y)` is semantically equivalent to calling
/// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_add`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self + rhs > u64::MAX`,"]
/// i.e. when [`checked_add`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_add`]: u64::checked_add"]
#[doc = "[`wrapping_add`]: u64::wrapping_add"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u64, rhs: u64) {
if !!lhs.overflowing_add(rhs).1 {
let msg =
"unsafe precondition(s) violated: u64::unchecked_add cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_add(self, rhs) }
}
/// Checked addition with a signed integer. Computes `self + rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u64.checked_add_signed(2), Some(3));"]
#[doc = "assert_eq!(1u64.checked_add_signed(-2), None);"]
#[doc = "assert_eq!((u64::MAX - 2).checked_add_signed(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add_signed(self, rhs: i64) -> Option<Self> {
let (a, b) = self.overflowing_add_signed(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict addition with a signed integer. Computes `self + rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u64.strict_add_signed(2), 3);"]
/// ```
///
/// The following panic because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1u64.strict_add_signed(-2);"]
/// ```
///
/// ```should_panic
#[doc = "let _ = (u64::MAX - 2).strict_add_signed(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add_signed(self, rhs: i64) -> Self {
let (a, b) = self.overflowing_add_signed(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Checked integer subtraction. Computes `self - rhs`, returning
/// `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u64.checked_sub(1), Some(0));"]
#[doc = "assert_eq!(0u64.checked_sub(1), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
if self < rhs {
None
} else { Some(unsafe { intrinsics::unchecked_sub(self, rhs) }) }
}
/// Strict integer subtraction. Computes `self - rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u64.strict_sub(1), 0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0u64.strict_sub(1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_sub(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
/// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_sub`].
///
/// If you find yourself writing code like this:
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if foo >= bar {
/// // SAFETY: just checked it will not overflow
/// let diff = unsafe { foo.unchecked_sub(bar) };
/// // ... use diff ...
/// }
/// ```
///
/// Consider changing it to
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if let Some(diff) = foo.checked_sub(bar) {
/// // ... use diff ...
/// }
/// ```
///
/// As that does exactly the same thing -- including telling the optimizer
/// that the subtraction cannot overflow -- but avoids needing `unsafe`.
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self - rhs < u64::MIN`,"]
/// i.e. when [`checked_sub`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_sub`]: u64::checked_sub"]
#[doc = "[`wrapping_sub`]: u64::wrapping_sub"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u64, rhs: u64) {
if !!lhs.overflowing_sub(rhs).1 {
let msg =
"unsafe precondition(s) violated: u64::unchecked_sub cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_sub(self, rhs) }
}
/// Checked subtraction with a signed integer. Computes `self - rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u64.checked_sub_signed(2), None);"]
#[doc = "assert_eq!(1u64.checked_sub_signed(-2), Some(3));"]
#[doc = "assert_eq!((u64::MAX - 2).checked_sub_signed(-4), None);"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub_signed(self, rhs: i64) -> Option<Self> {
let (res, overflow) = self.overflowing_sub_signed(rhs);
if !overflow { Some(res) } else { None }
}
/// Strict subtraction with a signed integer. Computes `self - rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3u64.strict_sub_signed(2), 1);"]
/// ```
///
/// The following panic because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1u64.strict_sub_signed(2);"]
/// ```
///
/// ```should_panic
#[doc = "let _ = (u64::MAX).strict_sub_signed(-1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub_signed(self, rhs: i64) -> Self {
let (a, b) = self.overflowing_sub_signed(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
#[doc =
"Checked integer subtraction. Computes `self - rhs` and checks if the result fits into an [`i64`], returning `None` if overflow occurred."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10u64.checked_signed_diff(2), Some(8));"]
#[doc = "assert_eq!(2u64.checked_signed_diff(10), Some(-8));"]
#[doc = "assert_eq!(u64::MAX.checked_signed_diff(i64::MAX as u64), None);"]
#[doc =
"assert_eq!((i64::MAX as u64).checked_signed_diff(u64::MAX), Some(i64::MIN));"]
#[doc = "assert_eq!((i64::MAX as u64 + 1).checked_signed_diff(0), None);"]
#[doc = "assert_eq!(u64::MAX.checked_signed_diff(u64::MAX), Some(0));"]
/// ```
#[stable(feature = "unsigned_signed_diff", since = "1.91.0")]
#[rustc_const_stable(feature = "unsigned_signed_diff", since = "1.91.0")]
#[inline]
pub const fn checked_signed_diff(self, rhs: Self) -> Option<i64> {
let res = self.wrapping_sub(rhs) as i64;
let overflow = (self >= rhs) == (res < 0);
if !overflow { Some(res) } else { None }
}
/// Checked integer multiplication. Computes `self * rhs`, returning
/// `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u64.checked_mul(1), Some(5));"]
#[doc = "assert_eq!(u64::MAX.checked_mul(2), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer multiplication. Computes `self * rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u64.strict_mul(1), 5);"]
/// ```
///
/// The following panics because of overflow:
///
/// ``` should_panic
#[doc = "let _ = u64::MAX.strict_mul(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_mul(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_mul(rhs);
if b { imp::overflow_panic::mul() } else { a }
}
/// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
/// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_mul`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self * rhs > u64::MAX`,"]
/// i.e. when [`checked_mul`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_mul`]: u64::checked_mul"]
#[doc = "[`wrapping_mul`]: u64::wrapping_mul"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u64, rhs: u64) {
if !!lhs.overflowing_mul(rhs).1 {
let msg =
"unsafe precondition(s) violated: u64::unchecked_mul cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_mul(self, rhs) }
}
/// Checked integer division. Computes `self / rhs`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128u64.checked_div(2), Some(64));"]
#[doc = "assert_eq!(1u64.checked_div(0), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(unsafe { intrinsics::unchecked_div(self, rhs) }) }
}
/// Strict integer division. Computes `self / rhs`.
///
/// Strict division on unsigned types is just normal division. There's no
/// way overflow could ever happen. This function exists so that all
/// operations are accounted for in the strict operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u64.strict_div(10), 10);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1u64).strict_div(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_div(self, rhs: Self) -> Self { self / rhs }
/// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128u64.checked_div_euclid(2), Some(64));"]
#[doc = "assert_eq!(1u64.checked_div_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(self.div_euclid(rhs)) }
}
/// Strict Euclidean division. Computes `self.div_euclid(rhs)`.
///
/// Strict division on unsigned types is just normal division. There's no
/// way overflow could ever happen. This function exists so that all
/// operations are accounted for in the strict operations. Since, for the
/// positive integers, all common definitions of division are equal, this
/// is exactly equal to `self.strict_div(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u64.strict_div_euclid(10), 10);"]
/// ```
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1u64).strict_div_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Checked integer division without remainder. Computes `self / rhs`,
/// returning `None` if `rhs == 0` or if `self % rhs != 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64u64.checked_div_exact(2), Some(32));"]
#[doc = "assert_eq!(64u64.checked_div_exact(32), Some(2));"]
#[doc = "assert_eq!(64u64.checked_div_exact(0), None);"]
#[doc = "assert_eq!(65u64.checked_div_exact(2), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_exact(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else {
unsafe {
if intrinsics::unlikely(intrinsics::unchecked_rem(self, rhs) != 0)
{
None
} else { Some(intrinsics::exact_div(self, rhs)) }
}
}
}
/// Integer division without remainder. Computes `self / rhs`, returning `None` if `self % rhs != 0`.
///
/// # Panics
///
/// This function will panic if `rhs == 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64u64.div_exact(2), Some(32));"]
#[doc = "assert_eq!(64u64.div_exact(32), Some(2));"]
#[doc = "assert_eq!(65u64.div_exact(2), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn div_exact(self, rhs: Self) -> Option<Self> {
if self % rhs != 0 { None } else { Some(self / rhs) }
}
/// Unchecked integer division without remainder. Computes `self / rhs`.
///
/// # Safety
///
/// This results in undefined behavior when `rhs == 0` or `self % rhs != 0`,
/// i.e. when [`checked_div_exact`](Self::checked_div_exact) would return `None`.
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_div_exact(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u64, rhs: u64) {
if !(rhs > 0 && lhs % rhs == 0) {
let msg =
"unsafe precondition(s) violated: u64::unchecked_div_exact divide by zero or leave a remainder\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::exact_div(self, rhs) }
}
/// Checked integer remainder. Computes `self % rhs`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u64.checked_rem(2), Some(1));"]
#[doc = "assert_eq!(5u64.checked_rem(0), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(unsafe { intrinsics::unchecked_rem(self, rhs) }) }
}
/// Strict integer remainder. Computes `self % rhs`.
///
/// Strict remainder calculation on unsigned types is just the regular
/// remainder calculation. There's no way overflow could ever happen.
/// This function exists so that all operations are accounted for in the
/// strict operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u64.strict_rem(10), 0);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5u64.strict_rem(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_rem(self, rhs: Self) -> Self { self % rhs }
/// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u64.checked_rem_euclid(2), Some(1));"]
#[doc = "assert_eq!(5u64.checked_rem_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(self.rem_euclid(rhs)) }
}
/// Strict Euclidean modulo. Computes `self.rem_euclid(rhs)`.
///
/// Strict modulo calculation on unsigned types is just the regular
/// remainder calculation. There's no way overflow could ever happen.
/// This function exists so that all operations are accounted for in the
/// strict operations. Since, for the positive integers, all common
/// definitions of division are equal, this is exactly equal to
/// `self.strict_rem(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u64.strict_rem_euclid(10), 0);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5u64.strict_rem_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Same value as `self | other`, but UB if any bit position is set in both inputs.
///
/// This is a situational micro-optimization for places where you'd rather
/// use addition on some platforms and bitwise or on other platforms, based
/// on exactly which instructions combine better with whatever else you're
/// doing. Note that there's no reason to bother using this for places
/// where it's clear from the operations involved that they can't overlap.
/// For example, if you're combining `u16`s into a `u32` with
/// `((a as u32) << 16) | (b as u32)`, that's fine, as the backend will
/// know those sides of the `|` are disjoint without needing help.
///
/// # Examples
///
/// ```
/// #![feature(disjoint_bitor)]
///
/// // SAFETY: `1` and `4` have no bits in common.
/// unsafe {
#[doc = " assert_eq!(1_u64.unchecked_disjoint_bitor(4), 5);"]
/// }
/// ```
///
/// # Safety
///
/// Requires that `(self & other) == 0`, otherwise it's immediate UB.
///
/// Equivalently, requires that `(self | other) == (self + other)`.
#[unstable(feature = "disjoint_bitor", issue = "135758")]
#[rustc_const_unstable(feature = "disjoint_bitor", issue = "135758")]
#[inline]
pub const unsafe fn unchecked_disjoint_bitor(self, other: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u64, rhs: u64) {
if !((lhs & rhs) == 0) {
let msg =
"unsafe precondition(s) violated: u64::unchecked_disjoint_bitor cannot have overlapping bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, other);
}
};
unsafe { intrinsics::disjoint_bitor(self, other) }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// This method might not be optimized owing to implementation details;
/// [`ilog2`](Self::ilog2) can produce results more efficiently for base 2,
/// and [`ilog10`](Self::ilog10) can produce results more efficiently for base 10.
///
/// # Panics
///
/// This function will panic if `self` is zero, or if `base` is less than 2.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u64.ilog(5), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog(self, base: Self) -> u32 {
if !(base >= 2) {
{
crate::panicking::panic_fmt(format_args!("base of integer logarithm must be at least 2"));
}
};
if let Some(log) = self.checked_ilog(base) {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the base 2 logarithm of the number, rounded down.
///
/// # Panics
///
/// This function will panic if `self` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u64.ilog2(), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog2(self) -> u32 {
if let Some(log) = self.checked_ilog2() {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// # Panics
///
/// This function will panic if `self` is zero.
///
/// # Example
///
/// ```
#[doc = "assert_eq!(10u64.ilog10(), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog10(self) -> u32 {
if let Some(log) = self.checked_ilog10() {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// Returns `None` if the number is zero, or if the base is not at least 2.
///
/// This method might not be optimized owing to implementation details;
/// `checked_ilog2` can produce results more efficiently for base 2, and
/// `checked_ilog10` can produce results more efficiently for base 10.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u64.checked_ilog(5), Some(1));"]
#[doc = "assert_eq!(4u64.checked_ilog(5), Some(0));"]
#[doc = "assert_eq!(5u64.checked_ilog(0), None);"]
#[doc = "assert_eq!(5u64.checked_ilog(1), None);"]
#[doc = "assert_eq!(0u64.checked_ilog(1), None);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog(self, base: Self) -> Option<u32> {
if core::intrinsics::is_val_statically_known(base) {
if base.is_power_of_two() && base > 1 {
let k = base.ilog2();
return Some(match self.checked_ilog2() {
Some(x) => x,
None => return None,
} / k);
}
if base == 10 { return self.checked_ilog10(); }
}
if self <= 0 || base <= 1 {
None
} else if self < base {
Some(0)
} else {
let mut n = 1;
let mut r = base;
if Self::BITS == 128 {
n = self.ilog2() / (base.ilog2() + 1);
r = base.pow(n);
}
while r <= self / base { n += 1; r *= base; }
Some(n)
}
}
/// Returns the base 2 logarithm of the number, rounded down.
///
/// Returns `None` if the number is zero.
///
/// Note that this is equivalent to [`highest_one`](Self::highest_one).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u64.checked_ilog2(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog2(self) -> Option<u32> {
match NonZero::new(self) { Some(x) => Some(x.ilog2()), None => None, }
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// Returns `None` if the number is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10u64.checked_ilog10(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog10(self) -> Option<u32> {
match NonZero::new(self) { Some(x) => Some(x.ilog10()), None => None, }
}
/// Checked negation. Computes `-self`, returning `None` unless `self ==
/// 0`.
///
/// Note that negating any positive integer will overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0u64.checked_neg(), Some(0));"]
#[doc = "assert_eq!(1u64.checked_neg(), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_neg(self) -> Option<Self> {
let (a, b) = self.overflowing_neg();
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict negation. Computes `-self`, panicking unless `self ==
/// 0`.
///
/// Note that negating any positive integer will overflow.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0u64.strict_neg(), 0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1u64.strict_neg();"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_neg(self) -> Self {
let (a, b) = self.overflowing_neg();
if b { imp::overflow_panic::neg() } else { a }
}
/// Checked shift left. Computes `self << rhs`, returning `None`
/// if `rhs` is larger than or equal to the number of bits in `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1u64.checked_shl(4), Some(0x10));"]
#[doc = "assert_eq!(0x10u64.checked_shl(129), None);"]
#[doc = "assert_eq!(0x10u64.checked_shl(63), Some(0));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
if rhs < Self::BITS {
Some(unsafe { self.unchecked_shl(rhs) })
} else { None }
}
/// Strict shift left. Computes `self << rhs`, panicking if `rhs` is larger
/// than or equal to the number of bits in `self`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1u64.strict_shl(4), 0x10);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0x10u64.strict_shl(129);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_shl(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_shl(rhs);
if b { imp::overflow_panic::shl() } else { a }
}
/// Unchecked shift left. Computes `self << rhs`, assuming that
/// `rhs` is less than the number of bits in `self`.
///
/// # Safety
///
/// This results in undefined behavior if `rhs` is larger than
/// or equal to the number of bits in `self`,
/// i.e. when [`checked_shl`] would return `None`.
///
#[doc = "[`checked_shl`]: u64::checked_shl"]
#[stable(feature = "unchecked_shifts", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_shl(self, rhs: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(rhs: u32) {
if !(rhs < <u64>::BITS) {
let msg =
"unsafe precondition(s) violated: u64::unchecked_shl cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(rhs); }
};
unsafe { intrinsics::unchecked_shl(self, rhs) }
}
/// Unbounded shift left. Computes `self << rhs`, without bounding the value of `rhs`.
///
/// If `rhs` is larger or equal to the number of bits in `self`,
/// the entire value is shifted out, and `0` is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1_u64.unbounded_shl(4), 0x10);"]
#[doc = "assert_eq!(0x1_u64.unbounded_shl(129), 0);"]
#[doc = "assert_eq!(0b101_u64.unbounded_shl(0), 0b101);"]
#[doc = "assert_eq!(0b101_u64.unbounded_shl(1), 0b1010);"]
#[doc = "assert_eq!(0b101_u64.unbounded_shl(2), 0b10100);"]
#[doc = "assert_eq!(42_u64.unbounded_shl(64), 0);"]
#[doc = "assert_eq!(42_u64.unbounded_shl(1).unbounded_shl(63), 0);"]
///
#[doc = "let start : u64 = 13;"]
/// let mut running = start;
/// for i in 0..160 {
/// // The unbounded shift left by i is the same as `<< 1` i times
/// assert_eq!(running, start.unbounded_shl(i));
/// // Which is not always the case for a wrapping shift
#[doc = " assert_eq!(running == start.wrapping_shl(i), i < 64);"]
///
/// running <<= 1;
/// }
/// ```
#[stable(feature = "unbounded_shifts", since = "1.87.0")]
#[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unbounded_shl(self, rhs: u32) -> u64 {
if rhs < Self::BITS { unsafe { self.unchecked_shl(rhs) } } else { 0 }
}
/// Exact shift left. Computes `self << rhs` as long as it can be reversed losslessly.
///
/// Returns `None` if any non-zero bits would be shifted out or if `rhs` >=
#[doc = "`u64::BITS`."]
/// Otherwise, returns `Some(self << rhs)`.
///
/// # Examples
///
/// ```
/// #![feature(exact_bitshifts)]
///
#[doc = "assert_eq!(0x1u64.shl_exact(4), Some(0x10));"]
#[doc = "assert_eq!(0x1u64.shl_exact(129), None);"]
/// ```
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn shl_exact(self, rhs: u32) -> Option<u64> {
if rhs <= self.leading_zeros() && rhs < <u64>::BITS {
Some(unsafe { self.unchecked_shl(rhs) })
} else { None }
}
/// Unchecked exact shift left. Computes `self << rhs`, assuming the operation can be
/// losslessly reversed `rhs` cannot be larger than
#[doc = "`u64::BITS`."]
///
/// # Safety
///
/// This results in undefined behavior when `rhs > self.leading_zeros() || rhs >=
#[doc = "u64::BITS`"]
/// i.e. when
#[doc = "[`u64::shl_exact`]"]
/// would return `None`.
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_shl_exact(self, rhs: u32) -> u64 {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(zeros: u32, bits: u32, rhs: u32) {
if !(rhs <= zeros && rhs < bits) {
let msg =
"unsafe precondition(s) violated: u64::unchecked_shl_exact cannot shift out non-zero bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_library_ub() {
precondition_check(self.leading_zeros(), <u64>::BITS, rhs);
}
};
unsafe { self.unchecked_shl(rhs) }
}
/// Checked shift right. Computes `self >> rhs`, returning `None`
/// if `rhs` is larger than or equal to the number of bits in `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10u64.checked_shr(4), Some(0x1));"]
#[doc = "assert_eq!(0x10u64.checked_shr(129), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
if rhs < Self::BITS {
Some(unsafe { self.unchecked_shr(rhs) })
} else { None }
}
/// Strict shift right. Computes `self >> rhs`, panicking if `rhs` is
/// larger than or equal to the number of bits in `self`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10u64.strict_shr(4), 0x1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0x10u64.strict_shr(129);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_shr(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_shr(rhs);
if b { imp::overflow_panic::shr() } else { a }
}
/// Unchecked shift right. Computes `self >> rhs`, assuming that
/// `rhs` is less than the number of bits in `self`.
///
/// # Safety
///
/// This results in undefined behavior if `rhs` is larger than
/// or equal to the number of bits in `self`,
/// i.e. when [`checked_shr`] would return `None`.
///
#[doc = "[`checked_shr`]: u64::checked_shr"]
#[stable(feature = "unchecked_shifts", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_shr(self, rhs: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(rhs: u32) {
if !(rhs < <u64>::BITS) {
let msg =
"unsafe precondition(s) violated: u64::unchecked_shr cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(rhs); }
};
unsafe { intrinsics::unchecked_shr(self, rhs) }
}
/// Unbounded shift right. Computes `self >> rhs`, without bounding the value of `rhs`.
///
/// If `rhs` is larger or equal to the number of bits in `self`,
/// the entire value is shifted out, and `0` is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10_u64.unbounded_shr(4), 0x1);"]
#[doc = "assert_eq!(0x10_u64.unbounded_shr(129), 0);"]
#[doc = "assert_eq!(0b1010_u64.unbounded_shr(0), 0b1010);"]
#[doc = "assert_eq!(0b1010_u64.unbounded_shr(1), 0b101);"]
#[doc = "assert_eq!(0b1010_u64.unbounded_shr(2), 0b10);"]
#[doc = "assert_eq!(42_u64.unbounded_shr(64), 0);"]
#[doc = "assert_eq!(42_u64.unbounded_shr(1).unbounded_shr(63), 0);"]
///
#[doc = "let start = u64::rotate_right(13, 4);"]
/// let mut running = start;
/// for i in 0..160 {
/// // The unbounded shift right by i is the same as `>> 1` i times
/// assert_eq!(running, start.unbounded_shr(i));
/// // Which is not always the case for a wrapping shift
#[doc = " assert_eq!(running == start.wrapping_shr(i), i < 64);"]
///
/// running >>= 1;
/// }
/// ```
#[stable(feature = "unbounded_shifts", since = "1.87.0")]
#[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unbounded_shr(self, rhs: u32) -> u64 {
if rhs < Self::BITS { unsafe { self.unchecked_shr(rhs) } } else { 0 }
}
/// Exact shift right. Computes `self >> rhs` as long as it can be reversed losslessly.
///
/// Returns `None` if any non-zero bits would be shifted out or if `rhs` >=
#[doc = "`u64::BITS`."]
/// Otherwise, returns `Some(self >> rhs)`.
///
/// # Examples
///
/// ```
/// #![feature(exact_bitshifts)]
///
#[doc = "assert_eq!(0x10u64.shr_exact(4), Some(0x1));"]
#[doc = "assert_eq!(0x10u64.shr_exact(5), None);"]
/// ```
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn shr_exact(self, rhs: u32) -> Option<u64> {
if rhs <= self.trailing_zeros() && rhs < <u64>::BITS {
Some(unsafe { self.unchecked_shr(rhs) })
} else { None }
}
/// Unchecked exact shift right. Computes `self >> rhs`, assuming the operation can be
/// losslessly reversed and `rhs` cannot be larger than
#[doc = "`u64::BITS`."]
///
/// # Safety
///
/// This results in undefined behavior when `rhs > self.trailing_zeros() || rhs >=
#[doc = "u64::BITS`"]
/// i.e. when
#[doc = "[`u64::shr_exact`]"]
/// would return `None`.
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_shr_exact(self, rhs: u32) -> u64 {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(zeros: u32, bits: u32, rhs: u32) {
if !(rhs <= zeros && rhs < bits) {
let msg =
"unsafe precondition(s) violated: u64::unchecked_shr_exact cannot shift out non-zero bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_library_ub() {
precondition_check(self.trailing_zeros(), <u64>::BITS, rhs);
}
};
unsafe { self.unchecked_shr(rhs) }
}
/// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u64.checked_pow(5), Some(32));"]
#[doc = "assert_eq!(0_u64.checked_pow(0), Some(1));"]
#[doc = "assert_eq!(u64::MAX.checked_pow(2), None);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
let mut base = self;
let mut acc: Self = 1;
if intrinsics::is_val_statically_known(base) && base.is_power_of_two() {
let k = base.ilog2();
let shift =
match k.checked_mul(exp) { Some(x) => x, None => return None, };
return (1 as Self).checked_shl(shift);
}
if exp == 0 { return Some(1); }
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 {
acc =
match acc.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
exp /= 2;
base =
match base.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
return acc.checked_mul(base);
}
loop {
if (exp & 1) == 1 {
acc =
match acc.checked_mul(base) {
Some(x) => x,
None => return None,
};
if exp == 1 { return Some(acc); }
}
exp /= 2;
base =
match base.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
}
/// Strict exponentiation. Computes `self.pow(exp)`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u64.strict_pow(5), 32);"]
#[doc = "assert_eq!(0_u64.strict_pow(0), 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = u64::MAX.strict_pow(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) {
None => imp::overflow_panic::pow(),
Some(a) => a,
}
}
/// Saturating integer addition. Computes `self + rhs`, saturating at
/// the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u64.saturating_add(1), 101);"]
#[doc = "assert_eq!(u64::MAX.saturating_add(127), u64::MAX);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[inline(always)]
pub const fn saturating_add(self, rhs: Self) -> Self {
intrinsics::saturating_add(self, rhs)
}
/// Saturating addition with a signed integer. Computes `self + rhs`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u64.saturating_add_signed(2), 3);"]
#[doc = "assert_eq!(1u64.saturating_add_signed(-2), 0);"]
#[doc = "assert_eq!((u64::MAX - 2).saturating_add_signed(4), u64::MAX);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_add_signed(self, rhs: i64) -> Self {
let (res, overflow) = self.overflowing_add(rhs as Self);
if overflow == (rhs < 0) { res } else if overflow { Self::MAX } else { 0 }
}
/// Saturating integer subtraction. Computes `self - rhs`, saturating
/// at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u64.saturating_sub(27), 73);"]
#[doc = "assert_eq!(13u64.saturating_sub(127), 0);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[inline(always)]
pub const fn saturating_sub(self, rhs: Self) -> Self {
intrinsics::saturating_sub(self, rhs)
}
/// Saturating integer subtraction. Computes `self` - `rhs`, saturating at
/// the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u64.saturating_sub_signed(2), 0);"]
#[doc = "assert_eq!(1u64.saturating_sub_signed(-2), 3);"]
#[doc = "assert_eq!((u64::MAX - 2).saturating_sub_signed(-4), u64::MAX);"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_sub_signed(self, rhs: i64) -> Self {
let (res, overflow) = self.overflowing_sub_signed(rhs);
if !overflow { res } else if rhs < 0 { Self::MAX } else { 0 }
}
/// Saturating integer multiplication. Computes `self * rhs`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u64.saturating_mul(10), 20);"]
#[doc = "assert_eq!((u64::MAX).saturating_mul(10), u64::MAX);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_mul(self, rhs: Self) -> Self {
match self.checked_mul(rhs) { Some(x) => x, None => Self::MAX, }
}
/// Saturating integer division. Computes `self / rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u64.saturating_div(2), 2);"]
///
/// ```
#[stable(feature = "saturating_div", since = "1.58.0")]
#[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn saturating_div(self, rhs: Self) -> Self {
self.wrapping_div(rhs)
}
/// Saturating integer exponentiation. Computes `self.pow(exp)`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(4u64.saturating_pow(3), 64);"]
#[doc = "assert_eq!(0_u64.saturating_pow(0), 1);"]
#[doc = "assert_eq!(u64::MAX.saturating_pow(2), u64::MAX);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) { Some(x) => x, None => Self::MAX, }
}
/// Wrapping (modular) addition. Computes `self + rhs`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(200u64.wrapping_add(55), 255);"]
#[doc = "assert_eq!(200u64.wrapping_add(u64::MAX), 199);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_add(self, rhs: Self) -> Self {
intrinsics::wrapping_add(self, rhs)
}
/// Wrapping (modular) addition with a signed integer. Computes
/// `self + rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u64.wrapping_add_signed(2), 3);"]
#[doc = "assert_eq!(1u64.wrapping_add_signed(-2), u64::MAX);"]
#[doc = "assert_eq!((u64::MAX - 2).wrapping_add_signed(4), 1);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_add_signed(self, rhs: i64) -> Self {
self.wrapping_add(rhs as Self)
}
/// Wrapping (modular) subtraction. Computes `self - rhs`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u64.wrapping_sub(100), 0);"]
#[doc = "assert_eq!(100u64.wrapping_sub(u64::MAX), 101);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_sub(self, rhs: Self) -> Self {
intrinsics::wrapping_sub(self, rhs)
}
/// Wrapping (modular) subtraction with a signed integer. Computes
/// `self - rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u64.wrapping_sub_signed(2), u64::MAX);"]
#[doc = "assert_eq!(1u64.wrapping_sub_signed(-2), 3);"]
#[doc = "assert_eq!((u64::MAX - 2).wrapping_sub_signed(-4), 1);"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_sub_signed(self, rhs: i64) -> Self {
self.wrapping_sub(rhs as Self)
}
/// Wrapping (modular) multiplication. Computes `self *
/// rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `u8` is used.
///
/// ```
/// assert_eq!(10u8.wrapping_mul(12), 120);
/// assert_eq!(25u8.wrapping_mul(12), 44);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_mul(self, rhs: Self) -> Self {
intrinsics::wrapping_mul(self, rhs)
}
/// Wrapping (modular) division. Computes `self / rhs`.
///
/// Wrapped division on unsigned types is just normal division. There's
/// no way wrapping could ever happen. This function exists so that all
/// operations are accounted for in the wrapping operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u64.wrapping_div(10), 10);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn wrapping_div(self, rhs: Self) -> Self { self / rhs }
/// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
///
/// Wrapped division on unsigned types is just normal division. There's
/// no way wrapping could ever happen. This function exists so that all
/// operations are accounted for in the wrapping operations. Since, for
/// the positive integers, all common definitions of division are equal,
/// this is exactly equal to `self.wrapping_div(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u64.wrapping_div_euclid(10), 10);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn wrapping_div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Wrapping (modular) remainder. Computes `self % rhs`.
///
/// Wrapped remainder calculation on unsigned types is just the regular
/// remainder calculation. There's no way wrapping could ever happen.
/// This function exists so that all operations are accounted for in the
/// wrapping operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u64.wrapping_rem(10), 0);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn wrapping_rem(self, rhs: Self) -> Self { self % rhs }
/// Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
///
/// Wrapped modulo calculation on unsigned types is just the regular
/// remainder calculation. There's no way wrapping could ever happen.
/// This function exists so that all operations are accounted for in the
/// wrapping operations. Since, for the positive integers, all common
/// definitions of division are equal, this is exactly equal to
/// `self.wrapping_rem(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u64.wrapping_rem_euclid(10), 0);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Wrapping (modular) negation. Computes `-self`,
/// wrapping around at the boundary of the type.
///
/// Since unsigned types do not have negative equivalents
/// all applications of this function will wrap (except for `-0`).
/// For values smaller than the corresponding signed type's maximum
/// the result is the same as casting the corresponding signed value.
/// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
/// `MAX` is the corresponding signed type's maximum.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0_u64.wrapping_neg(), 0);"]
#[doc = "assert_eq!(u64::MAX.wrapping_neg(), 1);"]
#[doc = "assert_eq!(13_u64.wrapping_neg(), (!13) + 1);"]
#[doc = "assert_eq!(42_u64.wrapping_neg(), !(42 - 1));"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_neg(self) -> Self { (0 as u64).wrapping_sub(self) }
/// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
/// where `mask` removes any high-order bits of `rhs` that
/// would cause the shift to exceed the bitwidth of the type.
///
/// Beware that, unlike most other `wrapping_*` methods on integers, this
/// does *not* give the same result as doing the shift in infinite precision
/// then truncating as needed. Instead, the behaviour of this method matches what shift instructions
/// do on many processors, and is what the `<<` operator does when overflow
/// checks are disabled, but numerically it's weird. Consider, instead,
/// using [`Self::unbounded_shl`] which has nicer behaviour.
///
/// Note that this is *not* the same as a rotate-left; the
/// RHS of a wrapping shift-left is restricted to the range
/// of the type, rather than the bits shifted out of the LHS
/// being returned to the other end. The primitive integer
/// types all implement a [`rotate_left`](Self::rotate_left) function,
/// which may be what you want instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1_u64.wrapping_shl(7), 128);"]
#[doc = "assert_eq!(0b101_u64.wrapping_shl(0), 0b101);"]
#[doc = "assert_eq!(0b101_u64.wrapping_shl(1), 0b1010);"]
#[doc = "assert_eq!(0b101_u64.wrapping_shl(2), 0b10100);"]
#[doc = "assert_eq!(u64::MAX.wrapping_shl(2), u64::MAX - 3);"]
#[doc = "assert_eq!(42_u64.wrapping_shl(64), 42);"]
#[doc = "assert_eq!(42_u64.wrapping_shl(1).wrapping_shl(63), 0);"]
#[doc = "assert_eq!(1_u64.wrapping_shl(128), 1);"]
#[doc = "assert_eq!(5_u64.wrapping_shl(1025), 10);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_shl(self, rhs: u32) -> Self {
unsafe { self.unchecked_shl(rhs & (Self::BITS - 1)) }
}
/// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
/// where `mask` removes any high-order bits of `rhs` that
/// would cause the shift to exceed the bitwidth of the type.
///
/// Beware that, unlike most other `wrapping_*` methods on integers, this
/// does *not* give the same result as doing the shift in infinite precision
/// then truncating as needed. Instead, the behaviour of this method matches what shift instructions
/// do on many processors, and is what the `>>` operator does when overflow
/// checks are disabled, but numerically it's weird. Consider, instead,
/// using [`Self::unbounded_shr`] which has nicer behaviour.
///
/// Note that this is *not* the same as a rotate-right; the
/// RHS of a wrapping shift-right is restricted to the range
/// of the type, rather than the bits shifted out of the LHS
/// being returned to the other end. The primitive integer
/// types all implement a [`rotate_right`](Self::rotate_right) function,
/// which may be what you want instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128_u64.wrapping_shr(7), 1);"]
#[doc = "assert_eq!(0b1010_u64.wrapping_shr(0), 0b1010);"]
#[doc = "assert_eq!(0b1010_u64.wrapping_shr(1), 0b101);"]
#[doc = "assert_eq!(0b1010_u64.wrapping_shr(2), 0b10);"]
#[doc = "assert_eq!(u64::MAX.wrapping_shr(1), i64::MAX.cast_unsigned());"]
#[doc = "assert_eq!(42_u64.wrapping_shr(64), 42);"]
#[doc = "assert_eq!(42_u64.wrapping_shr(1).wrapping_shr(63), 0);"]
#[doc = "assert_eq!(128_u64.wrapping_shr(128), 128);"]
#[doc = "assert_eq!(10_u64.wrapping_shr(1025), 5);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_shr(self, rhs: u32) -> Self {
unsafe { self.unchecked_shr(rhs & (Self::BITS - 1)) }
}
/// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3u64.wrapping_pow(5), 243);"]
/// assert_eq!(3u8.wrapping_pow(6), 217);
#[doc = "assert_eq!(0_u64.wrapping_pow(0), 1);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_pow(self, exp: u32) -> Self {
let (a, _) = self.overflowing_pow(exp);
a
}
/// Calculates `self` + `rhs`.
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u64.overflowing_add(2), (7, false));"]
#[doc = "assert_eq!(u64::MAX.overflowing_add(1), (0, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::add_with_overflow(self as u64, rhs as u64);
(a as Self, b)
}
/// Calculates `self` + `rhs` + `carry` and returns a tuple containing
/// the sum and the output carry (in that order).
///
/// Performs "ternary addition" of two integer operands and a carry-in
/// bit, and returns an output integer and a carry-out bit. This allows
/// chaining together multiple additions to create a wider addition, and
/// can be useful for bignum addition.
///
#[doc =
"This can be thought of as a 64-bit \"full adder\", in the electronics sense."]
///
/// If the input carry is false, this method is equivalent to
/// [`overflowing_add`](Self::overflowing_add), and the output carry is
/// equal to the overflow flag. Note that although carry and overflow
/// flags are similar for unsigned integers, they are different for
/// signed integers.
///
/// # Examples
///
/// ```
#[doc = "// 3 MAX (a = 3 \u{d7} 2^64 + 2^64 - 1)"]
#[doc = "// + 5 7 (b = 5 \u{d7} 2^64 + 7)"]
/// // ---------
#[doc = "// 9 6 (sum = 9 \u{d7} 2^64 + 6)"]
///
#[doc = "let (a1, a0): (u64, u64) = (3, u64::MAX);"]
#[doc = "let (b1, b0): (u64, u64) = (5, 7);"]
/// let carry0 = false;
///
/// let (sum0, carry1) = a0.carrying_add(b0, carry0);
/// assert_eq!(carry1, true);
/// let (sum1, carry2) = a1.carrying_add(b1, carry1);
/// assert_eq!(carry2, false);
///
/// assert_eq!((sum1, sum0), (9, 6));
/// ```
#[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
#[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue =
"152015")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
let (a, c1) = self.overflowing_add(rhs);
let (b, c2) = a.overflowing_add(carry as u64);
(b, unsafe { intrinsics::disjoint_bitor(c1, c2) })
}
/// Calculates `self` + `rhs` with a signed `rhs`.
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u64.overflowing_add_signed(2), (3, false));"]
#[doc = "assert_eq!(1u64.overflowing_add_signed(-2), (u64::MAX, true));"]
#[doc = "assert_eq!((u64::MAX - 2).overflowing_add_signed(4), (1, true));"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_add_signed(self, rhs: i64) -> (Self, bool) {
let (res, overflowed) = self.overflowing_add(rhs as Self);
(res, overflowed ^ (rhs < 0))
}
/// Calculates `self` - `rhs`.
///
/// Returns a tuple of the subtraction along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u64.overflowing_sub(2), (3, false));"]
#[doc = "assert_eq!(0u64.overflowing_sub(1), (u64::MAX, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::sub_with_overflow(self as u64, rhs as u64);
(a as Self, b)
}
/// Calculates `self` − `rhs` − `borrow` and returns a tuple
/// containing the difference and the output borrow.
///
/// Performs "ternary subtraction" by subtracting both an integer
/// operand and a borrow-in bit from `self`, and returns an output
/// integer and a borrow-out bit. This allows chaining together multiple
/// subtractions to create a wider subtraction, and can be useful for
/// bignum subtraction.
///
/// # Examples
///
/// ```
#[doc = "// 9 6 (a = 9 \u{d7} 2^64 + 6)"]
#[doc = "// - 5 7 (b = 5 \u{d7} 2^64 + 7)"]
/// // ---------
#[doc = "// 3 MAX (diff = 3 \u{d7} 2^64 + 2^64 - 1)"]
///
#[doc = "let (a1, a0): (u64, u64) = (9, 6);"]
#[doc = "let (b1, b0): (u64, u64) = (5, 7);"]
/// let borrow0 = false;
///
/// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);
/// assert_eq!(borrow1, true);
/// let (diff1, borrow2) = a1.borrowing_sub(b1, borrow1);
/// assert_eq!(borrow2, false);
///
#[doc = "assert_eq!((diff1, diff0), (3, u64::MAX));"]
/// ```
#[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
#[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue =
"152015")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
let (a, c1) = self.overflowing_sub(rhs);
let (b, c2) = a.overflowing_sub(borrow as u64);
(b, unsafe { intrinsics::disjoint_bitor(c1, c2) })
}
/// Calculates `self` - `rhs` with a signed `rhs`
///
/// Returns a tuple of the subtraction along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u64.overflowing_sub_signed(2), (u64::MAX, true));"]
#[doc = "assert_eq!(1u64.overflowing_sub_signed(-2), (3, false));"]
#[doc = "assert_eq!((u64::MAX - 2).overflowing_sub_signed(-4), (1, true));"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_sub_signed(self, rhs: i64) -> (Self, bool) {
let (res, overflow) = self.overflowing_sub(rhs as Self);
(res, overflow ^ (rhs < 0))
}
/// Computes the absolute difference between `self` and `other`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u64.abs_diff(80), 20u64);"]
#[doc = "assert_eq!(100u64.abs_diff(110), 10u64);"]
/// ```
#[stable(feature = "int_abs_diff", since = "1.60.0")]
#[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn abs_diff(self, other: Self) -> Self {
if size_of::<Self>() == 1 {
(self as i32).wrapping_sub(other as i32).unsigned_abs() as Self
} else { if self < other { other - self } else { self - other } }
}
/// Calculates the multiplication of `self` and `rhs`.
///
/// Returns a tuple of the multiplication along with a boolean
/// indicating whether an arithmetic overflow would occur. If an
/// overflow would have occurred then the wrapped value is returned.
///
/// If you want the *value* of the overflow, rather than just *whether*
/// an overflow occurred, see [`Self::carrying_mul`].
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `u32` is used.
///
/// ```
/// assert_eq!(5u32.overflowing_mul(2), (10, false));
/// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::mul_with_overflow(self as u64, rhs as u64);
(a as Self, b)
}
/// Calculates the "full multiplication" `self * rhs + carry`
/// without the possibility to overflow.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// Performs "long multiplication" which takes in an extra amount to add, and may return an
/// additional amount of overflow. This allows for chaining together multiple
/// multiplications to create "big integers" which represent larger values.
///
/// If you also need to add a value, then use [`Self::carrying_mul_add`].
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `u32` is used.
///
/// ```
/// assert_eq!(5u32.carrying_mul(2, 0), (10, 0));
/// assert_eq!(5u32.carrying_mul(2, 10), (20, 0));
/// assert_eq!(1_000_000_000u32.carrying_mul(10, 0), (1410065408, 2));
/// assert_eq!(1_000_000_000u32.carrying_mul(10, 10), (1410065418, 2));
#[doc =
"assert_eq!(u64::MAX.carrying_mul(u64::MAX, u64::MAX), (0, u64::MAX));"]
/// ```
///
/// This is the core operation needed for scalar multiplication when
/// implementing it for wider-than-native types.
///
/// ```
/// fn scalar_mul_eq(little_endian_digits: &mut Vec<u16>, multiplicand: u16) {
/// let mut carry = 0;
/// for d in little_endian_digits.iter_mut() {
/// (*d, carry) = d.carrying_mul(multiplicand, carry);
/// }
/// if carry != 0 {
/// little_endian_digits.push(carry);
/// }
/// }
///
/// let mut v = vec![10, 20];
/// scalar_mul_eq(&mut v, 3);
/// assert_eq!(v, [30, 60]);
///
/// assert_eq!(0x87654321_u64 * 0xFEED, 0x86D3D159E38D);
/// let mut v = vec![0x4321, 0x8765];
/// scalar_mul_eq(&mut v, 0xFEED);
/// assert_eq!(v, [0xE38D, 0xD159, 0x86D3]);
/// ```
///
/// If `carry` is zero, this is similar to [`overflowing_mul`](Self::overflowing_mul),
/// except that it gives the value of the overflow instead of just whether one happened:
///
/// ```
/// # #![allow(unused_features)]
/// #![feature(const_unsigned_bigint_helpers)]
/// let r = u8::carrying_mul(7, 13, 0);
/// assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(7, 13));
/// let r = u8::carrying_mul(13, 42, 0);
/// assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(13, 42));
/// ```
///
/// The value of the first field in the returned tuple matches what you'd get
/// by combining the [`wrapping_mul`](Self::wrapping_mul) and
/// [`wrapping_add`](Self::wrapping_add) methods:
///
/// ```
/// # #![allow(unused_features)]
/// #![feature(const_unsigned_bigint_helpers)]
/// assert_eq!(
/// 789_u16.carrying_mul(456, 123).0,
/// 789_u16.wrapping_mul(456).wrapping_add(123),
/// );
/// ```
#[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
#[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue =
"152015")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_mul(self, rhs: Self, carry: Self) -> (Self, Self) {
Self::carrying_mul_add(self, rhs, carry, 0)
}
/// Calculates the "full multiplication" `self * rhs + carry + add`.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// This cannot overflow, as the double-width result has exactly enough
/// space for the largest possible result. This is equivalent to how, in
/// decimal, 9 × 9 + 9 + 9 = 81 + 18 = 99 = 9×10⁰ + 9×10¹ = 10² - 1.
///
/// Performs "long multiplication" which takes in an extra amount to add, and may return an
/// additional amount of overflow. This allows for chaining together multiple
/// multiplications to create "big integers" which represent larger values.
///
/// If you don't need the `add` part, then you can use [`Self::carrying_mul`] instead.
///
/// # Examples
///
/// Please note that this example is shared between integer types,
/// which explains why `u32` is used here.
///
/// ```
/// assert_eq!(5u32.carrying_mul_add(2, 0, 0), (10, 0));
/// assert_eq!(5u32.carrying_mul_add(2, 10, 10), (30, 0));
/// assert_eq!(1_000_000_000u32.carrying_mul_add(10, 0, 0), (1410065408, 2));
/// assert_eq!(1_000_000_000u32.carrying_mul_add(10, 10, 10), (1410065428, 2));
#[doc =
"assert_eq!(u64::MAX.carrying_mul_add(u64::MAX, u64::MAX, u64::MAX), (u64::MAX, u64::MAX));"]
/// ```
///
/// This is the core per-digit operation for "grade school" O(n²) multiplication.
///
/// Please note that this example is shared between integer types,
/// using `u8` for simplicity of the demonstration.
///
/// ```
/// fn quadratic_mul<const N: usize>(a: [u8; N], b: [u8; N]) -> [u8; N] {
/// let mut out = [0; N];
/// for j in 0..N {
/// let mut carry = 0;
/// for i in 0..(N - j) {
/// (out[j + i], carry) = u8::carrying_mul_add(a[i], b[j], out[j + i], carry);
/// }
/// }
/// out
/// }
///
/// // -1 * -1 == 1
/// assert_eq!(quadratic_mul([0xFF; 3], [0xFF; 3]), [1, 0, 0]);
///
/// assert_eq!(u32::wrapping_mul(0x9e3779b9, 0x7f4a7c15), 0xcffc982d);
/// assert_eq!(
/// quadratic_mul(u32::to_le_bytes(0x9e3779b9), u32::to_le_bytes(0x7f4a7c15)),
/// u32::to_le_bytes(0xcffc982d)
/// );
/// ```
#[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
#[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue =
"152015")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_mul_add(self, rhs: Self, carry: Self, add: Self)
-> (Self, Self) {
intrinsics::carrying_mul_add(self, rhs, carry, add)
}
/// Calculates the divisor when `self` is divided by `rhs`.
///
/// Returns a tuple of the divisor along with a boolean indicating
/// whether an arithmetic overflow would occur. Note that for unsigned
/// integers overflow never occurs, so the second value is always
/// `false`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u64.overflowing_div(2), (2, false));"]
/// ```
#[inline(always)]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_overflowing_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[track_caller]
pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
(self / rhs, false)
}
/// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
///
/// Returns a tuple of the divisor along with a boolean indicating
/// whether an arithmetic overflow would occur. Note that for unsigned
/// integers overflow never occurs, so the second value is always
/// `false`.
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self.overflowing_div(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u64.overflowing_div_euclid(2), (2, false));"]
/// ```
#[inline(always)]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[track_caller]
pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
(self / rhs, false)
}
/// Calculates the remainder when `self` is divided by `rhs`.
///
/// Returns a tuple of the remainder after dividing along with a boolean
/// indicating whether an arithmetic overflow would occur. Note that for
/// unsigned integers overflow never occurs, so the second value is
/// always `false`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u64.overflowing_rem(2), (1, false));"]
/// ```
#[inline(always)]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_overflowing_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[track_caller]
pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
(self % rhs, false)
}
/// Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
///
/// Returns a tuple of the modulo after dividing along with a boolean
/// indicating whether an arithmetic overflow would occur. Note that for
/// unsigned integers overflow never occurs, so the second value is
/// always `false`.
/// Since, for the positive integers, all common
/// definitions of division are equal, this operation
/// is exactly equal to `self.overflowing_rem(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u64.overflowing_rem_euclid(2), (1, false));"]
/// ```
#[inline(always)]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[track_caller]
pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
(self % rhs, false)
}
/// Negates self in an overflowing fashion.
///
/// Returns `!self + 1` using wrapping operations to return the value
/// that represents the negation of this unsigned value. Note that for
/// positive unsigned values overflow always occurs, but negating 0 does
/// not overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0u64.overflowing_neg(), (0, false));"]
#[doc = "assert_eq!(2u64.overflowing_neg(), (-2i32 as u64, true));"]
/// ```
#[inline(always)]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn overflowing_neg(self) -> (Self, bool) {
((!self).wrapping_add(1), self != 0)
}
/// Shifts self left by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean
/// indicating whether the shift value was larger than or equal to the
/// number of bits. If the shift value is too large, then value is
/// masked (N-1) where N is the number of bits, and this value is then
/// used to perform the shift.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1u64.overflowing_shl(4), (0x10, false));"]
#[doc = "assert_eq!(0x1u64.overflowing_shl(132), (0x10, true));"]
#[doc = "assert_eq!(0x10u64.overflowing_shl(63), (0, false));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shl(rhs), rhs >= Self::BITS)
}
/// Shifts self right by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean
/// indicating whether the shift value was larger than or equal to the
/// number of bits. If the shift value is too large, then value is
/// masked (N-1) where N is the number of bits, and this value is then
/// used to perform the shift.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10u64.overflowing_shr(4), (0x1, false));"]
#[doc = "assert_eq!(0x10u64.overflowing_shr(132), (0x1, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shr(rhs), rhs >= Self::BITS)
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// Returns a tuple of the exponentiation along with a bool indicating
/// whether an overflow happened.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3u64.overflowing_pow(5), (243, false));"]
#[doc = "assert_eq!(0_u64.overflowing_pow(0), (1, false));"]
/// assert_eq!(3u8.overflowing_pow(6), (217, true));
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
let mut base = self;
let mut acc: Self = 1;
let mut overflow = false;
let mut tmp_overflow;
if intrinsics::is_val_statically_known(base) && base.is_power_of_two() {
let k = base.ilog2();
let Some(shift) = k.checked_mul(exp) else { return (0, true) };
return ((1 as Self).unbounded_shl(shift), shift >= Self::BITS)
}
if exp == 0 { return (1, false); }
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 {
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
}
exp /= 2;
(base, tmp_overflow) = base.overflowing_mul(base);
overflow |= tmp_overflow;
}
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
return (acc, overflow);
}
loop {
if (exp & 1) == 1 {
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
if exp == 1 { return (acc, overflow); }
}
exp /= 2;
(base, tmp_overflow) = base.overflowing_mul(base);
overflow |= tmp_overflow;
}
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u64.pow(5), 32);"]
#[doc = "assert_eq!(0_u64.pow(0), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn pow(self, exp: u32) -> Self {
if intrinsics::overflow_checks() {
self.strict_pow(exp)
} else { self.wrapping_pow(exp) }
}
/// Returns the square root of the number, rounded down.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10u64.isqrt(), 3);"]
/// ```
#[stable(feature = "isqrt", since = "1.84.0")]
#[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn isqrt(self) -> Self {
let result = imp::int_sqrt::u64(self as u64) as Self;
unsafe {
const MAX_RESULT: u64 = imp::int_sqrt::u64(<u64>::MAX) as u64;
crate::hint::assert_unchecked(result <= MAX_RESULT)
}
if self >= 1 { unsafe { crate::hint::assert_unchecked(result >= 1) } }
unsafe {
crate::hint::assert_unchecked(result.unchecked_mul(result) <= self);
crate::hint::assert_unchecked(result <= self);
}
result
}
/// Performs Euclidean division.
///
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self / rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7u64.div_euclid(4), 1); // or any other integer type"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Calculates the least remainder of `self` when divided by
/// `rhs`.
///
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self % rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7u64.rem_euclid(4), 3); // or any other integer type"]
/// ```
#[doc(alias = "modulo", alias = "mod")]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
///
/// This is the same as performing `self / rhs` for all unsigned integers.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "assert_eq!(7_u64.div_floor(4), 1);"]
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn div_floor(self, rhs: Self) -> Self { self / rhs }
/// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7_u64.div_ceil(4), 2);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_ceil(self, rhs: Self) -> Self {
let d = self / rhs;
let r = self % rhs;
if r > 0 { d + 1 } else { d }
}
/// Calculates the smallest value greater than or equal to `self` that
/// is a multiple of `rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// On overflow, this function will panic if overflow checks are enabled (default in debug
/// mode) and wrap if overflow checks are disabled (default in release mode).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(16_u64.next_multiple_of(8), 16);"]
#[doc = "assert_eq!(23_u64.next_multiple_of(8), 24);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_multiple_of(self, rhs: Self) -> Self {
match self % rhs { 0 => self, r => self + (rhs - r), }
}
/// Calculates the smallest value greater than or equal to `self` that
/// is a multiple of `rhs`. Returns `None` if `rhs` is zero or the
/// operation would result in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(16_u64.checked_next_multiple_of(8), Some(16));"]
#[doc = "assert_eq!(23_u64.checked_next_multiple_of(8), Some(24));"]
#[doc = "assert_eq!(1_u64.checked_next_multiple_of(0), None);"]
#[doc = "assert_eq!(u64::MAX.checked_next_multiple_of(2), None);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
match match self.checked_rem(rhs) { Some(x) => x, None => return None, } {
0 => Some(self),
r => self.checked_add(rhs - r),
}
}
/// Returns `true` if `self` is an integer multiple of `rhs`, and false otherwise.
///
/// This function is equivalent to `self % rhs == 0`, except that it will not panic
/// for `rhs == 0`. Instead, `0.is_multiple_of(0) == true`, and for any non-zero `n`,
/// `n.is_multiple_of(0) == false`.
///
/// # Examples
///
/// ```
#[doc = "assert!(6_u64.is_multiple_of(2));"]
#[doc = "assert!(!5_u64.is_multiple_of(2));"]
///
#[doc = "assert!(0_u64.is_multiple_of(0));"]
#[doc = "assert!(!6_u64.is_multiple_of(0));"]
/// ```
#[stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
#[rustc_const_stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
#[must_use]
#[inline]
pub const fn is_multiple_of(self, rhs: Self) -> bool {
match rhs { 0 => self == 0, _ => self % rhs == 0, }
}
/// Returns `true` if and only if `self == 2^k` for some unsigned integer `k`.
///
/// # Examples
///
/// ```
#[doc = "assert!(16u64.is_power_of_two());"]
#[doc = "assert!(!10u64.is_power_of_two());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
#[inline(always)]
pub const fn is_power_of_two(self) -> bool { self.count_ones() == 1 }
#[inline]
const fn one_less_than_next_power_of_two(self) -> Self {
if self <= 1 { return 0; }
let p = self - 1;
let z = unsafe { intrinsics::ctlz_nonzero(p) };
<u64>::MAX >> z
}
/// Returns the smallest power of two greater than or equal to `self`.
///
/// When return value overflows (i.e., `self > (1 << (N-1))` for type
/// `uN`), it panics in debug mode and the return value is wrapped to 0 in
/// release mode (the only situation in which this method can return 0).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u64.next_power_of_two(), 2);"]
#[doc = "assert_eq!(3u64.next_power_of_two(), 4);"]
#[doc = "assert_eq!(0u64.next_power_of_two(), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_power_of_two(self) -> Self {
self.one_less_than_next_power_of_two() + 1
}
/// Returns the smallest power of two greater than or equal to `self`. If
/// the next power of two is greater than the type's maximum value,
/// `None` is returned, otherwise the power of two is wrapped in `Some`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u64.checked_next_power_of_two(), Some(2));"]
#[doc = "assert_eq!(3u64.checked_next_power_of_two(), Some(4));"]
#[doc = "assert_eq!(u64::MAX.checked_next_power_of_two(), None);"]
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn checked_next_power_of_two(self) -> Option<Self> {
self.one_less_than_next_power_of_two().checked_add(1)
}
/// Returns the smallest power of two greater than or equal to `n`. If
/// the next power of two is greater than the type's maximum value,
/// the return value is wrapped to `0`.
///
/// # Examples
///
/// ```
/// #![feature(wrapping_next_power_of_two)]
///
#[doc = "assert_eq!(2u64.wrapping_next_power_of_two(), 2);"]
#[doc = "assert_eq!(3u64.wrapping_next_power_of_two(), 4);"]
#[doc = "assert_eq!(u64::MAX.wrapping_next_power_of_two(), 0);"]
/// ```
#[inline]
#[unstable(feature = "wrapping_next_power_of_two", issue = "32463", reason =
"needs decision on wrapping behavior")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn wrapping_next_power_of_two(self) -> Self {
self.one_less_than_next_power_of_two().wrapping_add(1)
}
/// Returns the memory representation of this integer as a byte array in
/// big-endian (network) byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234567890123456u64.to_be_bytes();"]
#[doc =
"assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
self.to_be().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// little-endian byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234567890123456u64.to_le_bytes();"]
#[doc =
"assert_eq!(bytes, [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
self.to_le().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code
/// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
/// instead.
///
#[doc = ""]
///
/// [`to_be_bytes`]: Self::to_be_bytes
/// [`to_le_bytes`]: Self::to_le_bytes
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234567890123456u64.to_ne_bytes();"]
/// assert_eq!(
/// bytes,
/// if cfg!(target_endian = "big") {
#[doc = " [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]"]
/// } else {
#[doc = " [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]"]
/// }
/// );
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[allow(unnecessary_transmutes)]
#[inline]
pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
unsafe { mem::transmute(self) }
}
/// Creates a native endian integer value from its representation
/// as a byte array in big endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc =
"let value = u64::from_be_bytes([0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]);"]
#[doc = "assert_eq!(value, 0x1234567890123456);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_be_u64(input: &mut &[u8]) -> u64 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u64>());"]
/// *input = rest;
#[doc = " u64::from_be_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_be(Self::from_ne_bytes(bytes))
}
/// Creates a native endian integer value from its representation
/// as a byte array in little endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc =
"let value = u64::from_le_bytes([0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);"]
#[doc = "assert_eq!(value, 0x1234567890123456);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_le_u64(input: &mut &[u8]) -> u64 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u64>());"]
/// *input = rest;
#[doc = " u64::from_le_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_le(Self::from_ne_bytes(bytes))
}
/// Creates a native endian integer value from its memory representation
/// as a byte array in native endianness.
///
/// As the target platform's native endianness is used, portable code
/// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
/// appropriate instead.
///
/// [`from_be_bytes`]: Self::from_be_bytes
/// [`from_le_bytes`]: Self::from_le_bytes
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = u64::from_ne_bytes(if cfg!(target_endian = \"big\") {"]
#[doc = " [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]"]
/// } else {
#[doc = " [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]"]
/// });
#[doc = "assert_eq!(value, 0x1234567890123456);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_ne_u64(input: &mut &[u8]) -> u64 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u64>());"]
/// *input = rest;
#[doc = " u64::from_ne_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use]
#[inline]
pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
unsafe { mem::transmute(bytes) }
}
/// New code should prefer to use
#[doc = "[`u64::MIN`] instead."]
///
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_promotable]
#[inline(always)]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MIN` associated constant on this type")]
#[rustc_diagnostic_item = "u64_legacy_fn_min_value"]
pub const fn min_value() -> Self { Self::MIN }
/// New code should prefer to use
#[doc = "[`u64::MAX`] instead."]
///
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_promotable]
#[inline(always)]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MAX` associated constant on this type")]
#[rustc_diagnostic_item = "u64_legacy_fn_max_value"]
pub const fn max_value() -> Self { Self::MAX }
/// Truncate an integer to an integer of the same size or smaller, preserving the least
/// significant bits.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u8, 120u64.truncate());"]
/// assert_eq!(120u8, 376u32.truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
/// instead of truncating.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u8, 120u64.saturating_truncate());"]
/// assert_eq!(255u8, 376u32.saturating_truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn saturating_truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_saturating_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
/// is outside the bounds of the smaller type.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(Some(120u8), 120u64.checked_truncate());"]
/// assert_eq!(None, 376u32.checked_truncate::<u8>());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn checked_truncate<Target>(self) -> Option<Target> where
Self: [const] traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_checked_truncate(self)
}
/// Widen to an integer of the same size or larger, preserving its value.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u128, 120u8.widen());"]
/// ```
#[must_use =
"this returns the widened value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn widen<Target>(self) -> Target where Self: [const]
traits::WidenTarget<Target> {
traits::WidenTarget::internal_widen(self)
}
/// Converts `self` to the target integer type, saturating at the numeric
/// bounds instead of overflowing.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(255u8, u64::MAX.saturating_cast());"]
#[doc = "assert_eq!(127i8, u64::MAX.saturating_cast());"]
#[doc = "assert_eq!(42i8, 42u64.saturating_cast());"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn saturating_cast<T: [const] BoundedCastFromInt<Self>>(self) -> T {
T::saturating_cast_from(self)
}
/// Converts `self` to the target integer type, wrapping around at the
/// boundary of the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(255u8, u64::MAX.wrapping_cast());"]
#[doc = "assert_eq!(42i8, 42u64.wrapping_cast());"]
#[doc = "assert_eq!(u64::MAX as i8, u64::MAX.wrapping_cast());"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn wrapping_cast<T: [const] BoundedCastFromInt<Self>>(self) -> T {
T::wrapping_cast_from(self)
}
/// Converts `self` to the target integer type, returning `None` if the value
/// is not representable by the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(Some(42u8), 42u64.checked_cast());"]
#[doc = "assert_eq!(128u64.checked_cast::<i8>(), None);"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn checked_cast<T: [const] CheckedCastFromInt<Self>>(self)
-> Option<T> {
T::checked_cast_from(self)
}
/// Converts `self` to the target integer type, panicking if the value
/// is not representable by the target type.
///
/// # Panics
///
/// This function will panic if the value is not representable by the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(42u8, 42u64.strict_cast());"]
/// ```
///
/// The following will panic:
///
/// ```should_panic
/// #![feature(integer_casts)]
#[doc = "let _ = 128u64.strict_cast::<i8>();"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
#[track_caller]
pub const fn strict_cast<T: [const] CheckedCastFromInt<Self>>(self) -> T {
T::strict_cast_from(self)
}
/// Converts `self` to the target integer type, assuming the value is
/// representable by the target type.
///
/// # Safety
///
/// This results in undefined behavior if the integer value of `self` is bigger than `T::MAX`,
/// or smaller than `T::MIN`, where `T` is the target type.
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const unsafe fn unchecked_cast<T: [const] CheckedCastFromInt<Self>>(self)
-> T {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(in_bounds: bool) {
if !in_bounds {
let msg =
"unsafe precondition(s) violated: u64::unchecked_cast must fit in the target type\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check({
let cast_val = self.checked_cast::<T>();
let ret = cast_val.is_some();
core::mem::forget(cast_val);
ret
});
}
};
unsafe { T::unchecked_cast_from(self) }
}uint_impl! {
1320Self = u64,
1321 ActualT = u64,
1322 SignedT = i64,
1323 BITS = 64,
1324 BITS_MINUS_ONE = 63,
1325 MAX = 18446744073709551615,
1326 rot = 12,
1327 rot_op = "0xaa00000000006e1",
1328 rot_result = "0x6e10aa",
1329 fsh_op = "0x2fe78e45983acd98",
1330 fshl_result = "0x6e12fe",
1331 fshr_result = "0x6e12fe78e45983ac",
1332 clmul_lhs = "0x7890123456789012",
1333 clmul_rhs = "0xdd358416f52ecd34",
1334 clmul_result = "0xa6299579b980928",
1335 swap_op = "0x1234567890123456",
1336 swapped = "0x5634129078563412",
1337 reversed = "0x6a2c48091e6a2c48",
1338 le_bytes = "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
1339 be_bytes = "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
1340 to_xe_bytes_doc = "",
1341 from_xe_bytes_doc = "",
1342 bound_condition = "",
1343 }1344/// Calculates the midpoint (average) between `self` and `rhs`.
///
/// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
/// sufficiently-large unsigned integral type. This implies that the result is
/// always rounded towards zero and that no overflow will ever occur.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0u64.midpoint(4), 2);"]
#[doc = "assert_eq!(1u64.midpoint(4), 2);"]
/// ```
#[stable(feature = "num_midpoint", since = "1.85.0")]
#[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[doc(alias = "average_floor")]
#[doc(alias = "average")]
#[inline]
pub const fn midpoint(self, rhs: u64) -> u64 {
((self as u128 + rhs as u128) / 2) as u64
}midpoint_impl! { u64, u128, unsigned }1345/// Widening multiplication. Computes `self * rhs`, widening to a larger integer.
///
/// The returned value is always exact and can never overflow.
///
/// Note that this method is semantically equivalent to [`carrying_mul`] with a
/// carry of zero, with the latter instead returning a tuple denoting the low and
/// high parts of the result. Consider using it instead if you need
/// interoperability with other big int helper functions, or if this method isn't
/// available for a given type.
///
/// [`carrying_mul`]: Self::carrying_mul
///
/// # Examples
///
/// ```
/// #![feature(widening_mul)]
///
#[doc = "assert_eq!(u64::MAX.widening_mul(0_u64), 0);"]
#[doc =
"assert_eq!(u64::MAX.widening_mul(u64::MAX), u64::MAX as u128 * u64::MAX as u128);"]
/// ```
#[unstable(feature = "widening_mul", issue = "152016")]
#[rustc_const_unstable(feature = "widening_mul", issue = "152016")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn widening_mul(self, rhs: Self) -> u128 {
self as u128 * rhs as u128
}widening_mul_impl! { u64, u128 }1346/// Performs a widening carry-less multiplication.
///
/// # Examples
///
/// ```
/// #![feature(uint_carryless_mul)]
///
#[doc =
"assert_eq!(u64::MAX.widening_carryless_mul(u64::MAX), u128::MAX / 3);"]
/// ```
#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
#[doc(alias = "clmul")]
#[unstable(feature = "uint_carryless_mul", issue = "152080")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn widening_carryless_mul(self, rhs: u64) -> u128 {
(self as u128).carryless_mul(rhs as u128)
}widening_carryless_mul_impl! { u64, u128 }1347/// Calculates the "full carryless multiplication" without the possibility to overflow.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `u8` is used.
///
/// ```
/// #![feature(uint_carryless_mul)]
///
/// assert_eq!(0b1000_0000u8.carrying_carryless_mul(0b1000_0000, 0b0000), (0, 0b0100_0000));
/// assert_eq!(0b1000_0000u8.carrying_carryless_mul(0b1000_0000, 0b1111), (0b1111, 0b0100_0000));
#[doc =
"assert_eq!(u64::MAX.carrying_carryless_mul(u64::MAX, u64::MAX), (!(u64::MAX / 3), u64::MAX / 3));"]
/// ```
#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
#[doc(alias = "clmul")]
#[unstable(feature = "uint_carryless_mul", issue = "152080")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_carryless_mul(self, rhs: Self, carry: Self)
-> (Self, Self) {
let p = (self as u128).carryless_mul(rhs as u128);
let lo = (p as u64);
let hi = (p >> Self::BITS) as u64;
(lo ^ carry, hi)
}carrying_carryless_mul_impl! { u64, u128 }1348}
13491350impl u128 {
1351/// The smallest value that can be represented by this integer type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(u128::MIN, 0);"]
/// ```
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MIN: Self = 0;
/// The largest value that can be represented by this integer type
#[doc = "(2<sup>128</sup> − 1)."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(u128::MAX, 340282366920938463463374607431768211455);"]
/// ```
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MAX: Self = !0;
/// The size of this integer type in bits.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(u128::BITS, 128);"]
/// ```
#[stable(feature = "int_bits_const", since = "1.53.0")]
pub const BITS: u32 = Self::MAX.count_ones();
/// Returns the number of ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 0b01001100u128;"]
/// assert_eq!(n.count_ones(), 3);
///
#[doc = "let max = u128::MAX;"]
#[doc = "assert_eq!(max.count_ones(), 128);"]
///
#[doc = "let zero = 0u128;"]
/// assert_eq!(zero.count_ones(), 0);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[doc(alias = "popcount")]
#[doc(alias = "popcnt")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn count_ones(self) -> u32 { return intrinsics::ctpop(self); }
/// Returns the number of zeros in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let zero = 0u128;"]
#[doc = "assert_eq!(zero.count_zeros(), 128);"]
///
#[doc = "let max = u128::MAX;"]
/// assert_eq!(max.count_zeros(), 0);
/// ```
///
/// This is heavily dependent on the width of the type, and thus
/// might give surprising results depending on type inference:
/// ```
/// # fn foo(_: u8) {}
/// # fn bar(_: u16) {}
/// let lucky = 7;
/// foo(lucky);
/// assert_eq!(lucky.count_zeros(), 5);
/// assert_eq!(lucky.count_ones(), 3);
///
/// let lucky = 7;
/// bar(lucky);
/// assert_eq!(lucky.count_zeros(), 13);
/// assert_eq!(lucky.count_ones(), 3);
/// ```
/// You might want to use [`Self::count_ones`] instead, or emphasize
/// the type you're using in the call rather than method syntax:
/// ```
/// let small = 1;
#[doc = "assert_eq!(u128::count_zeros(small), 127);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn count_zeros(self) -> u32 { (!self).count_ones() }
/// Returns the number of leading zeros in the binary representation of `self`.
///
/// Depending on what you're doing with the value, you might also be interested in the
/// [`ilog2`] function which returns a consistent number, even if the type widens.
///
/// # Examples
///
/// ```
#[doc = "let n = u128::MAX >> 2;"]
/// assert_eq!(n.leading_zeros(), 2);
///
#[doc = "let zero = 0u128;"]
#[doc = "assert_eq!(zero.leading_zeros(), 128);"]
///
#[doc = "let max = u128::MAX;"]
/// assert_eq!(max.leading_zeros(), 0);
/// ```
#[doc = "[`ilog2`]: u128::ilog2"]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn leading_zeros(self) -> u32 {
return intrinsics::ctlz(self as u128);
}
/// Returns the number of trailing zeros in the binary representation
/// of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 0b0101000u128;"]
/// assert_eq!(n.trailing_zeros(), 3);
///
#[doc = "let zero = 0u128;"]
#[doc = "assert_eq!(zero.trailing_zeros(), 128);"]
///
#[doc = "let max = u128::MAX;"]
#[doc = "assert_eq!(max.trailing_zeros(), 0);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn trailing_zeros(self) -> u32 { return intrinsics::cttz(self); }
/// Returns the number of leading ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = !(u128::MAX >> 2);"]
/// assert_eq!(n.leading_ones(), 2);
///
#[doc = "let zero = 0u128;"]
/// assert_eq!(zero.leading_ones(), 0);
///
#[doc = "let max = u128::MAX;"]
#[doc = "assert_eq!(max.leading_ones(), 128);"]
/// ```
#[stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn leading_ones(self) -> u32 { (!self).leading_zeros() }
/// Returns the number of trailing ones in the binary representation
/// of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 0b1010111u128;"]
/// assert_eq!(n.trailing_ones(), 3);
///
#[doc = "let zero = 0u128;"]
/// assert_eq!(zero.trailing_ones(), 0);
///
#[doc = "let max = u128::MAX;"]
#[doc = "assert_eq!(max.trailing_ones(), 128);"]
/// ```
#[stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn trailing_ones(self) -> u32 { (!self).trailing_zeros() }
/// Returns the minimum number of bits required to represent `self`.
///
/// This method returns zero if `self` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0_u128.bit_width(), 0);"]
#[doc = "assert_eq!(0b111_u128.bit_width(), 3);"]
#[doc = "assert_eq!(0b1110_u128.bit_width(), 4);"]
#[doc = "assert_eq!(u128::MAX.bit_width(), 128);"]
/// ```
#[stable(feature = "uint_bit_width", since = "1.97.0")]
#[rustc_const_stable(feature = "uint_bit_width", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn bit_width(self) -> u32 { Self::BITS - self.leading_zeros() }
/// Returns `self` with only the most significant bit set, or `0` if
/// the input is `0`.
///
/// # Examples
///
/// ```
#[doc = "let n: u128 = 0b_01100100;"]
///
/// assert_eq!(n.isolate_highest_one(), 0b_01000000);
#[doc = "assert_eq!(0_u128.isolate_highest_one(), 0);"]
/// ```
#[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn isolate_highest_one(self) -> Self {
self &
(((1 as u128) <<
(<u128>::BITS - 1)).wrapping_shr(self.leading_zeros()))
}
/// Returns `self` with only the least significant bit set, or `0` if
/// the input is `0`.
///
/// # Examples
///
/// ```
#[doc = "let n: u128 = 0b_01100100;"]
///
/// assert_eq!(n.isolate_lowest_one(), 0b_00000100);
#[doc = "assert_eq!(0_u128.isolate_lowest_one(), 0);"]
/// ```
#[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn isolate_lowest_one(self) -> Self { self & self.wrapping_neg() }
/// Returns the index of the highest bit set to one in `self`, or `None`
/// if `self` is `0`.
///
/// Note that this is equivalent to [`checked_ilog2`](Self::checked_ilog2).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0b0_u128.highest_one(), None);"]
#[doc = "assert_eq!(0b1_u128.highest_one(), Some(0));"]
#[doc = "assert_eq!(0b1_0000_u128.highest_one(), Some(4));"]
#[doc = "assert_eq!(0b1_1111_u128.highest_one(), Some(4));"]
/// ```
#[stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn highest_one(self) -> Option<u32> {
match NonZero::new(self) {
Some(v) => Some(v.highest_one()),
None => None,
}
}
/// Returns the index of the lowest bit set to one in `self`, or `None`
/// if `self` is `0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0b0_u128.lowest_one(), None);"]
#[doc = "assert_eq!(0b1_u128.lowest_one(), Some(0));"]
#[doc = "assert_eq!(0b1_0000_u128.lowest_one(), Some(4));"]
#[doc = "assert_eq!(0b1_1111_u128.lowest_one(), Some(0));"]
/// ```
#[stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn lowest_one(self) -> Option<u32> {
match NonZero::new(self) {
Some(v) => Some(v.lowest_one()),
None => None,
}
}
/// Returns the bit pattern of `self` reinterpreted as a signed integer of the same size.
///
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
/// the same.
///
/// # Examples
///
/// ```
#[doc = "let n = u128::MAX;"]
///
#[doc = "assert_eq!(n.cast_signed(), -1i128);"]
/// ```
#[stable(feature = "integer_sign_cast", since = "1.87.0")]
#[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_signed(self) -> i128 { self as i128 }
/// Saturating conversion of `self` to a signed integer of the same size.
///
/// The signed integer's maximum value is returned if `self` is larger
/// than the maximum positive value representable by the signed integer.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`checked_cast_signed`](Self::checked_cast_signed),
/// or [`strict_cast_signed`](Self::strict_cast_signed).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = u128::MAX;"]
///
#[doc = "assert_eq!(n.saturating_cast_signed(), i128::MAX);"]
#[doc = "assert_eq!(64u128.saturating_cast_signed(), 64i128);"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_cast_signed(self) -> i128 {
if self <= <i128>::MAX.cast_unsigned() {
self.cast_signed()
} else { <i128>::MAX }
}
/// Checked conversion of `self` to a signed integer of the same size,
/// returning `None` if `self` is larger than the signed integer's
/// maximum value.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`saturating_cast_signed`](Self::saturating_cast_signed),
/// or [`strict_cast_signed`](Self::strict_cast_signed).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = u128::MAX;"]
///
#[doc = "assert_eq!(n.checked_cast_signed(), None);"]
#[doc = "assert_eq!(64u128.checked_cast_signed(), Some(64i128));"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn checked_cast_signed(self) -> Option<i128> {
if self <= <i128>::MAX.cast_unsigned() {
Some(self.cast_signed())
} else { None }
}
/// Strict conversion of `self` to a signed integer of the same size,
/// which panics if `self` is larger than the signed integer's maximum
/// value.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`checked_cast_signed`](Self::checked_cast_signed),
/// or [`saturating_cast_signed`](Self::saturating_cast_signed).
///
/// # Examples
///
/// ```should_panic
/// #![feature(integer_cast_extras)]
#[doc = "let _ = u128::MAX.strict_cast_signed();"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_cast_signed(self) -> i128 {
match self.checked_cast_signed() {
Some(n) => n,
None => imp::overflow_panic::cast_integer(),
}
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `<<` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x13f40000000000000000000000004f76u128;"]
#[doc = "let m = 0x4f7613f4;"]
///
#[doc = "assert_eq!(n.rotate_left(16), m);"]
#[doc = "assert_eq!(n.rotate_left(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
pub const fn rotate_left(self, n: u32) -> Self {
return intrinsics::rotate_left(self, n);
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `>>` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x4f7613f4u128;"]
#[doc = "let m = 0x13f40000000000000000000000004f76;"]
///
#[doc = "assert_eq!(n.rotate_right(16), m);"]
#[doc = "assert_eq!(n.rotate_right(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
pub const fn rotate_right(self, n: u32) -> Self {
return intrinsics::rotate_right(self, n);
}
/// Performs a left funnel shift (concatenates `self` with `rhs`, with `self`
/// making up the most significant half, then shifts the combined value left
/// by `n`, and most significant half is extracted to produce the result).
///
/// Please note this isn't the same operation as the `<<` shifting operator or
/// [`rotate_left`](Self::rotate_left), although `a.funnel_shl(a, n)` is *equivalent*
/// to `a.rotate_left(n)`.
///
/// # Panics
///
/// If `n` is greater than or equal to the number of bits in `self`
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(funnel_shifts)]
#[doc = "let a = 0x13f40000000000000000000000004f76u128;"]
#[doc = "let b = 0x2fe78e45983acd98039000008736273u128;"]
#[doc = "let m = 0x4f7602fe;"]
///
#[doc = "assert_eq!(a.funnel_shl(b, 16), m);"]
/// ```
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn funnel_shl(self, rhs: Self, n: u32) -> Self {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift left with overflow"));
}
};
unsafe { self.unchecked_funnel_shl(rhs, n) }
}
/// Performs a right funnel shift (concatenates `self` and `rhs`, with `self`
/// making up the most significant half, then shifts the combined value right
/// by `n`, and least significant half is extracted to produce the result).
///
/// Please note this isn't the same operation as the `>>` shifting operator or
/// [`rotate_right`](Self::rotate_right), although `a.funnel_shr(a, n)` is *equivalent*
/// to `a.rotate_right(n)`.
///
/// # Panics
///
/// If `n` is greater than or equal to the number of bits in `self`
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(funnel_shifts)]
#[doc = "let a = 0x13f40000000000000000000000004f76u128;"]
#[doc = "let b = 0x2fe78e45983acd98039000008736273u128;"]
#[doc = "let m = 0x4f7602fe78e45983acd9803900000873;"]
///
#[doc = "assert_eq!(a.funnel_shr(b, 16), m);"]
/// ```
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn funnel_shr(self, rhs: Self, n: u32) -> Self {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift right with overflow"));
}
};
unsafe { self.unchecked_funnel_shr(rhs, n) }
}
/// Unchecked funnel shift left.
///
/// # Safety
///
/// This results in undefined behavior if `n` is greater than or equal to
#[doc = "`u128::BITS`,"]
/// i.e. when [`funnel_shl`](Self::funnel_shl) would panic.
///
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_funnel_shl(self, low: Self, n: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(n: u32) {
if !(n < <u128>::BITS) {
let msg =
"unsafe precondition(s) violated: u128::unchecked_funnel_shl cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(n); }
};
unsafe { intrinsics::unchecked_funnel_shl(self, low, n) }
}
/// Unchecked funnel shift right.
///
/// # Safety
///
/// This results in undefined behavior if `n` is greater than or equal to
#[doc = "`u128::BITS`,"]
/// i.e. when [`funnel_shr`](Self::funnel_shr) would panic.
///
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_funnel_shr(self, low: Self, n: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(n: u32) {
if !(n < <u128>::BITS) {
let msg =
"unsafe precondition(s) violated: u128::unchecked_funnel_shr cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(n); }
};
unsafe { intrinsics::unchecked_funnel_shr(self, low, n) }
}
/// Performs a carry-less multiplication, returning the lower bits.
///
/// This operation is similar to long multiplication in base 2, except that exclusive or is
/// used instead of addition. The implementation is equivalent to:
///
/// ```no_run
#[doc = "pub fn carryless_mul(lhs: u128, rhs: u128) -> u128{"]
/// let mut retval = 0;
#[doc = " for i in 0..u128::BITS {"]
/// if (rhs >> i) & 1 != 0 {
/// // long multiplication would use +=
/// retval ^= lhs << i;
/// }
/// }
/// retval
/// }
/// ```
///
/// The actual implementation is more efficient, and on some platforms lowers directly to a
/// dedicated instruction.
///
/// # Uses
///
/// Carryless multiplication can be used to turn a bitmask of quote characters into a
/// bit mask of characters surrounded by quotes:
///
/// ```no_run
/// r#"abc xxx "foobar" zzz "a"!"#; // input string
/// 0b0000000010000001000001010; // quote_mask
/// 0b0000000001111110000000100; // quote_mask.carryless_mul(!0) & !quote_mask
/// ```
///
/// Another use is in cryptography, where carryless multiplication allows for efficient
/// implementations of polynomial multiplication in `GF(2)[X]`, the polynomial ring
/// over `GF(2)`.
///
/// # Examples
///
/// ```
/// #![feature(uint_carryless_mul)]
///
#[doc = "let a = 0x12345678901234567890123456789012u128;"]
#[doc = "let b = 0x4317e40ab4ddcf05dd358416f52ecd34u128;"]
///
#[doc = "assert_eq!(a.carryless_mul(b), 0xb9cf660de35d0c170a6299579b980928);"]
/// ```
#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
#[doc(alias = "clmul")]
#[unstable(feature = "uint_carryless_mul", issue = "152080")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn carryless_mul(self, rhs: Self) -> Self {
intrinsics::carryless_mul(self, rhs)
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x12345678901234567890123456789012u128;"]
/// let m = n.swap_bytes();
///
#[doc = "assert_eq!(m, 0x12907856341290785634129078563412);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn swap_bytes(self) -> Self {
intrinsics::bswap(self as u128) as Self
}
/// Returns an integer with the bit locations specified by `mask` packed
/// contiguously into the least significant bits of the result.
/// ```
/// #![feature(uint_gather_scatter_bits)]
#[doc = "let n: u128 = 0b1011_1100;"]
///
/// assert_eq!(n.extract_bits(0b0010_0100), 0b0000_0011);
/// assert_eq!(n.extract_bits(0xF0), 0b0000_1011);
/// ```
#[doc(alias = "pext")]
#[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn extract_bits(self, mask: Self) -> Self {
imp::int_bits::u128::extract_impl(self as u128, mask as u128) as u128
}
/// Returns an integer with the least significant bits of `self`
/// distributed to the bit locations specified by `mask`.
/// ```
/// #![feature(uint_gather_scatter_bits)]
#[doc = "let n: u128 = 0b1010_1101;"]
///
/// assert_eq!(n.deposit_bits(0b0101_0101), 0b0101_0001);
/// assert_eq!(n.deposit_bits(0xF0), 0b1101_0000);
/// ```
#[doc(alias = "pdep")]
#[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn deposit_bits(self, mask: Self) -> Self {
imp::int_bits::u128::deposit_impl(self as u128, mask as u128) as u128
}
/// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
/// second least-significant bit becomes second most-significant bit, etc.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x12345678901234567890123456789012u128;"]
/// let m = n.reverse_bits();
///
#[doc = "assert_eq!(m, 0x48091e6a2c48091e6a2c48091e6a2c48);"]
#[doc = "assert_eq!(0, 0u128.reverse_bits());"]
/// ```
#[stable(feature = "reverse_bits", since = "1.37.0")]
#[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn reverse_bits(self) -> Self {
intrinsics::bitreverse(self as u128) as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au128;"]
///
/// if cfg!(target_endian = "big") {
#[doc = " assert_eq!(u128::from_be(n), n)"]
/// } else {
#[doc = " assert_eq!(u128::from_be(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use]
#[inline(always)]
pub const fn from_be(x: Self) -> Self { x.swap_bytes() }
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au128;"]
///
/// if cfg!(target_endian = "little") {
#[doc = " assert_eq!(u128::from_le(n), n)"]
/// } else {
#[doc = " assert_eq!(u128::from_le(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use]
#[inline(always)]
pub const fn from_le(x: Self) -> Self { x }
/// Converts `self` to big endian from the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au128;"]
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn to_be(self) -> Self { self.swap_bytes() }
/// Converts `self` to little endian from the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au128;"]
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn to_le(self) -> Self { self }
/// Checked integer addition. Computes `self + rhs`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((u128::MAX - 2).checked_add(1), Some(u128::MAX - 1));"]
#[doc = "assert_eq!((u128::MAX - 2).checked_add(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(intrinsics::add_with_overflow(self, rhs).1) {
None
} else { Some(unsafe { intrinsics::unchecked_add(self, rhs) }) }
}
/// Strict integer addition. Computes `self + rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((u128::MAX - 2).strict_add(1), u128::MAX - 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (u128::MAX - 2).strict_add(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_add(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Unchecked integer addition. Computes `self + rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_add(y)` is semantically equivalent to calling
/// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_add`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self + rhs > u128::MAX`,"]
/// i.e. when [`checked_add`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_add`]: u128::checked_add"]
#[doc = "[`wrapping_add`]: u128::wrapping_add"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u128, rhs: u128) {
if !!lhs.overflowing_add(rhs).1 {
let msg =
"unsafe precondition(s) violated: u128::unchecked_add cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_add(self, rhs) }
}
/// Checked addition with a signed integer. Computes `self + rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u128.checked_add_signed(2), Some(3));"]
#[doc = "assert_eq!(1u128.checked_add_signed(-2), None);"]
#[doc = "assert_eq!((u128::MAX - 2).checked_add_signed(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add_signed(self, rhs: i128) -> Option<Self> {
let (a, b) = self.overflowing_add_signed(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict addition with a signed integer. Computes `self + rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u128.strict_add_signed(2), 3);"]
/// ```
///
/// The following panic because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1u128.strict_add_signed(-2);"]
/// ```
///
/// ```should_panic
#[doc = "let _ = (u128::MAX - 2).strict_add_signed(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add_signed(self, rhs: i128) -> Self {
let (a, b) = self.overflowing_add_signed(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Checked integer subtraction. Computes `self - rhs`, returning
/// `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u128.checked_sub(1), Some(0));"]
#[doc = "assert_eq!(0u128.checked_sub(1), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
if self < rhs {
None
} else { Some(unsafe { intrinsics::unchecked_sub(self, rhs) }) }
}
/// Strict integer subtraction. Computes `self - rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u128.strict_sub(1), 0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0u128.strict_sub(1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_sub(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
/// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_sub`].
///
/// If you find yourself writing code like this:
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if foo >= bar {
/// // SAFETY: just checked it will not overflow
/// let diff = unsafe { foo.unchecked_sub(bar) };
/// // ... use diff ...
/// }
/// ```
///
/// Consider changing it to
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if let Some(diff) = foo.checked_sub(bar) {
/// // ... use diff ...
/// }
/// ```
///
/// As that does exactly the same thing -- including telling the optimizer
/// that the subtraction cannot overflow -- but avoids needing `unsafe`.
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self - rhs < u128::MIN`,"]
/// i.e. when [`checked_sub`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_sub`]: u128::checked_sub"]
#[doc = "[`wrapping_sub`]: u128::wrapping_sub"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u128, rhs: u128) {
if !!lhs.overflowing_sub(rhs).1 {
let msg =
"unsafe precondition(s) violated: u128::unchecked_sub cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_sub(self, rhs) }
}
/// Checked subtraction with a signed integer. Computes `self - rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u128.checked_sub_signed(2), None);"]
#[doc = "assert_eq!(1u128.checked_sub_signed(-2), Some(3));"]
#[doc = "assert_eq!((u128::MAX - 2).checked_sub_signed(-4), None);"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub_signed(self, rhs: i128) -> Option<Self> {
let (res, overflow) = self.overflowing_sub_signed(rhs);
if !overflow { Some(res) } else { None }
}
/// Strict subtraction with a signed integer. Computes `self - rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3u128.strict_sub_signed(2), 1);"]
/// ```
///
/// The following panic because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1u128.strict_sub_signed(2);"]
/// ```
///
/// ```should_panic
#[doc = "let _ = (u128::MAX).strict_sub_signed(-1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub_signed(self, rhs: i128) -> Self {
let (a, b) = self.overflowing_sub_signed(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
#[doc =
"Checked integer subtraction. Computes `self - rhs` and checks if the result fits into an [`i128`], returning `None` if overflow occurred."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10u128.checked_signed_diff(2), Some(8));"]
#[doc = "assert_eq!(2u128.checked_signed_diff(10), Some(-8));"]
#[doc = "assert_eq!(u128::MAX.checked_signed_diff(i128::MAX as u128), None);"]
#[doc =
"assert_eq!((i128::MAX as u128).checked_signed_diff(u128::MAX), Some(i128::MIN));"]
#[doc = "assert_eq!((i128::MAX as u128 + 1).checked_signed_diff(0), None);"]
#[doc = "assert_eq!(u128::MAX.checked_signed_diff(u128::MAX), Some(0));"]
/// ```
#[stable(feature = "unsigned_signed_diff", since = "1.91.0")]
#[rustc_const_stable(feature = "unsigned_signed_diff", since = "1.91.0")]
#[inline]
pub const fn checked_signed_diff(self, rhs: Self) -> Option<i128> {
let res = self.wrapping_sub(rhs) as i128;
let overflow = (self >= rhs) == (res < 0);
if !overflow { Some(res) } else { None }
}
/// Checked integer multiplication. Computes `self * rhs`, returning
/// `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u128.checked_mul(1), Some(5));"]
#[doc = "assert_eq!(u128::MAX.checked_mul(2), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer multiplication. Computes `self * rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u128.strict_mul(1), 5);"]
/// ```
///
/// The following panics because of overflow:
///
/// ``` should_panic
#[doc = "let _ = u128::MAX.strict_mul(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_mul(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_mul(rhs);
if b { imp::overflow_panic::mul() } else { a }
}
/// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
/// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_mul`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self * rhs > u128::MAX`,"]
/// i.e. when [`checked_mul`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_mul`]: u128::checked_mul"]
#[doc = "[`wrapping_mul`]: u128::wrapping_mul"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u128, rhs: u128) {
if !!lhs.overflowing_mul(rhs).1 {
let msg =
"unsafe precondition(s) violated: u128::unchecked_mul cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_mul(self, rhs) }
}
/// Checked integer division. Computes `self / rhs`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128u128.checked_div(2), Some(64));"]
#[doc = "assert_eq!(1u128.checked_div(0), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(unsafe { intrinsics::unchecked_div(self, rhs) }) }
}
/// Strict integer division. Computes `self / rhs`.
///
/// Strict division on unsigned types is just normal division. There's no
/// way overflow could ever happen. This function exists so that all
/// operations are accounted for in the strict operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u128.strict_div(10), 10);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1u128).strict_div(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_div(self, rhs: Self) -> Self { self / rhs }
/// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128u128.checked_div_euclid(2), Some(64));"]
#[doc = "assert_eq!(1u128.checked_div_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(self.div_euclid(rhs)) }
}
/// Strict Euclidean division. Computes `self.div_euclid(rhs)`.
///
/// Strict division on unsigned types is just normal division. There's no
/// way overflow could ever happen. This function exists so that all
/// operations are accounted for in the strict operations. Since, for the
/// positive integers, all common definitions of division are equal, this
/// is exactly equal to `self.strict_div(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u128.strict_div_euclid(10), 10);"]
/// ```
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1u128).strict_div_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Checked integer division without remainder. Computes `self / rhs`,
/// returning `None` if `rhs == 0` or if `self % rhs != 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64u128.checked_div_exact(2), Some(32));"]
#[doc = "assert_eq!(64u128.checked_div_exact(32), Some(2));"]
#[doc = "assert_eq!(64u128.checked_div_exact(0), None);"]
#[doc = "assert_eq!(65u128.checked_div_exact(2), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_exact(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else {
unsafe {
if intrinsics::unlikely(intrinsics::unchecked_rem(self, rhs) != 0)
{
None
} else { Some(intrinsics::exact_div(self, rhs)) }
}
}
}
/// Integer division without remainder. Computes `self / rhs`, returning `None` if `self % rhs != 0`.
///
/// # Panics
///
/// This function will panic if `rhs == 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64u128.div_exact(2), Some(32));"]
#[doc = "assert_eq!(64u128.div_exact(32), Some(2));"]
#[doc = "assert_eq!(65u128.div_exact(2), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn div_exact(self, rhs: Self) -> Option<Self> {
if self % rhs != 0 { None } else { Some(self / rhs) }
}
/// Unchecked integer division without remainder. Computes `self / rhs`.
///
/// # Safety
///
/// This results in undefined behavior when `rhs == 0` or `self % rhs != 0`,
/// i.e. when [`checked_div_exact`](Self::checked_div_exact) would return `None`.
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_div_exact(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u128, rhs: u128) {
if !(rhs > 0 && lhs % rhs == 0) {
let msg =
"unsafe precondition(s) violated: u128::unchecked_div_exact divide by zero or leave a remainder\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::exact_div(self, rhs) }
}
/// Checked integer remainder. Computes `self % rhs`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u128.checked_rem(2), Some(1));"]
#[doc = "assert_eq!(5u128.checked_rem(0), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(unsafe { intrinsics::unchecked_rem(self, rhs) }) }
}
/// Strict integer remainder. Computes `self % rhs`.
///
/// Strict remainder calculation on unsigned types is just the regular
/// remainder calculation. There's no way overflow could ever happen.
/// This function exists so that all operations are accounted for in the
/// strict operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u128.strict_rem(10), 0);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5u128.strict_rem(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_rem(self, rhs: Self) -> Self { self % rhs }
/// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u128.checked_rem_euclid(2), Some(1));"]
#[doc = "assert_eq!(5u128.checked_rem_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(self.rem_euclid(rhs)) }
}
/// Strict Euclidean modulo. Computes `self.rem_euclid(rhs)`.
///
/// Strict modulo calculation on unsigned types is just the regular
/// remainder calculation. There's no way overflow could ever happen.
/// This function exists so that all operations are accounted for in the
/// strict operations. Since, for the positive integers, all common
/// definitions of division are equal, this is exactly equal to
/// `self.strict_rem(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u128.strict_rem_euclid(10), 0);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5u128.strict_rem_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Same value as `self | other`, but UB if any bit position is set in both inputs.
///
/// This is a situational micro-optimization for places where you'd rather
/// use addition on some platforms and bitwise or on other platforms, based
/// on exactly which instructions combine better with whatever else you're
/// doing. Note that there's no reason to bother using this for places
/// where it's clear from the operations involved that they can't overlap.
/// For example, if you're combining `u16`s into a `u32` with
/// `((a as u32) << 16) | (b as u32)`, that's fine, as the backend will
/// know those sides of the `|` are disjoint without needing help.
///
/// # Examples
///
/// ```
/// #![feature(disjoint_bitor)]
///
/// // SAFETY: `1` and `4` have no bits in common.
/// unsafe {
#[doc = " assert_eq!(1_u128.unchecked_disjoint_bitor(4), 5);"]
/// }
/// ```
///
/// # Safety
///
/// Requires that `(self & other) == 0`, otherwise it's immediate UB.
///
/// Equivalently, requires that `(self | other) == (self + other)`.
#[unstable(feature = "disjoint_bitor", issue = "135758")]
#[rustc_const_unstable(feature = "disjoint_bitor", issue = "135758")]
#[inline]
pub const unsafe fn unchecked_disjoint_bitor(self, other: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u128, rhs: u128) {
if !((lhs & rhs) == 0) {
let msg =
"unsafe precondition(s) violated: u128::unchecked_disjoint_bitor cannot have overlapping bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, other);
}
};
unsafe { intrinsics::disjoint_bitor(self, other) }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// This method might not be optimized owing to implementation details;
/// [`ilog2`](Self::ilog2) can produce results more efficiently for base 2,
/// and [`ilog10`](Self::ilog10) can produce results more efficiently for base 10.
///
/// # Panics
///
/// This function will panic if `self` is zero, or if `base` is less than 2.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u128.ilog(5), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog(self, base: Self) -> u32 {
if !(base >= 2) {
{
crate::panicking::panic_fmt(format_args!("base of integer logarithm must be at least 2"));
}
};
if let Some(log) = self.checked_ilog(base) {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the base 2 logarithm of the number, rounded down.
///
/// # Panics
///
/// This function will panic if `self` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u128.ilog2(), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog2(self) -> u32 {
if let Some(log) = self.checked_ilog2() {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// # Panics
///
/// This function will panic if `self` is zero.
///
/// # Example
///
/// ```
#[doc = "assert_eq!(10u128.ilog10(), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog10(self) -> u32 {
if let Some(log) = self.checked_ilog10() {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// Returns `None` if the number is zero, or if the base is not at least 2.
///
/// This method might not be optimized owing to implementation details;
/// `checked_ilog2` can produce results more efficiently for base 2, and
/// `checked_ilog10` can produce results more efficiently for base 10.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u128.checked_ilog(5), Some(1));"]
#[doc = "assert_eq!(4u128.checked_ilog(5), Some(0));"]
#[doc = "assert_eq!(5u128.checked_ilog(0), None);"]
#[doc = "assert_eq!(5u128.checked_ilog(1), None);"]
#[doc = "assert_eq!(0u128.checked_ilog(1), None);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog(self, base: Self) -> Option<u32> {
if core::intrinsics::is_val_statically_known(base) {
if base.is_power_of_two() && base > 1 {
let k = base.ilog2();
return Some(match self.checked_ilog2() {
Some(x) => x,
None => return None,
} / k);
}
if base == 10 { return self.checked_ilog10(); }
}
if self <= 0 || base <= 1 {
None
} else if self < base {
Some(0)
} else {
let mut n = 1;
let mut r = base;
if Self::BITS == 128 {
n = self.ilog2() / (base.ilog2() + 1);
r = base.pow(n);
}
while r <= self / base { n += 1; r *= base; }
Some(n)
}
}
/// Returns the base 2 logarithm of the number, rounded down.
///
/// Returns `None` if the number is zero.
///
/// Note that this is equivalent to [`highest_one`](Self::highest_one).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u128.checked_ilog2(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog2(self) -> Option<u32> {
match NonZero::new(self) { Some(x) => Some(x.ilog2()), None => None, }
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// Returns `None` if the number is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10u128.checked_ilog10(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog10(self) -> Option<u32> {
match NonZero::new(self) { Some(x) => Some(x.ilog10()), None => None, }
}
/// Checked negation. Computes `-self`, returning `None` unless `self ==
/// 0`.
///
/// Note that negating any positive integer will overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0u128.checked_neg(), Some(0));"]
#[doc = "assert_eq!(1u128.checked_neg(), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_neg(self) -> Option<Self> {
let (a, b) = self.overflowing_neg();
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict negation. Computes `-self`, panicking unless `self ==
/// 0`.
///
/// Note that negating any positive integer will overflow.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0u128.strict_neg(), 0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1u128.strict_neg();"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_neg(self) -> Self {
let (a, b) = self.overflowing_neg();
if b { imp::overflow_panic::neg() } else { a }
}
/// Checked shift left. Computes `self << rhs`, returning `None`
/// if `rhs` is larger than or equal to the number of bits in `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1u128.checked_shl(4), Some(0x10));"]
#[doc = "assert_eq!(0x10u128.checked_shl(129), None);"]
#[doc = "assert_eq!(0x10u128.checked_shl(127), Some(0));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
if rhs < Self::BITS {
Some(unsafe { self.unchecked_shl(rhs) })
} else { None }
}
/// Strict shift left. Computes `self << rhs`, panicking if `rhs` is larger
/// than or equal to the number of bits in `self`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1u128.strict_shl(4), 0x10);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0x10u128.strict_shl(129);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_shl(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_shl(rhs);
if b { imp::overflow_panic::shl() } else { a }
}
/// Unchecked shift left. Computes `self << rhs`, assuming that
/// `rhs` is less than the number of bits in `self`.
///
/// # Safety
///
/// This results in undefined behavior if `rhs` is larger than
/// or equal to the number of bits in `self`,
/// i.e. when [`checked_shl`] would return `None`.
///
#[doc = "[`checked_shl`]: u128::checked_shl"]
#[stable(feature = "unchecked_shifts", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_shl(self, rhs: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(rhs: u32) {
if !(rhs < <u128>::BITS) {
let msg =
"unsafe precondition(s) violated: u128::unchecked_shl cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(rhs); }
};
unsafe { intrinsics::unchecked_shl(self, rhs) }
}
/// Unbounded shift left. Computes `self << rhs`, without bounding the value of `rhs`.
///
/// If `rhs` is larger or equal to the number of bits in `self`,
/// the entire value is shifted out, and `0` is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1_u128.unbounded_shl(4), 0x10);"]
#[doc = "assert_eq!(0x1_u128.unbounded_shl(129), 0);"]
#[doc = "assert_eq!(0b101_u128.unbounded_shl(0), 0b101);"]
#[doc = "assert_eq!(0b101_u128.unbounded_shl(1), 0b1010);"]
#[doc = "assert_eq!(0b101_u128.unbounded_shl(2), 0b10100);"]
#[doc = "assert_eq!(42_u128.unbounded_shl(128), 0);"]
#[doc = "assert_eq!(42_u128.unbounded_shl(1).unbounded_shl(127), 0);"]
///
#[doc = "let start : u128 = 13;"]
/// let mut running = start;
/// for i in 0..160 {
/// // The unbounded shift left by i is the same as `<< 1` i times
/// assert_eq!(running, start.unbounded_shl(i));
/// // Which is not always the case for a wrapping shift
#[doc = " assert_eq!(running == start.wrapping_shl(i), i < 128);"]
///
/// running <<= 1;
/// }
/// ```
#[stable(feature = "unbounded_shifts", since = "1.87.0")]
#[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unbounded_shl(self, rhs: u32) -> u128 {
if rhs < Self::BITS { unsafe { self.unchecked_shl(rhs) } } else { 0 }
}
/// Exact shift left. Computes `self << rhs` as long as it can be reversed losslessly.
///
/// Returns `None` if any non-zero bits would be shifted out or if `rhs` >=
#[doc = "`u128::BITS`."]
/// Otherwise, returns `Some(self << rhs)`.
///
/// # Examples
///
/// ```
/// #![feature(exact_bitshifts)]
///
#[doc = "assert_eq!(0x1u128.shl_exact(4), Some(0x10));"]
#[doc = "assert_eq!(0x1u128.shl_exact(129), None);"]
/// ```
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn shl_exact(self, rhs: u32) -> Option<u128> {
if rhs <= self.leading_zeros() && rhs < <u128>::BITS {
Some(unsafe { self.unchecked_shl(rhs) })
} else { None }
}
/// Unchecked exact shift left. Computes `self << rhs`, assuming the operation can be
/// losslessly reversed `rhs` cannot be larger than
#[doc = "`u128::BITS`."]
///
/// # Safety
///
/// This results in undefined behavior when `rhs > self.leading_zeros() || rhs >=
#[doc = "u128::BITS`"]
/// i.e. when
#[doc = "[`u128::shl_exact`]"]
/// would return `None`.
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_shl_exact(self, rhs: u32) -> u128 {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(zeros: u32, bits: u32, rhs: u32) {
if !(rhs <= zeros && rhs < bits) {
let msg =
"unsafe precondition(s) violated: u128::unchecked_shl_exact cannot shift out non-zero bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_library_ub() {
precondition_check(self.leading_zeros(), <u128>::BITS, rhs);
}
};
unsafe { self.unchecked_shl(rhs) }
}
/// Checked shift right. Computes `self >> rhs`, returning `None`
/// if `rhs` is larger than or equal to the number of bits in `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10u128.checked_shr(4), Some(0x1));"]
#[doc = "assert_eq!(0x10u128.checked_shr(129), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
if rhs < Self::BITS {
Some(unsafe { self.unchecked_shr(rhs) })
} else { None }
}
/// Strict shift right. Computes `self >> rhs`, panicking if `rhs` is
/// larger than or equal to the number of bits in `self`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10u128.strict_shr(4), 0x1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0x10u128.strict_shr(129);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_shr(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_shr(rhs);
if b { imp::overflow_panic::shr() } else { a }
}
/// Unchecked shift right. Computes `self >> rhs`, assuming that
/// `rhs` is less than the number of bits in `self`.
///
/// # Safety
///
/// This results in undefined behavior if `rhs` is larger than
/// or equal to the number of bits in `self`,
/// i.e. when [`checked_shr`] would return `None`.
///
#[doc = "[`checked_shr`]: u128::checked_shr"]
#[stable(feature = "unchecked_shifts", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_shr(self, rhs: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(rhs: u32) {
if !(rhs < <u128>::BITS) {
let msg =
"unsafe precondition(s) violated: u128::unchecked_shr cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(rhs); }
};
unsafe { intrinsics::unchecked_shr(self, rhs) }
}
/// Unbounded shift right. Computes `self >> rhs`, without bounding the value of `rhs`.
///
/// If `rhs` is larger or equal to the number of bits in `self`,
/// the entire value is shifted out, and `0` is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10_u128.unbounded_shr(4), 0x1);"]
#[doc = "assert_eq!(0x10_u128.unbounded_shr(129), 0);"]
#[doc = "assert_eq!(0b1010_u128.unbounded_shr(0), 0b1010);"]
#[doc = "assert_eq!(0b1010_u128.unbounded_shr(1), 0b101);"]
#[doc = "assert_eq!(0b1010_u128.unbounded_shr(2), 0b10);"]
#[doc = "assert_eq!(42_u128.unbounded_shr(128), 0);"]
#[doc = "assert_eq!(42_u128.unbounded_shr(1).unbounded_shr(127), 0);"]
///
#[doc = "let start = u128::rotate_right(13, 4);"]
/// let mut running = start;
/// for i in 0..160 {
/// // The unbounded shift right by i is the same as `>> 1` i times
/// assert_eq!(running, start.unbounded_shr(i));
/// // Which is not always the case for a wrapping shift
#[doc = " assert_eq!(running == start.wrapping_shr(i), i < 128);"]
///
/// running >>= 1;
/// }
/// ```
#[stable(feature = "unbounded_shifts", since = "1.87.0")]
#[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unbounded_shr(self, rhs: u32) -> u128 {
if rhs < Self::BITS { unsafe { self.unchecked_shr(rhs) } } else { 0 }
}
/// Exact shift right. Computes `self >> rhs` as long as it can be reversed losslessly.
///
/// Returns `None` if any non-zero bits would be shifted out or if `rhs` >=
#[doc = "`u128::BITS`."]
/// Otherwise, returns `Some(self >> rhs)`.
///
/// # Examples
///
/// ```
/// #![feature(exact_bitshifts)]
///
#[doc = "assert_eq!(0x10u128.shr_exact(4), Some(0x1));"]
#[doc = "assert_eq!(0x10u128.shr_exact(5), None);"]
/// ```
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn shr_exact(self, rhs: u32) -> Option<u128> {
if rhs <= self.trailing_zeros() && rhs < <u128>::BITS {
Some(unsafe { self.unchecked_shr(rhs) })
} else { None }
}
/// Unchecked exact shift right. Computes `self >> rhs`, assuming the operation can be
/// losslessly reversed and `rhs` cannot be larger than
#[doc = "`u128::BITS`."]
///
/// # Safety
///
/// This results in undefined behavior when `rhs > self.trailing_zeros() || rhs >=
#[doc = "u128::BITS`"]
/// i.e. when
#[doc = "[`u128::shr_exact`]"]
/// would return `None`.
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_shr_exact(self, rhs: u32) -> u128 {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(zeros: u32, bits: u32, rhs: u32) {
if !(rhs <= zeros && rhs < bits) {
let msg =
"unsafe precondition(s) violated: u128::unchecked_shr_exact cannot shift out non-zero bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_library_ub() {
precondition_check(self.trailing_zeros(), <u128>::BITS, rhs);
}
};
unsafe { self.unchecked_shr(rhs) }
}
/// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u128.checked_pow(5), Some(32));"]
#[doc = "assert_eq!(0_u128.checked_pow(0), Some(1));"]
#[doc = "assert_eq!(u128::MAX.checked_pow(2), None);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
let mut base = self;
let mut acc: Self = 1;
if intrinsics::is_val_statically_known(base) && base.is_power_of_two() {
let k = base.ilog2();
let shift =
match k.checked_mul(exp) { Some(x) => x, None => return None, };
return (1 as Self).checked_shl(shift);
}
if exp == 0 { return Some(1); }
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 {
acc =
match acc.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
exp /= 2;
base =
match base.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
return acc.checked_mul(base);
}
loop {
if (exp & 1) == 1 {
acc =
match acc.checked_mul(base) {
Some(x) => x,
None => return None,
};
if exp == 1 { return Some(acc); }
}
exp /= 2;
base =
match base.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
}
/// Strict exponentiation. Computes `self.pow(exp)`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u128.strict_pow(5), 32);"]
#[doc = "assert_eq!(0_u128.strict_pow(0), 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = u128::MAX.strict_pow(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) {
None => imp::overflow_panic::pow(),
Some(a) => a,
}
}
/// Saturating integer addition. Computes `self + rhs`, saturating at
/// the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u128.saturating_add(1), 101);"]
#[doc = "assert_eq!(u128::MAX.saturating_add(127), u128::MAX);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[inline(always)]
pub const fn saturating_add(self, rhs: Self) -> Self {
intrinsics::saturating_add(self, rhs)
}
/// Saturating addition with a signed integer. Computes `self + rhs`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u128.saturating_add_signed(2), 3);"]
#[doc = "assert_eq!(1u128.saturating_add_signed(-2), 0);"]
#[doc = "assert_eq!((u128::MAX - 2).saturating_add_signed(4), u128::MAX);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_add_signed(self, rhs: i128) -> Self {
let (res, overflow) = self.overflowing_add(rhs as Self);
if overflow == (rhs < 0) { res } else if overflow { Self::MAX } else { 0 }
}
/// Saturating integer subtraction. Computes `self - rhs`, saturating
/// at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u128.saturating_sub(27), 73);"]
#[doc = "assert_eq!(13u128.saturating_sub(127), 0);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[inline(always)]
pub const fn saturating_sub(self, rhs: Self) -> Self {
intrinsics::saturating_sub(self, rhs)
}
/// Saturating integer subtraction. Computes `self` - `rhs`, saturating at
/// the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u128.saturating_sub_signed(2), 0);"]
#[doc = "assert_eq!(1u128.saturating_sub_signed(-2), 3);"]
#[doc = "assert_eq!((u128::MAX - 2).saturating_sub_signed(-4), u128::MAX);"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_sub_signed(self, rhs: i128) -> Self {
let (res, overflow) = self.overflowing_sub_signed(rhs);
if !overflow { res } else if rhs < 0 { Self::MAX } else { 0 }
}
/// Saturating integer multiplication. Computes `self * rhs`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u128.saturating_mul(10), 20);"]
#[doc = "assert_eq!((u128::MAX).saturating_mul(10), u128::MAX);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_mul(self, rhs: Self) -> Self {
match self.checked_mul(rhs) { Some(x) => x, None => Self::MAX, }
}
/// Saturating integer division. Computes `self / rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u128.saturating_div(2), 2);"]
///
/// ```
#[stable(feature = "saturating_div", since = "1.58.0")]
#[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn saturating_div(self, rhs: Self) -> Self {
self.wrapping_div(rhs)
}
/// Saturating integer exponentiation. Computes `self.pow(exp)`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(4u128.saturating_pow(3), 64);"]
#[doc = "assert_eq!(0_u128.saturating_pow(0), 1);"]
#[doc = "assert_eq!(u128::MAX.saturating_pow(2), u128::MAX);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) { Some(x) => x, None => Self::MAX, }
}
/// Wrapping (modular) addition. Computes `self + rhs`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(200u128.wrapping_add(55), 255);"]
#[doc = "assert_eq!(200u128.wrapping_add(u128::MAX), 199);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_add(self, rhs: Self) -> Self {
intrinsics::wrapping_add(self, rhs)
}
/// Wrapping (modular) addition with a signed integer. Computes
/// `self + rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u128.wrapping_add_signed(2), 3);"]
#[doc = "assert_eq!(1u128.wrapping_add_signed(-2), u128::MAX);"]
#[doc = "assert_eq!((u128::MAX - 2).wrapping_add_signed(4), 1);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_add_signed(self, rhs: i128) -> Self {
self.wrapping_add(rhs as Self)
}
/// Wrapping (modular) subtraction. Computes `self - rhs`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u128.wrapping_sub(100), 0);"]
#[doc = "assert_eq!(100u128.wrapping_sub(u128::MAX), 101);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_sub(self, rhs: Self) -> Self {
intrinsics::wrapping_sub(self, rhs)
}
/// Wrapping (modular) subtraction with a signed integer. Computes
/// `self - rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u128.wrapping_sub_signed(2), u128::MAX);"]
#[doc = "assert_eq!(1u128.wrapping_sub_signed(-2), 3);"]
#[doc = "assert_eq!((u128::MAX - 2).wrapping_sub_signed(-4), 1);"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_sub_signed(self, rhs: i128) -> Self {
self.wrapping_sub(rhs as Self)
}
/// Wrapping (modular) multiplication. Computes `self *
/// rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `u8` is used.
///
/// ```
/// assert_eq!(10u8.wrapping_mul(12), 120);
/// assert_eq!(25u8.wrapping_mul(12), 44);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_mul(self, rhs: Self) -> Self {
intrinsics::wrapping_mul(self, rhs)
}
/// Wrapping (modular) division. Computes `self / rhs`.
///
/// Wrapped division on unsigned types is just normal division. There's
/// no way wrapping could ever happen. This function exists so that all
/// operations are accounted for in the wrapping operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u128.wrapping_div(10), 10);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn wrapping_div(self, rhs: Self) -> Self { self / rhs }
/// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
///
/// Wrapped division on unsigned types is just normal division. There's
/// no way wrapping could ever happen. This function exists so that all
/// operations are accounted for in the wrapping operations. Since, for
/// the positive integers, all common definitions of division are equal,
/// this is exactly equal to `self.wrapping_div(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u128.wrapping_div_euclid(10), 10);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn wrapping_div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Wrapping (modular) remainder. Computes `self % rhs`.
///
/// Wrapped remainder calculation on unsigned types is just the regular
/// remainder calculation. There's no way wrapping could ever happen.
/// This function exists so that all operations are accounted for in the
/// wrapping operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u128.wrapping_rem(10), 0);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn wrapping_rem(self, rhs: Self) -> Self { self % rhs }
/// Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
///
/// Wrapped modulo calculation on unsigned types is just the regular
/// remainder calculation. There's no way wrapping could ever happen.
/// This function exists so that all operations are accounted for in the
/// wrapping operations. Since, for the positive integers, all common
/// definitions of division are equal, this is exactly equal to
/// `self.wrapping_rem(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u128.wrapping_rem_euclid(10), 0);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Wrapping (modular) negation. Computes `-self`,
/// wrapping around at the boundary of the type.
///
/// Since unsigned types do not have negative equivalents
/// all applications of this function will wrap (except for `-0`).
/// For values smaller than the corresponding signed type's maximum
/// the result is the same as casting the corresponding signed value.
/// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
/// `MAX` is the corresponding signed type's maximum.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0_u128.wrapping_neg(), 0);"]
#[doc = "assert_eq!(u128::MAX.wrapping_neg(), 1);"]
#[doc = "assert_eq!(13_u128.wrapping_neg(), (!13) + 1);"]
#[doc = "assert_eq!(42_u128.wrapping_neg(), !(42 - 1));"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_neg(self) -> Self { (0 as u128).wrapping_sub(self) }
/// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
/// where `mask` removes any high-order bits of `rhs` that
/// would cause the shift to exceed the bitwidth of the type.
///
/// Beware that, unlike most other `wrapping_*` methods on integers, this
/// does *not* give the same result as doing the shift in infinite precision
/// then truncating as needed. Instead, the behaviour of this method matches what shift instructions
/// do on many processors, and is what the `<<` operator does when overflow
/// checks are disabled, but numerically it's weird. Consider, instead,
/// using [`Self::unbounded_shl`] which has nicer behaviour.
///
/// Note that this is *not* the same as a rotate-left; the
/// RHS of a wrapping shift-left is restricted to the range
/// of the type, rather than the bits shifted out of the LHS
/// being returned to the other end. The primitive integer
/// types all implement a [`rotate_left`](Self::rotate_left) function,
/// which may be what you want instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1_u128.wrapping_shl(7), 128);"]
#[doc = "assert_eq!(0b101_u128.wrapping_shl(0), 0b101);"]
#[doc = "assert_eq!(0b101_u128.wrapping_shl(1), 0b1010);"]
#[doc = "assert_eq!(0b101_u128.wrapping_shl(2), 0b10100);"]
#[doc = "assert_eq!(u128::MAX.wrapping_shl(2), u128::MAX - 3);"]
#[doc = "assert_eq!(42_u128.wrapping_shl(128), 42);"]
#[doc = "assert_eq!(42_u128.wrapping_shl(1).wrapping_shl(127), 0);"]
#[doc = "assert_eq!(1_u128.wrapping_shl(128), 1);"]
#[doc = "assert_eq!(5_u128.wrapping_shl(1025), 10);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_shl(self, rhs: u32) -> Self {
unsafe { self.unchecked_shl(rhs & (Self::BITS - 1)) }
}
/// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
/// where `mask` removes any high-order bits of `rhs` that
/// would cause the shift to exceed the bitwidth of the type.
///
/// Beware that, unlike most other `wrapping_*` methods on integers, this
/// does *not* give the same result as doing the shift in infinite precision
/// then truncating as needed. Instead, the behaviour of this method matches what shift instructions
/// do on many processors, and is what the `>>` operator does when overflow
/// checks are disabled, but numerically it's weird. Consider, instead,
/// using [`Self::unbounded_shr`] which has nicer behaviour.
///
/// Note that this is *not* the same as a rotate-right; the
/// RHS of a wrapping shift-right is restricted to the range
/// of the type, rather than the bits shifted out of the LHS
/// being returned to the other end. The primitive integer
/// types all implement a [`rotate_right`](Self::rotate_right) function,
/// which may be what you want instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128_u128.wrapping_shr(7), 1);"]
#[doc = "assert_eq!(0b1010_u128.wrapping_shr(0), 0b1010);"]
#[doc = "assert_eq!(0b1010_u128.wrapping_shr(1), 0b101);"]
#[doc = "assert_eq!(0b1010_u128.wrapping_shr(2), 0b10);"]
#[doc = "assert_eq!(u128::MAX.wrapping_shr(1), i128::MAX.cast_unsigned());"]
#[doc = "assert_eq!(42_u128.wrapping_shr(128), 42);"]
#[doc = "assert_eq!(42_u128.wrapping_shr(1).wrapping_shr(127), 0);"]
#[doc = "assert_eq!(128_u128.wrapping_shr(128), 128);"]
#[doc = "assert_eq!(10_u128.wrapping_shr(1025), 5);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_shr(self, rhs: u32) -> Self {
unsafe { self.unchecked_shr(rhs & (Self::BITS - 1)) }
}
/// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3u128.wrapping_pow(5), 243);"]
/// assert_eq!(3u8.wrapping_pow(6), 217);
#[doc = "assert_eq!(0_u128.wrapping_pow(0), 1);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_pow(self, exp: u32) -> Self {
let (a, _) = self.overflowing_pow(exp);
a
}
/// Calculates `self` + `rhs`.
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u128.overflowing_add(2), (7, false));"]
#[doc = "assert_eq!(u128::MAX.overflowing_add(1), (0, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::add_with_overflow(self as u128, rhs as u128);
(a as Self, b)
}
/// Calculates `self` + `rhs` + `carry` and returns a tuple containing
/// the sum and the output carry (in that order).
///
/// Performs "ternary addition" of two integer operands and a carry-in
/// bit, and returns an output integer and a carry-out bit. This allows
/// chaining together multiple additions to create a wider addition, and
/// can be useful for bignum addition.
///
#[doc =
"This can be thought of as a 128-bit \"full adder\", in the electronics sense."]
///
/// If the input carry is false, this method is equivalent to
/// [`overflowing_add`](Self::overflowing_add), and the output carry is
/// equal to the overflow flag. Note that although carry and overflow
/// flags are similar for unsigned integers, they are different for
/// signed integers.
///
/// # Examples
///
/// ```
#[doc = "// 3 MAX (a = 3 \u{d7} 2^128 + 2^128 - 1)"]
#[doc = "// + 5 7 (b = 5 \u{d7} 2^128 + 7)"]
/// // ---------
#[doc = "// 9 6 (sum = 9 \u{d7} 2^128 + 6)"]
///
#[doc = "let (a1, a0): (u128, u128) = (3, u128::MAX);"]
#[doc = "let (b1, b0): (u128, u128) = (5, 7);"]
/// let carry0 = false;
///
/// let (sum0, carry1) = a0.carrying_add(b0, carry0);
/// assert_eq!(carry1, true);
/// let (sum1, carry2) = a1.carrying_add(b1, carry1);
/// assert_eq!(carry2, false);
///
/// assert_eq!((sum1, sum0), (9, 6));
/// ```
#[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
#[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue =
"152015")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
let (a, c1) = self.overflowing_add(rhs);
let (b, c2) = a.overflowing_add(carry as u128);
(b, unsafe { intrinsics::disjoint_bitor(c1, c2) })
}
/// Calculates `self` + `rhs` with a signed `rhs`.
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u128.overflowing_add_signed(2), (3, false));"]
#[doc = "assert_eq!(1u128.overflowing_add_signed(-2), (u128::MAX, true));"]
#[doc = "assert_eq!((u128::MAX - 2).overflowing_add_signed(4), (1, true));"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_add_signed(self, rhs: i128) -> (Self, bool) {
let (res, overflowed) = self.overflowing_add(rhs as Self);
(res, overflowed ^ (rhs < 0))
}
/// Calculates `self` - `rhs`.
///
/// Returns a tuple of the subtraction along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u128.overflowing_sub(2), (3, false));"]
#[doc = "assert_eq!(0u128.overflowing_sub(1), (u128::MAX, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::sub_with_overflow(self as u128, rhs as u128);
(a as Self, b)
}
/// Calculates `self` − `rhs` − `borrow` and returns a tuple
/// containing the difference and the output borrow.
///
/// Performs "ternary subtraction" by subtracting both an integer
/// operand and a borrow-in bit from `self`, and returns an output
/// integer and a borrow-out bit. This allows chaining together multiple
/// subtractions to create a wider subtraction, and can be useful for
/// bignum subtraction.
///
/// # Examples
///
/// ```
#[doc = "// 9 6 (a = 9 \u{d7} 2^128 + 6)"]
#[doc = "// - 5 7 (b = 5 \u{d7} 2^128 + 7)"]
/// // ---------
#[doc = "// 3 MAX (diff = 3 \u{d7} 2^128 + 2^128 - 1)"]
///
#[doc = "let (a1, a0): (u128, u128) = (9, 6);"]
#[doc = "let (b1, b0): (u128, u128) = (5, 7);"]
/// let borrow0 = false;
///
/// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);
/// assert_eq!(borrow1, true);
/// let (diff1, borrow2) = a1.borrowing_sub(b1, borrow1);
/// assert_eq!(borrow2, false);
///
#[doc = "assert_eq!((diff1, diff0), (3, u128::MAX));"]
/// ```
#[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
#[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue =
"152015")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
let (a, c1) = self.overflowing_sub(rhs);
let (b, c2) = a.overflowing_sub(borrow as u128);
(b, unsafe { intrinsics::disjoint_bitor(c1, c2) })
}
/// Calculates `self` - `rhs` with a signed `rhs`
///
/// Returns a tuple of the subtraction along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u128.overflowing_sub_signed(2), (u128::MAX, true));"]
#[doc = "assert_eq!(1u128.overflowing_sub_signed(-2), (3, false));"]
#[doc = "assert_eq!((u128::MAX - 2).overflowing_sub_signed(-4), (1, true));"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_sub_signed(self, rhs: i128) -> (Self, bool) {
let (res, overflow) = self.overflowing_sub(rhs as Self);
(res, overflow ^ (rhs < 0))
}
/// Computes the absolute difference between `self` and `other`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u128.abs_diff(80), 20u128);"]
#[doc = "assert_eq!(100u128.abs_diff(110), 10u128);"]
/// ```
#[stable(feature = "int_abs_diff", since = "1.60.0")]
#[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn abs_diff(self, other: Self) -> Self {
if size_of::<Self>() == 1 {
(self as i32).wrapping_sub(other as i32).unsigned_abs() as Self
} else { if self < other { other - self } else { self - other } }
}
/// Calculates the multiplication of `self` and `rhs`.
///
/// Returns a tuple of the multiplication along with a boolean
/// indicating whether an arithmetic overflow would occur. If an
/// overflow would have occurred then the wrapped value is returned.
///
/// If you want the *value* of the overflow, rather than just *whether*
/// an overflow occurred, see [`Self::carrying_mul`].
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `u32` is used.
///
/// ```
/// assert_eq!(5u32.overflowing_mul(2), (10, false));
/// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::mul_with_overflow(self as u128, rhs as u128);
(a as Self, b)
}
/// Calculates the "full multiplication" `self * rhs + carry`
/// without the possibility to overflow.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// Performs "long multiplication" which takes in an extra amount to add, and may return an
/// additional amount of overflow. This allows for chaining together multiple
/// multiplications to create "big integers" which represent larger values.
///
/// If you also need to add a value, then use [`Self::carrying_mul_add`].
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `u32` is used.
///
/// ```
/// assert_eq!(5u32.carrying_mul(2, 0), (10, 0));
/// assert_eq!(5u32.carrying_mul(2, 10), (20, 0));
/// assert_eq!(1_000_000_000u32.carrying_mul(10, 0), (1410065408, 2));
/// assert_eq!(1_000_000_000u32.carrying_mul(10, 10), (1410065418, 2));
#[doc =
"assert_eq!(u128::MAX.carrying_mul(u128::MAX, u128::MAX), (0, u128::MAX));"]
/// ```
///
/// This is the core operation needed for scalar multiplication when
/// implementing it for wider-than-native types.
///
/// ```
/// fn scalar_mul_eq(little_endian_digits: &mut Vec<u16>, multiplicand: u16) {
/// let mut carry = 0;
/// for d in little_endian_digits.iter_mut() {
/// (*d, carry) = d.carrying_mul(multiplicand, carry);
/// }
/// if carry != 0 {
/// little_endian_digits.push(carry);
/// }
/// }
///
/// let mut v = vec![10, 20];
/// scalar_mul_eq(&mut v, 3);
/// assert_eq!(v, [30, 60]);
///
/// assert_eq!(0x87654321_u64 * 0xFEED, 0x86D3D159E38D);
/// let mut v = vec![0x4321, 0x8765];
/// scalar_mul_eq(&mut v, 0xFEED);
/// assert_eq!(v, [0xE38D, 0xD159, 0x86D3]);
/// ```
///
/// If `carry` is zero, this is similar to [`overflowing_mul`](Self::overflowing_mul),
/// except that it gives the value of the overflow instead of just whether one happened:
///
/// ```
/// # #![allow(unused_features)]
/// #![feature(const_unsigned_bigint_helpers)]
/// let r = u8::carrying_mul(7, 13, 0);
/// assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(7, 13));
/// let r = u8::carrying_mul(13, 42, 0);
/// assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(13, 42));
/// ```
///
/// The value of the first field in the returned tuple matches what you'd get
/// by combining the [`wrapping_mul`](Self::wrapping_mul) and
/// [`wrapping_add`](Self::wrapping_add) methods:
///
/// ```
/// # #![allow(unused_features)]
/// #![feature(const_unsigned_bigint_helpers)]
/// assert_eq!(
/// 789_u16.carrying_mul(456, 123).0,
/// 789_u16.wrapping_mul(456).wrapping_add(123),
/// );
/// ```
#[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
#[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue =
"152015")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_mul(self, rhs: Self, carry: Self) -> (Self, Self) {
Self::carrying_mul_add(self, rhs, carry, 0)
}
/// Calculates the "full multiplication" `self * rhs + carry + add`.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// This cannot overflow, as the double-width result has exactly enough
/// space for the largest possible result. This is equivalent to how, in
/// decimal, 9 × 9 + 9 + 9 = 81 + 18 = 99 = 9×10⁰ + 9×10¹ = 10² - 1.
///
/// Performs "long multiplication" which takes in an extra amount to add, and may return an
/// additional amount of overflow. This allows for chaining together multiple
/// multiplications to create "big integers" which represent larger values.
///
/// If you don't need the `add` part, then you can use [`Self::carrying_mul`] instead.
///
/// # Examples
///
/// Please note that this example is shared between integer types,
/// which explains why `u32` is used here.
///
/// ```
/// assert_eq!(5u32.carrying_mul_add(2, 0, 0), (10, 0));
/// assert_eq!(5u32.carrying_mul_add(2, 10, 10), (30, 0));
/// assert_eq!(1_000_000_000u32.carrying_mul_add(10, 0, 0), (1410065408, 2));
/// assert_eq!(1_000_000_000u32.carrying_mul_add(10, 10, 10), (1410065428, 2));
#[doc =
"assert_eq!(u128::MAX.carrying_mul_add(u128::MAX, u128::MAX, u128::MAX), (u128::MAX, u128::MAX));"]
/// ```
///
/// This is the core per-digit operation for "grade school" O(n²) multiplication.
///
/// Please note that this example is shared between integer types,
/// using `u8` for simplicity of the demonstration.
///
/// ```
/// fn quadratic_mul<const N: usize>(a: [u8; N], b: [u8; N]) -> [u8; N] {
/// let mut out = [0; N];
/// for j in 0..N {
/// let mut carry = 0;
/// for i in 0..(N - j) {
/// (out[j + i], carry) = u8::carrying_mul_add(a[i], b[j], out[j + i], carry);
/// }
/// }
/// out
/// }
///
/// // -1 * -1 == 1
/// assert_eq!(quadratic_mul([0xFF; 3], [0xFF; 3]), [1, 0, 0]);
///
/// assert_eq!(u32::wrapping_mul(0x9e3779b9, 0x7f4a7c15), 0xcffc982d);
/// assert_eq!(
/// quadratic_mul(u32::to_le_bytes(0x9e3779b9), u32::to_le_bytes(0x7f4a7c15)),
/// u32::to_le_bytes(0xcffc982d)
/// );
/// ```
#[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
#[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue =
"152015")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_mul_add(self, rhs: Self, carry: Self, add: Self)
-> (Self, Self) {
intrinsics::carrying_mul_add(self, rhs, carry, add)
}
/// Calculates the divisor when `self` is divided by `rhs`.
///
/// Returns a tuple of the divisor along with a boolean indicating
/// whether an arithmetic overflow would occur. Note that for unsigned
/// integers overflow never occurs, so the second value is always
/// `false`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u128.overflowing_div(2), (2, false));"]
/// ```
#[inline(always)]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_overflowing_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[track_caller]
pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
(self / rhs, false)
}
/// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
///
/// Returns a tuple of the divisor along with a boolean indicating
/// whether an arithmetic overflow would occur. Note that for unsigned
/// integers overflow never occurs, so the second value is always
/// `false`.
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self.overflowing_div(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u128.overflowing_div_euclid(2), (2, false));"]
/// ```
#[inline(always)]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[track_caller]
pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
(self / rhs, false)
}
/// Calculates the remainder when `self` is divided by `rhs`.
///
/// Returns a tuple of the remainder after dividing along with a boolean
/// indicating whether an arithmetic overflow would occur. Note that for
/// unsigned integers overflow never occurs, so the second value is
/// always `false`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u128.overflowing_rem(2), (1, false));"]
/// ```
#[inline(always)]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_overflowing_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[track_caller]
pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
(self % rhs, false)
}
/// Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
///
/// Returns a tuple of the modulo after dividing along with a boolean
/// indicating whether an arithmetic overflow would occur. Note that for
/// unsigned integers overflow never occurs, so the second value is
/// always `false`.
/// Since, for the positive integers, all common
/// definitions of division are equal, this operation
/// is exactly equal to `self.overflowing_rem(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u128.overflowing_rem_euclid(2), (1, false));"]
/// ```
#[inline(always)]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[track_caller]
pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
(self % rhs, false)
}
/// Negates self in an overflowing fashion.
///
/// Returns `!self + 1` using wrapping operations to return the value
/// that represents the negation of this unsigned value. Note that for
/// positive unsigned values overflow always occurs, but negating 0 does
/// not overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0u128.overflowing_neg(), (0, false));"]
#[doc = "assert_eq!(2u128.overflowing_neg(), (-2i32 as u128, true));"]
/// ```
#[inline(always)]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn overflowing_neg(self) -> (Self, bool) {
((!self).wrapping_add(1), self != 0)
}
/// Shifts self left by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean
/// indicating whether the shift value was larger than or equal to the
/// number of bits. If the shift value is too large, then value is
/// masked (N-1) where N is the number of bits, and this value is then
/// used to perform the shift.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1u128.overflowing_shl(4), (0x10, false));"]
#[doc = "assert_eq!(0x1u128.overflowing_shl(132), (0x10, true));"]
#[doc = "assert_eq!(0x10u128.overflowing_shl(127), (0, false));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shl(rhs), rhs >= Self::BITS)
}
/// Shifts self right by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean
/// indicating whether the shift value was larger than or equal to the
/// number of bits. If the shift value is too large, then value is
/// masked (N-1) where N is the number of bits, and this value is then
/// used to perform the shift.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10u128.overflowing_shr(4), (0x1, false));"]
#[doc = "assert_eq!(0x10u128.overflowing_shr(132), (0x1, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shr(rhs), rhs >= Self::BITS)
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// Returns a tuple of the exponentiation along with a bool indicating
/// whether an overflow happened.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3u128.overflowing_pow(5), (243, false));"]
#[doc = "assert_eq!(0_u128.overflowing_pow(0), (1, false));"]
/// assert_eq!(3u8.overflowing_pow(6), (217, true));
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
let mut base = self;
let mut acc: Self = 1;
let mut overflow = false;
let mut tmp_overflow;
if intrinsics::is_val_statically_known(base) && base.is_power_of_two() {
let k = base.ilog2();
let Some(shift) = k.checked_mul(exp) else { return (0, true) };
return ((1 as Self).unbounded_shl(shift), shift >= Self::BITS)
}
if exp == 0 { return (1, false); }
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 {
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
}
exp /= 2;
(base, tmp_overflow) = base.overflowing_mul(base);
overflow |= tmp_overflow;
}
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
return (acc, overflow);
}
loop {
if (exp & 1) == 1 {
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
if exp == 1 { return (acc, overflow); }
}
exp /= 2;
(base, tmp_overflow) = base.overflowing_mul(base);
overflow |= tmp_overflow;
}
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u128.pow(5), 32);"]
#[doc = "assert_eq!(0_u128.pow(0), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn pow(self, exp: u32) -> Self {
if intrinsics::overflow_checks() {
self.strict_pow(exp)
} else { self.wrapping_pow(exp) }
}
/// Returns the square root of the number, rounded down.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10u128.isqrt(), 3);"]
/// ```
#[stable(feature = "isqrt", since = "1.84.0")]
#[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn isqrt(self) -> Self {
let result = imp::int_sqrt::u128(self as u128) as Self;
unsafe {
const MAX_RESULT: u128 = imp::int_sqrt::u128(<u128>::MAX) as u128;
crate::hint::assert_unchecked(result <= MAX_RESULT)
}
if self >= 1 { unsafe { crate::hint::assert_unchecked(result >= 1) } }
unsafe {
crate::hint::assert_unchecked(result.unchecked_mul(result) <= self);
crate::hint::assert_unchecked(result <= self);
}
result
}
/// Performs Euclidean division.
///
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self / rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7u128.div_euclid(4), 1); // or any other integer type"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Calculates the least remainder of `self` when divided by
/// `rhs`.
///
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self % rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7u128.rem_euclid(4), 3); // or any other integer type"]
/// ```
#[doc(alias = "modulo", alias = "mod")]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
///
/// This is the same as performing `self / rhs` for all unsigned integers.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "assert_eq!(7_u128.div_floor(4), 1);"]
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn div_floor(self, rhs: Self) -> Self { self / rhs }
/// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7_u128.div_ceil(4), 2);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_ceil(self, rhs: Self) -> Self {
let d = self / rhs;
let r = self % rhs;
if r > 0 { d + 1 } else { d }
}
/// Calculates the smallest value greater than or equal to `self` that
/// is a multiple of `rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// On overflow, this function will panic if overflow checks are enabled (default in debug
/// mode) and wrap if overflow checks are disabled (default in release mode).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(16_u128.next_multiple_of(8), 16);"]
#[doc = "assert_eq!(23_u128.next_multiple_of(8), 24);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_multiple_of(self, rhs: Self) -> Self {
match self % rhs { 0 => self, r => self + (rhs - r), }
}
/// Calculates the smallest value greater than or equal to `self` that
/// is a multiple of `rhs`. Returns `None` if `rhs` is zero or the
/// operation would result in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(16_u128.checked_next_multiple_of(8), Some(16));"]
#[doc = "assert_eq!(23_u128.checked_next_multiple_of(8), Some(24));"]
#[doc = "assert_eq!(1_u128.checked_next_multiple_of(0), None);"]
#[doc = "assert_eq!(u128::MAX.checked_next_multiple_of(2), None);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
match match self.checked_rem(rhs) { Some(x) => x, None => return None, } {
0 => Some(self),
r => self.checked_add(rhs - r),
}
}
/// Returns `true` if `self` is an integer multiple of `rhs`, and false otherwise.
///
/// This function is equivalent to `self % rhs == 0`, except that it will not panic
/// for `rhs == 0`. Instead, `0.is_multiple_of(0) == true`, and for any non-zero `n`,
/// `n.is_multiple_of(0) == false`.
///
/// # Examples
///
/// ```
#[doc = "assert!(6_u128.is_multiple_of(2));"]
#[doc = "assert!(!5_u128.is_multiple_of(2));"]
///
#[doc = "assert!(0_u128.is_multiple_of(0));"]
#[doc = "assert!(!6_u128.is_multiple_of(0));"]
/// ```
#[stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
#[rustc_const_stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
#[must_use]
#[inline]
pub const fn is_multiple_of(self, rhs: Self) -> bool {
match rhs { 0 => self == 0, _ => self % rhs == 0, }
}
/// Returns `true` if and only if `self == 2^k` for some unsigned integer `k`.
///
/// # Examples
///
/// ```
#[doc = "assert!(16u128.is_power_of_two());"]
#[doc = "assert!(!10u128.is_power_of_two());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
#[inline(always)]
pub const fn is_power_of_two(self) -> bool { self.count_ones() == 1 }
#[inline]
const fn one_less_than_next_power_of_two(self) -> Self {
if self <= 1 { return 0; }
let p = self - 1;
let z = unsafe { intrinsics::ctlz_nonzero(p) };
<u128>::MAX >> z
}
/// Returns the smallest power of two greater than or equal to `self`.
///
/// When return value overflows (i.e., `self > (1 << (N-1))` for type
/// `uN`), it panics in debug mode and the return value is wrapped to 0 in
/// release mode (the only situation in which this method can return 0).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u128.next_power_of_two(), 2);"]
#[doc = "assert_eq!(3u128.next_power_of_two(), 4);"]
#[doc = "assert_eq!(0u128.next_power_of_two(), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_power_of_two(self) -> Self {
self.one_less_than_next_power_of_two() + 1
}
/// Returns the smallest power of two greater than or equal to `self`. If
/// the next power of two is greater than the type's maximum value,
/// `None` is returned, otherwise the power of two is wrapped in `Some`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u128.checked_next_power_of_two(), Some(2));"]
#[doc = "assert_eq!(3u128.checked_next_power_of_two(), Some(4));"]
#[doc = "assert_eq!(u128::MAX.checked_next_power_of_two(), None);"]
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn checked_next_power_of_two(self) -> Option<Self> {
self.one_less_than_next_power_of_two().checked_add(1)
}
/// Returns the smallest power of two greater than or equal to `n`. If
/// the next power of two is greater than the type's maximum value,
/// the return value is wrapped to `0`.
///
/// # Examples
///
/// ```
/// #![feature(wrapping_next_power_of_two)]
///
#[doc = "assert_eq!(2u128.wrapping_next_power_of_two(), 2);"]
#[doc = "assert_eq!(3u128.wrapping_next_power_of_two(), 4);"]
#[doc = "assert_eq!(u128::MAX.wrapping_next_power_of_two(), 0);"]
/// ```
#[inline]
#[unstable(feature = "wrapping_next_power_of_two", issue = "32463", reason =
"needs decision on wrapping behavior")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn wrapping_next_power_of_two(self) -> Self {
self.one_less_than_next_power_of_two().wrapping_add(1)
}
/// Returns the memory representation of this integer as a byte array in
/// big-endian (network) byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12345678901234567890123456789012u128.to_be_bytes();"]
#[doc =
"assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
self.to_be().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// little-endian byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12345678901234567890123456789012u128.to_le_bytes();"]
#[doc =
"assert_eq!(bytes, [0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
self.to_le().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code
/// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
/// instead.
///
#[doc = ""]
///
/// [`to_be_bytes`]: Self::to_be_bytes
/// [`to_le_bytes`]: Self::to_le_bytes
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12345678901234567890123456789012u128.to_ne_bytes();"]
/// assert_eq!(
/// bytes,
/// if cfg!(target_endian = "big") {
#[doc =
" [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]"]
/// } else {
#[doc =
" [0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]"]
/// }
/// );
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[allow(unnecessary_transmutes)]
#[inline]
pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
unsafe { mem::transmute(self) }
}
/// Creates a native endian integer value from its representation
/// as a byte array in big endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc =
"let value = u128::from_be_bytes([0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]);"]
#[doc = "assert_eq!(value, 0x12345678901234567890123456789012);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_be_u128(input: &mut &[u8]) -> u128 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u128>());"]
/// *input = rest;
#[doc = " u128::from_be_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_be(Self::from_ne_bytes(bytes))
}
/// Creates a native endian integer value from its representation
/// as a byte array in little endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc =
"let value = u128::from_le_bytes([0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);"]
#[doc = "assert_eq!(value, 0x12345678901234567890123456789012);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_le_u128(input: &mut &[u8]) -> u128 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u128>());"]
/// *input = rest;
#[doc = " u128::from_le_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_le(Self::from_ne_bytes(bytes))
}
/// Creates a native endian integer value from its memory representation
/// as a byte array in native endianness.
///
/// As the target platform's native endianness is used, portable code
/// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
/// appropriate instead.
///
/// [`from_be_bytes`]: Self::from_be_bytes
/// [`from_le_bytes`]: Self::from_le_bytes
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = u128::from_ne_bytes(if cfg!(target_endian = \"big\") {"]
#[doc =
" [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]"]
/// } else {
#[doc =
" [0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]"]
/// });
#[doc = "assert_eq!(value, 0x12345678901234567890123456789012);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_ne_u128(input: &mut &[u8]) -> u128 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u128>());"]
/// *input = rest;
#[doc = " u128::from_ne_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use]
#[inline]
pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
unsafe { mem::transmute(bytes) }
}
/// New code should prefer to use
#[doc = "[`u128::MIN`] instead."]
///
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_promotable]
#[inline(always)]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MIN` associated constant on this type")]
#[rustc_diagnostic_item = "u128_legacy_fn_min_value"]
pub const fn min_value() -> Self { Self::MIN }
/// New code should prefer to use
#[doc = "[`u128::MAX`] instead."]
///
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_promotable]
#[inline(always)]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MAX` associated constant on this type")]
#[rustc_diagnostic_item = "u128_legacy_fn_max_value"]
pub const fn max_value() -> Self { Self::MAX }
/// Truncate an integer to an integer of the same size or smaller, preserving the least
/// significant bits.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u8, 120u128.truncate());"]
/// assert_eq!(120u8, 376u32.truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
/// instead of truncating.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u8, 120u128.saturating_truncate());"]
/// assert_eq!(255u8, 376u32.saturating_truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn saturating_truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_saturating_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
/// is outside the bounds of the smaller type.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(Some(120u8), 120u128.checked_truncate());"]
/// assert_eq!(None, 376u32.checked_truncate::<u8>());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn checked_truncate<Target>(self) -> Option<Target> where
Self: [const] traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_checked_truncate(self)
}
/// Widen to an integer of the same size or larger, preserving its value.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u128, 120u8.widen());"]
/// ```
#[must_use =
"this returns the widened value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn widen<Target>(self) -> Target where Self: [const]
traits::WidenTarget<Target> {
traits::WidenTarget::internal_widen(self)
}
/// Converts `self` to the target integer type, saturating at the numeric
/// bounds instead of overflowing.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(255u8, u128::MAX.saturating_cast());"]
#[doc = "assert_eq!(127i8, u128::MAX.saturating_cast());"]
#[doc = "assert_eq!(42i8, 42u128.saturating_cast());"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn saturating_cast<T: [const] BoundedCastFromInt<Self>>(self) -> T {
T::saturating_cast_from(self)
}
/// Converts `self` to the target integer type, wrapping around at the
/// boundary of the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(255u8, u128::MAX.wrapping_cast());"]
#[doc = "assert_eq!(42i8, 42u128.wrapping_cast());"]
#[doc = "assert_eq!(u128::MAX as i8, u128::MAX.wrapping_cast());"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn wrapping_cast<T: [const] BoundedCastFromInt<Self>>(self) -> T {
T::wrapping_cast_from(self)
}
/// Converts `self` to the target integer type, returning `None` if the value
/// is not representable by the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(Some(42u8), 42u128.checked_cast());"]
#[doc = "assert_eq!(128u128.checked_cast::<i8>(), None);"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn checked_cast<T: [const] CheckedCastFromInt<Self>>(self)
-> Option<T> {
T::checked_cast_from(self)
}
/// Converts `self` to the target integer type, panicking if the value
/// is not representable by the target type.
///
/// # Panics
///
/// This function will panic if the value is not representable by the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(42u8, 42u128.strict_cast());"]
/// ```
///
/// The following will panic:
///
/// ```should_panic
/// #![feature(integer_casts)]
#[doc = "let _ = 128u128.strict_cast::<i8>();"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
#[track_caller]
pub const fn strict_cast<T: [const] CheckedCastFromInt<Self>>(self) -> T {
T::strict_cast_from(self)
}
/// Converts `self` to the target integer type, assuming the value is
/// representable by the target type.
///
/// # Safety
///
/// This results in undefined behavior if the integer value of `self` is bigger than `T::MAX`,
/// or smaller than `T::MIN`, where `T` is the target type.
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const unsafe fn unchecked_cast<T: [const] CheckedCastFromInt<Self>>(self)
-> T {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(in_bounds: bool) {
if !in_bounds {
let msg =
"unsafe precondition(s) violated: u128::unchecked_cast must fit in the target type\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check({
let cast_val = self.checked_cast::<T>();
let ret = cast_val.is_some();
core::mem::forget(cast_val);
ret
});
}
};
unsafe { T::unchecked_cast_from(self) }
}uint_impl! {
1352Self = u128,
1353 ActualT = u128,
1354 SignedT = i128,
1355 BITS = 128,
1356 BITS_MINUS_ONE = 127,
1357 MAX = 340282366920938463463374607431768211455,
1358 rot = 16,
1359 rot_op = "0x13f40000000000000000000000004f76",
1360 rot_result = "0x4f7613f4",
1361 fsh_op = "0x2fe78e45983acd98039000008736273",
1362 fshl_result = "0x4f7602fe",
1363 fshr_result = "0x4f7602fe78e45983acd9803900000873",
1364 clmul_lhs = "0x12345678901234567890123456789012",
1365 clmul_rhs = "0x4317e40ab4ddcf05dd358416f52ecd34",
1366 clmul_result = "0xb9cf660de35d0c170a6299579b980928",
1367 swap_op = "0x12345678901234567890123456789012",
1368 swapped = "0x12907856341290785634129078563412",
1369 reversed = "0x48091e6a2c48091e6a2c48091e6a2c48",
1370 le_bytes = "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
1371 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
1372 be_bytes = "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
1373 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
1374 to_xe_bytes_doc = "",
1375 from_xe_bytes_doc = "",
1376 bound_condition = "",
1377 }1378/// Calculates the midpoint (average) between `self` and `rhs`.
///
/// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
/// sufficiently-large unsigned integral type. This implies that the result is
/// always rounded towards zero and that no overflow will ever occur.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0u128.midpoint(4), 2);"]
#[doc = "assert_eq!(1u128.midpoint(4), 2);"]
/// ```
#[stable(feature = "num_midpoint", since = "1.85.0")]
#[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[doc(alias = "average_floor")]
#[doc(alias = "average")]
#[inline]
pub const fn midpoint(self, rhs: u128) -> u128 {
((self ^ rhs) >> 1) + (self & rhs)
}midpoint_impl! { u128, unsigned }1379/// Calculates the "full carryless multiplication" without the possibility to overflow.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `u8` is used.
///
/// ```
/// #![feature(uint_carryless_mul)]
///
/// assert_eq!(0b1000_0000u8.carrying_carryless_mul(0b1000_0000, 0b0000), (0, 0b0100_0000));
/// assert_eq!(0b1000_0000u8.carrying_carryless_mul(0b1000_0000, 0b1111), (0b1111, 0b0100_0000));
#[doc =
"assert_eq!(u128::MAX.carrying_carryless_mul(u128::MAX, u128::MAX), (!(u128::MAX / 3), u128::MAX / 3));"]
/// ```
#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
#[doc(alias = "clmul")]
#[unstable(feature = "uint_carryless_mul", issue = "152080")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_carryless_mul(self, rhs: Self, carry: Self)
-> (Self, Self) {
let x0 = self as u64;
let x1 = (self >> 64) as u64;
let y0 = rhs as u64;
let y1 = (rhs >> 64) as u64;
let z0 = u64::widening_carryless_mul(x0, y0);
let z2 = u64::widening_carryless_mul(x1, y1);
let z3 = u64::widening_carryless_mul(x0 ^ x1, y0 ^ y1);
let z1 = z3 ^ z0 ^ z2;
let lo = z0 ^ (z1 << 64);
let hi = z2 ^ (z1 >> 64);
(lo ^ carry, hi)
}carrying_carryless_mul_impl! { u128, u256 }1380}
13811382#[doc(auto_cfg = false)]
1383#[cfg(target_pointer_width = "16")]
1384impl usize {
1385uint_impl! {
1386Self = usize,
1387 ActualT = u16,
1388 SignedT = isize,
1389 BITS = 16,
1390 BITS_MINUS_ONE = 15,
1391 MAX = 65535,
1392 rot = 4,
1393 rot_op = "0xa003",
1394 rot_result = "0x3a",
1395 fsh_op = "0x2de",
1396 fshl_result = "0x30",
1397 fshr_result = "0x302d",
1398 clmul_lhs = "0x9012",
1399 clmul_rhs = "0xcd34",
1400 clmul_result = "0x928",
1401 swap_op = "0x1234",
1402 swapped = "0x3412",
1403 reversed = "0x2c48",
1404 le_bytes = "[0x34, 0x12]",
1405 be_bytes = "[0x12, 0x34]",
1406 to_xe_bytes_doc = usize_isize_to_xe_bytes_doc!(),
1407 from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(),
1408 bound_condition = " on 16-bit targets",
1409 }
1410midpoint_impl! { usize, u32, unsigned }
1411carrying_carryless_mul_impl! { usize, u32 }
1412}
14131414#[doc(auto_cfg = false)]
1415#[cfg(target_pointer_width = "32")]
1416impl usize {
1417uint_impl! {
1418Self = usize,
1419 ActualT = u32,
1420 SignedT = isize,
1421 BITS = 32,
1422 BITS_MINUS_ONE = 31,
1423 MAX = 4294967295,
1424 rot = 8,
1425 rot_op = "0x10000b3",
1426 rot_result = "0xb301",
1427 fsh_op = "0x2fe78e45",
1428 fshl_result = "0xb32f",
1429 fshr_result = "0xb32fe78e",
1430 clmul_lhs = "0x56789012",
1431 clmul_rhs = "0xf52ecd34",
1432 clmul_result = "0x9b980928",
1433 swap_op = "0x12345678",
1434 swapped = "0x78563412",
1435 reversed = "0x1e6a2c48",
1436 le_bytes = "[0x78, 0x56, 0x34, 0x12]",
1437 be_bytes = "[0x12, 0x34, 0x56, 0x78]",
1438 to_xe_bytes_doc = usize_isize_to_xe_bytes_doc!(),
1439 from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(),
1440 bound_condition = " on 32-bit targets",
1441 }
1442midpoint_impl! { usize, u64, unsigned }
1443carrying_carryless_mul_impl! { usize, u64 }
1444}
14451446#[doc(auto_cfg = false)]
1447#[cfg(target_pointer_width = "64")]
1448impl usize {
1449/// The smallest value that can be represented by this integer type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(usize::MIN, 0);"]
/// ```
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MIN: Self = 0;
/// The largest value that can be represented by this integer type
#[doc = "(2<sup>64</sup> − 1 on 64-bit targets)."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(usize::MAX, 18446744073709551615);"]
/// ```
#[stable(feature = "assoc_int_consts", since = "1.43.0")]
pub const MAX: Self = !0;
/// The size of this integer type in bits.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(usize::BITS, 64);"]
/// ```
#[stable(feature = "int_bits_const", since = "1.53.0")]
pub const BITS: u32 = Self::MAX.count_ones();
/// Returns the number of ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 0b01001100usize;"]
/// assert_eq!(n.count_ones(), 3);
///
#[doc = "let max = usize::MAX;"]
#[doc = "assert_eq!(max.count_ones(), 64);"]
///
#[doc = "let zero = 0usize;"]
/// assert_eq!(zero.count_ones(), 0);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[doc(alias = "popcount")]
#[doc(alias = "popcnt")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn count_ones(self) -> u32 { return intrinsics::ctpop(self); }
/// Returns the number of zeros in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let zero = 0usize;"]
#[doc = "assert_eq!(zero.count_zeros(), 64);"]
///
#[doc = "let max = usize::MAX;"]
/// assert_eq!(max.count_zeros(), 0);
/// ```
///
/// This is heavily dependent on the width of the type, and thus
/// might give surprising results depending on type inference:
/// ```
/// # fn foo(_: u8) {}
/// # fn bar(_: u16) {}
/// let lucky = 7;
/// foo(lucky);
/// assert_eq!(lucky.count_zeros(), 5);
/// assert_eq!(lucky.count_ones(), 3);
///
/// let lucky = 7;
/// bar(lucky);
/// assert_eq!(lucky.count_zeros(), 13);
/// assert_eq!(lucky.count_ones(), 3);
/// ```
/// You might want to use [`Self::count_ones`] instead, or emphasize
/// the type you're using in the call rather than method syntax:
/// ```
/// let small = 1;
#[doc = "assert_eq!(usize::count_zeros(small), 63);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn count_zeros(self) -> u32 { (!self).count_ones() }
/// Returns the number of leading zeros in the binary representation of `self`.
///
/// Depending on what you're doing with the value, you might also be interested in the
/// [`ilog2`] function which returns a consistent number, even if the type widens.
///
/// # Examples
///
/// ```
#[doc = "let n = usize::MAX >> 2;"]
/// assert_eq!(n.leading_zeros(), 2);
///
#[doc = "let zero = 0usize;"]
#[doc = "assert_eq!(zero.leading_zeros(), 64);"]
///
#[doc = "let max = usize::MAX;"]
/// assert_eq!(max.leading_zeros(), 0);
/// ```
#[doc = "[`ilog2`]: usize::ilog2"]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn leading_zeros(self) -> u32 {
return intrinsics::ctlz(self as u64);
}
/// Returns the number of trailing zeros in the binary representation
/// of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 0b0101000usize;"]
/// assert_eq!(n.trailing_zeros(), 3);
///
#[doc = "let zero = 0usize;"]
#[doc = "assert_eq!(zero.trailing_zeros(), 64);"]
///
#[doc = "let max = usize::MAX;"]
#[doc = "assert_eq!(max.trailing_zeros(), 0);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn trailing_zeros(self) -> u32 { return intrinsics::cttz(self); }
/// Returns the number of leading ones in the binary representation of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = !(usize::MAX >> 2);"]
/// assert_eq!(n.leading_ones(), 2);
///
#[doc = "let zero = 0usize;"]
/// assert_eq!(zero.leading_ones(), 0);
///
#[doc = "let max = usize::MAX;"]
#[doc = "assert_eq!(max.leading_ones(), 64);"]
/// ```
#[stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn leading_ones(self) -> u32 { (!self).leading_zeros() }
/// Returns the number of trailing ones in the binary representation
/// of `self`.
///
/// # Examples
///
/// ```
#[doc = "let n = 0b1010111usize;"]
/// assert_eq!(n.trailing_ones(), 3);
///
#[doc = "let zero = 0usize;"]
/// assert_eq!(zero.trailing_ones(), 0);
///
#[doc = "let max = usize::MAX;"]
#[doc = "assert_eq!(max.trailing_ones(), 64);"]
/// ```
#[stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[rustc_const_stable(feature = "leading_trailing_ones", since = "1.46.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn trailing_ones(self) -> u32 { (!self).trailing_zeros() }
/// Returns the minimum number of bits required to represent `self`.
///
/// This method returns zero if `self` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0_usize.bit_width(), 0);"]
#[doc = "assert_eq!(0b111_usize.bit_width(), 3);"]
#[doc = "assert_eq!(0b1110_usize.bit_width(), 4);"]
#[doc = "assert_eq!(usize::MAX.bit_width(), 64);"]
/// ```
#[stable(feature = "uint_bit_width", since = "1.97.0")]
#[rustc_const_stable(feature = "uint_bit_width", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn bit_width(self) -> u32 { Self::BITS - self.leading_zeros() }
/// Returns `self` with only the most significant bit set, or `0` if
/// the input is `0`.
///
/// # Examples
///
/// ```
#[doc = "let n: usize = 0b_01100100;"]
///
/// assert_eq!(n.isolate_highest_one(), 0b_01000000);
#[doc = "assert_eq!(0_usize.isolate_highest_one(), 0);"]
/// ```
#[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn isolate_highest_one(self) -> Self {
self &
(((1 as usize) <<
(<usize>::BITS - 1)).wrapping_shr(self.leading_zeros()))
}
/// Returns `self` with only the least significant bit set, or `0` if
/// the input is `0`.
///
/// # Examples
///
/// ```
#[doc = "let n: usize = 0b_01100100;"]
///
/// assert_eq!(n.isolate_lowest_one(), 0b_00000100);
#[doc = "assert_eq!(0_usize.isolate_lowest_one(), 0);"]
/// ```
#[stable(feature = "isolate_most_least_significant_one", since = "1.97.0")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn isolate_lowest_one(self) -> Self { self & self.wrapping_neg() }
/// Returns the index of the highest bit set to one in `self`, or `None`
/// if `self` is `0`.
///
/// Note that this is equivalent to [`checked_ilog2`](Self::checked_ilog2).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0b0_usize.highest_one(), None);"]
#[doc = "assert_eq!(0b1_usize.highest_one(), Some(0));"]
#[doc = "assert_eq!(0b1_0000_usize.highest_one(), Some(4));"]
#[doc = "assert_eq!(0b1_1111_usize.highest_one(), Some(4));"]
/// ```
#[stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn highest_one(self) -> Option<u32> {
match NonZero::new(self) {
Some(v) => Some(v.highest_one()),
None => None,
}
}
/// Returns the index of the lowest bit set to one in `self`, or `None`
/// if `self` is `0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0b0_usize.lowest_one(), None);"]
#[doc = "assert_eq!(0b1_usize.lowest_one(), Some(0));"]
#[doc = "assert_eq!(0b1_0000_usize.lowest_one(), Some(4));"]
#[doc = "assert_eq!(0b1_1111_usize.lowest_one(), Some(0));"]
/// ```
#[stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since = "1.97.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn lowest_one(self) -> Option<u32> {
match NonZero::new(self) {
Some(v) => Some(v.lowest_one()),
None => None,
}
}
/// Returns the bit pattern of `self` reinterpreted as a signed integer of the same size.
///
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
/// the same.
///
/// # Examples
///
/// ```
#[doc = "let n = usize::MAX;"]
///
#[doc = "assert_eq!(n.cast_signed(), -1isize);"]
/// ```
#[stable(feature = "integer_sign_cast", since = "1.87.0")]
#[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_signed(self) -> isize { self as isize }
/// Saturating conversion of `self` to a signed integer of the same size.
///
/// The signed integer's maximum value is returned if `self` is larger
/// than the maximum positive value representable by the signed integer.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`checked_cast_signed`](Self::checked_cast_signed),
/// or [`strict_cast_signed`](Self::strict_cast_signed).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = usize::MAX;"]
///
#[doc = "assert_eq!(n.saturating_cast_signed(), isize::MAX);"]
#[doc = "assert_eq!(64usize.saturating_cast_signed(), 64isize);"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_cast_signed(self) -> isize {
if self <= <isize>::MAX.cast_unsigned() {
self.cast_signed()
} else { <isize>::MAX }
}
/// Checked conversion of `self` to a signed integer of the same size,
/// returning `None` if `self` is larger than the signed integer's
/// maximum value.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`saturating_cast_signed`](Self::saturating_cast_signed),
/// or [`strict_cast_signed`](Self::strict_cast_signed).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = usize::MAX;"]
///
#[doc = "assert_eq!(n.checked_cast_signed(), None);"]
#[doc = "assert_eq!(64usize.checked_cast_signed(), Some(64isize));"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn checked_cast_signed(self) -> Option<isize> {
if self <= <isize>::MAX.cast_unsigned() {
Some(self.cast_signed())
} else { None }
}
/// Strict conversion of `self` to a signed integer of the same size,
/// which panics if `self` is larger than the signed integer's maximum
/// value.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`checked_cast_signed`](Self::checked_cast_signed),
/// or [`saturating_cast_signed`](Self::saturating_cast_signed).
///
/// # Examples
///
/// ```should_panic
/// #![feature(integer_cast_extras)]
#[doc = "let _ = usize::MAX.strict_cast_signed();"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_cast_signed(self) -> isize {
match self.checked_cast_signed() {
Some(n) => n,
None => imp::overflow_panic::cast_integer(),
}
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `<<` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0xaa00000000006e1usize;"]
#[doc = "let m = 0x6e10aa;"]
///
#[doc = "assert_eq!(n.rotate_left(12), m);"]
#[doc = "assert_eq!(n.rotate_left(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
pub const fn rotate_left(self, n: u32) -> Self {
return intrinsics::rotate_left(self, n);
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `>>` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x6e10aausize;"]
#[doc = "let m = 0xaa00000000006e1;"]
///
#[doc = "assert_eq!(n.rotate_right(12), m);"]
#[doc = "assert_eq!(n.rotate_right(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
pub const fn rotate_right(self, n: u32) -> Self {
return intrinsics::rotate_right(self, n);
}
/// Performs a left funnel shift (concatenates `self` with `rhs`, with `self`
/// making up the most significant half, then shifts the combined value left
/// by `n`, and most significant half is extracted to produce the result).
///
/// Please note this isn't the same operation as the `<<` shifting operator or
/// [`rotate_left`](Self::rotate_left), although `a.funnel_shl(a, n)` is *equivalent*
/// to `a.rotate_left(n)`.
///
/// # Panics
///
/// If `n` is greater than or equal to the number of bits in `self`
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(funnel_shifts)]
#[doc = "let a = 0xaa00000000006e1usize;"]
#[doc = "let b = 0x2fe78e45983acd98usize;"]
#[doc = "let m = 0x6e12fe;"]
///
#[doc = "assert_eq!(a.funnel_shl(b, 12), m);"]
/// ```
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn funnel_shl(self, rhs: Self, n: u32) -> Self {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift left with overflow"));
}
};
unsafe { self.unchecked_funnel_shl(rhs, n) }
}
/// Performs a right funnel shift (concatenates `self` and `rhs`, with `self`
/// making up the most significant half, then shifts the combined value right
/// by `n`, and least significant half is extracted to produce the result).
///
/// Please note this isn't the same operation as the `>>` shifting operator or
/// [`rotate_right`](Self::rotate_right), although `a.funnel_shr(a, n)` is *equivalent*
/// to `a.rotate_right(n)`.
///
/// # Panics
///
/// If `n` is greater than or equal to the number of bits in `self`
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(funnel_shifts)]
#[doc = "let a = 0xaa00000000006e1usize;"]
#[doc = "let b = 0x2fe78e45983acd98usize;"]
#[doc = "let m = 0x6e12fe78e45983ac;"]
///
#[doc = "assert_eq!(a.funnel_shr(b, 12), m);"]
/// ```
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn funnel_shr(self, rhs: Self, n: u32) -> Self {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift right with overflow"));
}
};
unsafe { self.unchecked_funnel_shr(rhs, n) }
}
/// Unchecked funnel shift left.
///
/// # Safety
///
/// This results in undefined behavior if `n` is greater than or equal to
#[doc = "`usize::BITS`,"]
/// i.e. when [`funnel_shl`](Self::funnel_shl) would panic.
///
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_funnel_shl(self, low: Self, n: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(n: u32) {
if !(n < <u64>::BITS) {
let msg =
"unsafe precondition(s) violated: usize::unchecked_funnel_shl cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(n); }
};
unsafe { intrinsics::unchecked_funnel_shl(self, low, n) }
}
/// Unchecked funnel shift right.
///
/// # Safety
///
/// This results in undefined behavior if `n` is greater than or equal to
#[doc = "`usize::BITS`,"]
/// i.e. when [`funnel_shr`](Self::funnel_shr) would panic.
///
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_funnel_shr(self, low: Self, n: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(n: u32) {
if !(n < <u64>::BITS) {
let msg =
"unsafe precondition(s) violated: usize::unchecked_funnel_shr cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(n); }
};
unsafe { intrinsics::unchecked_funnel_shr(self, low, n) }
}
/// Performs a carry-less multiplication, returning the lower bits.
///
/// This operation is similar to long multiplication in base 2, except that exclusive or is
/// used instead of addition. The implementation is equivalent to:
///
/// ```no_run
#[doc = "pub fn carryless_mul(lhs: usize, rhs: usize) -> usize{"]
/// let mut retval = 0;
#[doc = " for i in 0..usize::BITS {"]
/// if (rhs >> i) & 1 != 0 {
/// // long multiplication would use +=
/// retval ^= lhs << i;
/// }
/// }
/// retval
/// }
/// ```
///
/// The actual implementation is more efficient, and on some platforms lowers directly to a
/// dedicated instruction.
///
/// # Uses
///
/// Carryless multiplication can be used to turn a bitmask of quote characters into a
/// bit mask of characters surrounded by quotes:
///
/// ```no_run
/// r#"abc xxx "foobar" zzz "a"!"#; // input string
/// 0b0000000010000001000001010; // quote_mask
/// 0b0000000001111110000000100; // quote_mask.carryless_mul(!0) & !quote_mask
/// ```
///
/// Another use is in cryptography, where carryless multiplication allows for efficient
/// implementations of polynomial multiplication in `GF(2)[X]`, the polynomial ring
/// over `GF(2)`.
///
/// # Examples
///
/// ```
/// #![feature(uint_carryless_mul)]
///
#[doc = "let a = 0x7890123456789012usize;"]
#[doc = "let b = 0xdd358416f52ecd34usize;"]
///
#[doc = "assert_eq!(a.carryless_mul(b), 0xa6299579b980928);"]
/// ```
#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
#[doc(alias = "clmul")]
#[unstable(feature = "uint_carryless_mul", issue = "152080")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn carryless_mul(self, rhs: Self) -> Self {
intrinsics::carryless_mul(self, rhs)
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1234567890123456usize;"]
/// let m = n.swap_bytes();
///
#[doc = "assert_eq!(m, 0x5634129078563412);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn swap_bytes(self) -> Self {
intrinsics::bswap(self as u64) as Self
}
/// Returns an integer with the bit locations specified by `mask` packed
/// contiguously into the least significant bits of the result.
/// ```
/// #![feature(uint_gather_scatter_bits)]
#[doc = "let n: usize = 0b1011_1100;"]
///
/// assert_eq!(n.extract_bits(0b0010_0100), 0b0000_0011);
/// assert_eq!(n.extract_bits(0xF0), 0b0000_1011);
/// ```
#[doc(alias = "pext")]
#[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn extract_bits(self, mask: Self) -> Self {
imp::int_bits::u64::extract_impl(self as u64, mask as u64) as usize
}
/// Returns an integer with the least significant bits of `self`
/// distributed to the bit locations specified by `mask`.
/// ```
/// #![feature(uint_gather_scatter_bits)]
#[doc = "let n: usize = 0b1010_1101;"]
///
/// assert_eq!(n.deposit_bits(0b0101_0101), 0b0101_0001);
/// assert_eq!(n.deposit_bits(0xF0), 0b1101_0000);
/// ```
#[doc(alias = "pdep")]
#[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn deposit_bits(self, mask: Self) -> Self {
imp::int_bits::u64::deposit_impl(self as u64, mask as u64) as usize
}
/// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
/// second least-significant bit becomes second most-significant bit, etc.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1234567890123456usize;"]
/// let m = n.reverse_bits();
///
#[doc = "assert_eq!(m, 0x6a2c48091e6a2c48);"]
#[doc = "assert_eq!(0, 0usize.reverse_bits());"]
/// ```
#[stable(feature = "reverse_bits", since = "1.37.0")]
#[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn reverse_bits(self) -> Self {
intrinsics::bitreverse(self as u64) as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ausize;"]
///
/// if cfg!(target_endian = "big") {
#[doc = " assert_eq!(usize::from_be(n), n)"]
/// } else {
#[doc = " assert_eq!(usize::from_be(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use]
#[inline(always)]
pub const fn from_be(x: Self) -> Self { x.swap_bytes() }
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ausize;"]
///
/// if cfg!(target_endian = "little") {
#[doc = " assert_eq!(usize::from_le(n), n)"]
/// } else {
#[doc = " assert_eq!(usize::from_le(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use]
#[inline(always)]
pub const fn from_le(x: Self) -> Self { x }
/// Converts `self` to big endian from the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ausize;"]
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn to_be(self) -> Self { self.swap_bytes() }
/// Converts `self` to little endian from the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ausize;"]
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn to_le(self) -> Self { self }
/// Checked integer addition. Computes `self + rhs`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((usize::MAX - 2).checked_add(1), Some(usize::MAX - 1));"]
#[doc = "assert_eq!((usize::MAX - 2).checked_add(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(intrinsics::add_with_overflow(self, rhs).1) {
None
} else { Some(unsafe { intrinsics::unchecked_add(self, rhs) }) }
}
/// Strict integer addition. Computes `self + rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((usize::MAX - 2).strict_add(1), usize::MAX - 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (usize::MAX - 2).strict_add(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_add(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Unchecked integer addition. Computes `self + rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_add(y)` is semantically equivalent to calling
/// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_add`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self + rhs > usize::MAX`,"]
/// i.e. when [`checked_add`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_add`]: usize::checked_add"]
#[doc = "[`wrapping_add`]: usize::wrapping_add"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: usize, rhs: usize) {
if !!lhs.overflowing_add(rhs).1 {
let msg =
"unsafe precondition(s) violated: usize::unchecked_add cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_add(self, rhs) }
}
/// Checked addition with a signed integer. Computes `self + rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1usize.checked_add_signed(2), Some(3));"]
#[doc = "assert_eq!(1usize.checked_add_signed(-2), None);"]
#[doc = "assert_eq!((usize::MAX - 2).checked_add_signed(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add_signed(self, rhs: isize) -> Option<Self> {
let (a, b) = self.overflowing_add_signed(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict addition with a signed integer. Computes `self + rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1usize.strict_add_signed(2), 3);"]
/// ```
///
/// The following panic because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1usize.strict_add_signed(-2);"]
/// ```
///
/// ```should_panic
#[doc = "let _ = (usize::MAX - 2).strict_add_signed(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add_signed(self, rhs: isize) -> Self {
let (a, b) = self.overflowing_add_signed(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Checked integer subtraction. Computes `self - rhs`, returning
/// `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1usize.checked_sub(1), Some(0));"]
#[doc = "assert_eq!(0usize.checked_sub(1), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
if self < rhs {
None
} else { Some(unsafe { intrinsics::unchecked_sub(self, rhs) }) }
}
/// Strict integer subtraction. Computes `self - rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1usize.strict_sub(1), 0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0usize.strict_sub(1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_sub(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
/// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_sub`].
///
/// If you find yourself writing code like this:
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if foo >= bar {
/// // SAFETY: just checked it will not overflow
/// let diff = unsafe { foo.unchecked_sub(bar) };
/// // ... use diff ...
/// }
/// ```
///
/// Consider changing it to
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if let Some(diff) = foo.checked_sub(bar) {
/// // ... use diff ...
/// }
/// ```
///
/// As that does exactly the same thing -- including telling the optimizer
/// that the subtraction cannot overflow -- but avoids needing `unsafe`.
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self - rhs < usize::MIN`,"]
/// i.e. when [`checked_sub`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_sub`]: usize::checked_sub"]
#[doc = "[`wrapping_sub`]: usize::wrapping_sub"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: usize, rhs: usize) {
if !!lhs.overflowing_sub(rhs).1 {
let msg =
"unsafe precondition(s) violated: usize::unchecked_sub cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_sub(self, rhs) }
}
/// Checked subtraction with a signed integer. Computes `self - rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1usize.checked_sub_signed(2), None);"]
#[doc = "assert_eq!(1usize.checked_sub_signed(-2), Some(3));"]
#[doc = "assert_eq!((usize::MAX - 2).checked_sub_signed(-4), None);"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub_signed(self, rhs: isize) -> Option<Self> {
let (res, overflow) = self.overflowing_sub_signed(rhs);
if !overflow { Some(res) } else { None }
}
/// Strict subtraction with a signed integer. Computes `self - rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3usize.strict_sub_signed(2), 1);"]
/// ```
///
/// The following panic because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1usize.strict_sub_signed(2);"]
/// ```
///
/// ```should_panic
#[doc = "let _ = (usize::MAX).strict_sub_signed(-1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub_signed(self, rhs: isize) -> Self {
let (a, b) = self.overflowing_sub_signed(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
#[doc =
"Checked integer subtraction. Computes `self - rhs` and checks if the result fits into an [`isize`], returning `None` if overflow occurred."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10usize.checked_signed_diff(2), Some(8));"]
#[doc = "assert_eq!(2usize.checked_signed_diff(10), Some(-8));"]
#[doc =
"assert_eq!(usize::MAX.checked_signed_diff(isize::MAX as usize), None);"]
#[doc =
"assert_eq!((isize::MAX as usize).checked_signed_diff(usize::MAX), Some(isize::MIN));"]
#[doc = "assert_eq!((isize::MAX as usize + 1).checked_signed_diff(0), None);"]
#[doc = "assert_eq!(usize::MAX.checked_signed_diff(usize::MAX), Some(0));"]
/// ```
#[stable(feature = "unsigned_signed_diff", since = "1.91.0")]
#[rustc_const_stable(feature = "unsigned_signed_diff", since = "1.91.0")]
#[inline]
pub const fn checked_signed_diff(self, rhs: Self) -> Option<isize> {
let res = self.wrapping_sub(rhs) as isize;
let overflow = (self >= rhs) == (res < 0);
if !overflow { Some(res) } else { None }
}
/// Checked integer multiplication. Computes `self * rhs`, returning
/// `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5usize.checked_mul(1), Some(5));"]
#[doc = "assert_eq!(usize::MAX.checked_mul(2), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer multiplication. Computes `self * rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5usize.strict_mul(1), 5);"]
/// ```
///
/// The following panics because of overflow:
///
/// ``` should_panic
#[doc = "let _ = usize::MAX.strict_mul(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_mul(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_mul(rhs);
if b { imp::overflow_panic::mul() } else { a }
}
/// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
/// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_mul`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self * rhs > usize::MAX`,"]
/// i.e. when [`checked_mul`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_mul`]: usize::checked_mul"]
#[doc = "[`wrapping_mul`]: usize::wrapping_mul"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: usize, rhs: usize) {
if !!lhs.overflowing_mul(rhs).1 {
let msg =
"unsafe precondition(s) violated: usize::unchecked_mul cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_mul(self, rhs) }
}
/// Checked integer division. Computes `self / rhs`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128usize.checked_div(2), Some(64));"]
#[doc = "assert_eq!(1usize.checked_div(0), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(unsafe { intrinsics::unchecked_div(self, rhs) }) }
}
/// Strict integer division. Computes `self / rhs`.
///
/// Strict division on unsigned types is just normal division. There's no
/// way overflow could ever happen. This function exists so that all
/// operations are accounted for in the strict operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100usize.strict_div(10), 10);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1usize).strict_div(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_div(self, rhs: Self) -> Self { self / rhs }
/// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128usize.checked_div_euclid(2), Some(64));"]
#[doc = "assert_eq!(1usize.checked_div_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(self.div_euclid(rhs)) }
}
/// Strict Euclidean division. Computes `self.div_euclid(rhs)`.
///
/// Strict division on unsigned types is just normal division. There's no
/// way overflow could ever happen. This function exists so that all
/// operations are accounted for in the strict operations. Since, for the
/// positive integers, all common definitions of division are equal, this
/// is exactly equal to `self.strict_div(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100usize.strict_div_euclid(10), 10);"]
/// ```
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1usize).strict_div_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Checked integer division without remainder. Computes `self / rhs`,
/// returning `None` if `rhs == 0` or if `self % rhs != 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64usize.checked_div_exact(2), Some(32));"]
#[doc = "assert_eq!(64usize.checked_div_exact(32), Some(2));"]
#[doc = "assert_eq!(64usize.checked_div_exact(0), None);"]
#[doc = "assert_eq!(65usize.checked_div_exact(2), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_exact(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else {
unsafe {
if intrinsics::unlikely(intrinsics::unchecked_rem(self, rhs) != 0)
{
None
} else { Some(intrinsics::exact_div(self, rhs)) }
}
}
}
/// Integer division without remainder. Computes `self / rhs`, returning `None` if `self % rhs != 0`.
///
/// # Panics
///
/// This function will panic if `rhs == 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64usize.div_exact(2), Some(32));"]
#[doc = "assert_eq!(64usize.div_exact(32), Some(2));"]
#[doc = "assert_eq!(65usize.div_exact(2), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn div_exact(self, rhs: Self) -> Option<Self> {
if self % rhs != 0 { None } else { Some(self / rhs) }
}
/// Unchecked integer division without remainder. Computes `self / rhs`.
///
/// # Safety
///
/// This results in undefined behavior when `rhs == 0` or `self % rhs != 0`,
/// i.e. when [`checked_div_exact`](Self::checked_div_exact) would return `None`.
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_div_exact(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: usize, rhs: usize) {
if !(rhs > 0 && lhs % rhs == 0) {
let msg =
"unsafe precondition(s) violated: usize::unchecked_div_exact divide by zero or leave a remainder\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::exact_div(self, rhs) }
}
/// Checked integer remainder. Computes `self % rhs`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5usize.checked_rem(2), Some(1));"]
#[doc = "assert_eq!(5usize.checked_rem(0), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(unsafe { intrinsics::unchecked_rem(self, rhs) }) }
}
/// Strict integer remainder. Computes `self % rhs`.
///
/// Strict remainder calculation on unsigned types is just the regular
/// remainder calculation. There's no way overflow could ever happen.
/// This function exists so that all operations are accounted for in the
/// strict operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100usize.strict_rem(10), 0);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5usize.strict_rem(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_rem(self, rhs: Self) -> Self { self % rhs }
/// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5usize.checked_rem_euclid(2), Some(1));"]
#[doc = "assert_eq!(5usize.checked_rem_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(self.rem_euclid(rhs)) }
}
/// Strict Euclidean modulo. Computes `self.rem_euclid(rhs)`.
///
/// Strict modulo calculation on unsigned types is just the regular
/// remainder calculation. There's no way overflow could ever happen.
/// This function exists so that all operations are accounted for in the
/// strict operations. Since, for the positive integers, all common
/// definitions of division are equal, this is exactly equal to
/// `self.strict_rem(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100usize.strict_rem_euclid(10), 0);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5usize.strict_rem_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Same value as `self | other`, but UB if any bit position is set in both inputs.
///
/// This is a situational micro-optimization for places where you'd rather
/// use addition on some platforms and bitwise or on other platforms, based
/// on exactly which instructions combine better with whatever else you're
/// doing. Note that there's no reason to bother using this for places
/// where it's clear from the operations involved that they can't overlap.
/// For example, if you're combining `u16`s into a `u32` with
/// `((a as u32) << 16) | (b as u32)`, that's fine, as the backend will
/// know those sides of the `|` are disjoint without needing help.
///
/// # Examples
///
/// ```
/// #![feature(disjoint_bitor)]
///
/// // SAFETY: `1` and `4` have no bits in common.
/// unsafe {
#[doc = " assert_eq!(1_usize.unchecked_disjoint_bitor(4), 5);"]
/// }
/// ```
///
/// # Safety
///
/// Requires that `(self & other) == 0`, otherwise it's immediate UB.
///
/// Equivalently, requires that `(self | other) == (self + other)`.
#[unstable(feature = "disjoint_bitor", issue = "135758")]
#[rustc_const_unstable(feature = "disjoint_bitor", issue = "135758")]
#[inline]
pub const unsafe fn unchecked_disjoint_bitor(self, other: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: usize, rhs: usize) {
if !((lhs & rhs) == 0) {
let msg =
"unsafe precondition(s) violated: usize::unchecked_disjoint_bitor cannot have overlapping bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, other);
}
};
unsafe { intrinsics::disjoint_bitor(self, other) }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// This method might not be optimized owing to implementation details;
/// [`ilog2`](Self::ilog2) can produce results more efficiently for base 2,
/// and [`ilog10`](Self::ilog10) can produce results more efficiently for base 10.
///
/// # Panics
///
/// This function will panic if `self` is zero, or if `base` is less than 2.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5usize.ilog(5), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog(self, base: Self) -> u32 {
if !(base >= 2) {
{
crate::panicking::panic_fmt(format_args!("base of integer logarithm must be at least 2"));
}
};
if let Some(log) = self.checked_ilog(base) {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the base 2 logarithm of the number, rounded down.
///
/// # Panics
///
/// This function will panic if `self` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2usize.ilog2(), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog2(self) -> u32 {
if let Some(log) = self.checked_ilog2() {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// # Panics
///
/// This function will panic if `self` is zero.
///
/// # Example
///
/// ```
#[doc = "assert_eq!(10usize.ilog10(), 1);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn ilog10(self) -> u32 {
if let Some(log) = self.checked_ilog10() {
log
} else { imp::int_log10::panic_for_nonpositive_argument() }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// Returns `None` if the number is zero, or if the base is not at least 2.
///
/// This method might not be optimized owing to implementation details;
/// `checked_ilog2` can produce results more efficiently for base 2, and
/// `checked_ilog10` can produce results more efficiently for base 10.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5usize.checked_ilog(5), Some(1));"]
#[doc = "assert_eq!(4usize.checked_ilog(5), Some(0));"]
#[doc = "assert_eq!(5usize.checked_ilog(0), None);"]
#[doc = "assert_eq!(5usize.checked_ilog(1), None);"]
#[doc = "assert_eq!(0usize.checked_ilog(1), None);"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog(self, base: Self) -> Option<u32> {
if core::intrinsics::is_val_statically_known(base) {
if base.is_power_of_two() && base > 1 {
let k = base.ilog2();
return Some(match self.checked_ilog2() {
Some(x) => x,
None => return None,
} / k);
}
if base == 10 { return self.checked_ilog10(); }
}
if self <= 0 || base <= 1 {
None
} else if self < base {
Some(0)
} else {
let mut n = 1;
let mut r = base;
if Self::BITS == 128 {
n = self.ilog2() / (base.ilog2() + 1);
r = base.pow(n);
}
while r <= self / base { n += 1; r *= base; }
Some(n)
}
}
/// Returns the base 2 logarithm of the number, rounded down.
///
/// Returns `None` if the number is zero.
///
/// Note that this is equivalent to [`highest_one`](Self::highest_one).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2usize.checked_ilog2(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog2(self) -> Option<u32> {
match NonZero::new(self) { Some(x) => Some(x.ilog2()), None => None, }
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// Returns `None` if the number is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10usize.checked_ilog10(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog10(self) -> Option<u32> {
match NonZero::new(self) { Some(x) => Some(x.ilog10()), None => None, }
}
/// Checked negation. Computes `-self`, returning `None` unless `self ==
/// 0`.
///
/// Note that negating any positive integer will overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0usize.checked_neg(), Some(0));"]
#[doc = "assert_eq!(1usize.checked_neg(), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_neg(self) -> Option<Self> {
let (a, b) = self.overflowing_neg();
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict negation. Computes `-self`, panicking unless `self ==
/// 0`.
///
/// Note that negating any positive integer will overflow.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0usize.strict_neg(), 0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1usize.strict_neg();"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_neg(self) -> Self {
let (a, b) = self.overflowing_neg();
if b { imp::overflow_panic::neg() } else { a }
}
/// Checked shift left. Computes `self << rhs`, returning `None`
/// if `rhs` is larger than or equal to the number of bits in `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1usize.checked_shl(4), Some(0x10));"]
#[doc = "assert_eq!(0x10usize.checked_shl(129), None);"]
#[doc = "assert_eq!(0x10usize.checked_shl(63), Some(0));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_shl(self, rhs: u32) -> Option<Self> {
if rhs < Self::BITS {
Some(unsafe { self.unchecked_shl(rhs) })
} else { None }
}
/// Strict shift left. Computes `self << rhs`, panicking if `rhs` is larger
/// than or equal to the number of bits in `self`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1usize.strict_shl(4), 0x10);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0x10usize.strict_shl(129);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_shl(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_shl(rhs);
if b { imp::overflow_panic::shl() } else { a }
}
/// Unchecked shift left. Computes `self << rhs`, assuming that
/// `rhs` is less than the number of bits in `self`.
///
/// # Safety
///
/// This results in undefined behavior if `rhs` is larger than
/// or equal to the number of bits in `self`,
/// i.e. when [`checked_shl`] would return `None`.
///
#[doc = "[`checked_shl`]: usize::checked_shl"]
#[stable(feature = "unchecked_shifts", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_shl(self, rhs: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(rhs: u32) {
if !(rhs < <u64>::BITS) {
let msg =
"unsafe precondition(s) violated: usize::unchecked_shl cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(rhs); }
};
unsafe { intrinsics::unchecked_shl(self, rhs) }
}
/// Unbounded shift left. Computes `self << rhs`, without bounding the value of `rhs`.
///
/// If `rhs` is larger or equal to the number of bits in `self`,
/// the entire value is shifted out, and `0` is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1_usize.unbounded_shl(4), 0x10);"]
#[doc = "assert_eq!(0x1_usize.unbounded_shl(129), 0);"]
#[doc = "assert_eq!(0b101_usize.unbounded_shl(0), 0b101);"]
#[doc = "assert_eq!(0b101_usize.unbounded_shl(1), 0b1010);"]
#[doc = "assert_eq!(0b101_usize.unbounded_shl(2), 0b10100);"]
#[doc = "assert_eq!(42_usize.unbounded_shl(64), 0);"]
#[doc = "assert_eq!(42_usize.unbounded_shl(1).unbounded_shl(63), 0);"]
///
#[doc = "let start : usize = 13;"]
/// let mut running = start;
/// for i in 0..160 {
/// // The unbounded shift left by i is the same as `<< 1` i times
/// assert_eq!(running, start.unbounded_shl(i));
/// // Which is not always the case for a wrapping shift
#[doc = " assert_eq!(running == start.wrapping_shl(i), i < 64);"]
///
/// running <<= 1;
/// }
/// ```
#[stable(feature = "unbounded_shifts", since = "1.87.0")]
#[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unbounded_shl(self, rhs: u32) -> usize {
if rhs < Self::BITS { unsafe { self.unchecked_shl(rhs) } } else { 0 }
}
/// Exact shift left. Computes `self << rhs` as long as it can be reversed losslessly.
///
/// Returns `None` if any non-zero bits would be shifted out or if `rhs` >=
#[doc = "`usize::BITS`."]
/// Otherwise, returns `Some(self << rhs)`.
///
/// # Examples
///
/// ```
/// #![feature(exact_bitshifts)]
///
#[doc = "assert_eq!(0x1usize.shl_exact(4), Some(0x10));"]
#[doc = "assert_eq!(0x1usize.shl_exact(129), None);"]
/// ```
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn shl_exact(self, rhs: u32) -> Option<usize> {
if rhs <= self.leading_zeros() && rhs < <usize>::BITS {
Some(unsafe { self.unchecked_shl(rhs) })
} else { None }
}
/// Unchecked exact shift left. Computes `self << rhs`, assuming the operation can be
/// losslessly reversed `rhs` cannot be larger than
#[doc = "`usize::BITS`."]
///
/// # Safety
///
/// This results in undefined behavior when `rhs > self.leading_zeros() || rhs >=
#[doc = "usize::BITS`"]
/// i.e. when
#[doc = "[`usize::shl_exact`]"]
/// would return `None`.
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_shl_exact(self, rhs: u32) -> usize {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(zeros: u32, bits: u32, rhs: u32) {
if !(rhs <= zeros && rhs < bits) {
let msg =
"unsafe precondition(s) violated: usize::unchecked_shl_exact cannot shift out non-zero bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_library_ub() {
precondition_check(self.leading_zeros(), <usize>::BITS, rhs);
}
};
unsafe { self.unchecked_shl(rhs) }
}
/// Checked shift right. Computes `self >> rhs`, returning `None`
/// if `rhs` is larger than or equal to the number of bits in `self`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10usize.checked_shr(4), Some(0x1));"]
#[doc = "assert_eq!(0x10usize.checked_shr(129), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_shr(self, rhs: u32) -> Option<Self> {
if rhs < Self::BITS {
Some(unsafe { self.unchecked_shr(rhs) })
} else { None }
}
/// Strict shift right. Computes `self >> rhs`, panicking if `rhs` is
/// larger than or equal to the number of bits in `self`.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10usize.strict_shr(4), 0x1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0x10usize.strict_shr(129);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_shr(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_shr(rhs);
if b { imp::overflow_panic::shr() } else { a }
}
/// Unchecked shift right. Computes `self >> rhs`, assuming that
/// `rhs` is less than the number of bits in `self`.
///
/// # Safety
///
/// This results in undefined behavior if `rhs` is larger than
/// or equal to the number of bits in `self`,
/// i.e. when [`checked_shr`] would return `None`.
///
#[doc = "[`checked_shr`]: usize::checked_shr"]
#[stable(feature = "unchecked_shifts", since = "1.93.0")]
#[rustc_const_stable(feature = "unchecked_shifts", since = "1.93.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_shr(self, rhs: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(rhs: u32) {
if !(rhs < <u64>::BITS) {
let msg =
"unsafe precondition(s) violated: usize::unchecked_shr cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(rhs); }
};
unsafe { intrinsics::unchecked_shr(self, rhs) }
}
/// Unbounded shift right. Computes `self >> rhs`, without bounding the value of `rhs`.
///
/// If `rhs` is larger or equal to the number of bits in `self`,
/// the entire value is shifted out, and `0` is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10_usize.unbounded_shr(4), 0x1);"]
#[doc = "assert_eq!(0x10_usize.unbounded_shr(129), 0);"]
#[doc = "assert_eq!(0b1010_usize.unbounded_shr(0), 0b1010);"]
#[doc = "assert_eq!(0b1010_usize.unbounded_shr(1), 0b101);"]
#[doc = "assert_eq!(0b1010_usize.unbounded_shr(2), 0b10);"]
#[doc = "assert_eq!(42_usize.unbounded_shr(64), 0);"]
#[doc = "assert_eq!(42_usize.unbounded_shr(1).unbounded_shr(63), 0);"]
///
#[doc = "let start = usize::rotate_right(13, 4);"]
/// let mut running = start;
/// for i in 0..160 {
/// // The unbounded shift right by i is the same as `>> 1` i times
/// assert_eq!(running, start.unbounded_shr(i));
/// // Which is not always the case for a wrapping shift
#[doc = " assert_eq!(running == start.wrapping_shr(i), i < 64);"]
///
/// running >>= 1;
/// }
/// ```
#[stable(feature = "unbounded_shifts", since = "1.87.0")]
#[rustc_const_stable(feature = "unbounded_shifts", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn unbounded_shr(self, rhs: u32) -> usize {
if rhs < Self::BITS { unsafe { self.unchecked_shr(rhs) } } else { 0 }
}
/// Exact shift right. Computes `self >> rhs` as long as it can be reversed losslessly.
///
/// Returns `None` if any non-zero bits would be shifted out or if `rhs` >=
#[doc = "`usize::BITS`."]
/// Otherwise, returns `Some(self >> rhs)`.
///
/// # Examples
///
/// ```
/// #![feature(exact_bitshifts)]
///
#[doc = "assert_eq!(0x10usize.shr_exact(4), Some(0x1));"]
#[doc = "assert_eq!(0x10usize.shr_exact(5), None);"]
/// ```
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn shr_exact(self, rhs: u32) -> Option<usize> {
if rhs <= self.trailing_zeros() && rhs < <usize>::BITS {
Some(unsafe { self.unchecked_shr(rhs) })
} else { None }
}
/// Unchecked exact shift right. Computes `self >> rhs`, assuming the operation can be
/// losslessly reversed and `rhs` cannot be larger than
#[doc = "`usize::BITS`."]
///
/// # Safety
///
/// This results in undefined behavior when `rhs > self.trailing_zeros() || rhs >=
#[doc = "usize::BITS`"]
/// i.e. when
#[doc = "[`usize::shr_exact`]"]
/// would return `None`.
#[unstable(feature = "exact_bitshifts", issue = "144336")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_shr_exact(self, rhs: u32) -> usize {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(zeros: u32, bits: u32, rhs: u32) {
if !(rhs <= zeros && rhs < bits) {
let msg =
"unsafe precondition(s) violated: usize::unchecked_shr_exact cannot shift out non-zero bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_library_ub() {
precondition_check(self.trailing_zeros(), <usize>::BITS, rhs);
}
};
unsafe { self.unchecked_shr(rhs) }
}
/// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2usize.checked_pow(5), Some(32));"]
#[doc = "assert_eq!(0_usize.checked_pow(0), Some(1));"]
#[doc = "assert_eq!(usize::MAX.checked_pow(2), None);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_pow(self, mut exp: u32) -> Option<Self> {
let mut base = self;
let mut acc: Self = 1;
if intrinsics::is_val_statically_known(base) && base.is_power_of_two() {
let k = base.ilog2();
let shift =
match k.checked_mul(exp) { Some(x) => x, None => return None, };
return (1 as Self).checked_shl(shift);
}
if exp == 0 { return Some(1); }
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 {
acc =
match acc.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
exp /= 2;
base =
match base.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
return acc.checked_mul(base);
}
loop {
if (exp & 1) == 1 {
acc =
match acc.checked_mul(base) {
Some(x) => x,
None => return None,
};
if exp == 1 { return Some(acc); }
}
exp /= 2;
base =
match base.checked_mul(base) {
Some(x) => x,
None => return None,
};
}
}
/// Strict exponentiation. Computes `self.pow(exp)`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2usize.strict_pow(5), 32);"]
#[doc = "assert_eq!(0_usize.strict_pow(0), 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = usize::MAX.strict_pow(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) {
None => imp::overflow_panic::pow(),
Some(a) => a,
}
}
/// Saturating integer addition. Computes `self + rhs`, saturating at
/// the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100usize.saturating_add(1), 101);"]
#[doc = "assert_eq!(usize::MAX.saturating_add(127), usize::MAX);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[inline(always)]
pub const fn saturating_add(self, rhs: Self) -> Self {
intrinsics::saturating_add(self, rhs)
}
/// Saturating addition with a signed integer. Computes `self + rhs`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1usize.saturating_add_signed(2), 3);"]
#[doc = "assert_eq!(1usize.saturating_add_signed(-2), 0);"]
#[doc = "assert_eq!((usize::MAX - 2).saturating_add_signed(4), usize::MAX);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_add_signed(self, rhs: isize) -> Self {
let (res, overflow) = self.overflowing_add(rhs as Self);
if overflow == (rhs < 0) { res } else if overflow { Self::MAX } else { 0 }
}
/// Saturating integer subtraction. Computes `self - rhs`, saturating
/// at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100usize.saturating_sub(27), 73);"]
#[doc = "assert_eq!(13usize.saturating_sub(127), 0);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[inline(always)]
pub const fn saturating_sub(self, rhs: Self) -> Self {
intrinsics::saturating_sub(self, rhs)
}
/// Saturating integer subtraction. Computes `self` - `rhs`, saturating at
/// the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1usize.saturating_sub_signed(2), 0);"]
#[doc = "assert_eq!(1usize.saturating_sub_signed(-2), 3);"]
#[doc = "assert_eq!((usize::MAX - 2).saturating_sub_signed(-4), usize::MAX);"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_sub_signed(self, rhs: isize) -> Self {
let (res, overflow) = self.overflowing_sub_signed(rhs);
if !overflow { res } else if rhs < 0 { Self::MAX } else { 0 }
}
/// Saturating integer multiplication. Computes `self * rhs`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2usize.saturating_mul(10), 20);"]
#[doc = "assert_eq!((usize::MAX).saturating_mul(10), usize::MAX);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_saturating_int_methods", since =
"1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_mul(self, rhs: Self) -> Self {
match self.checked_mul(rhs) { Some(x) => x, None => Self::MAX, }
}
/// Saturating integer division. Computes `self / rhs`, saturating at the
/// numeric bounds instead of overflowing.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5usize.saturating_div(2), 2);"]
///
/// ```
#[stable(feature = "saturating_div", since = "1.58.0")]
#[rustc_const_stable(feature = "saturating_div", since = "1.58.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn saturating_div(self, rhs: Self) -> Self {
self.wrapping_div(rhs)
}
/// Saturating integer exponentiation. Computes `self.pow(exp)`,
/// saturating at the numeric bounds instead of overflowing.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(4usize.saturating_pow(3), 64);"]
#[doc = "assert_eq!(0_usize.saturating_pow(0), 1);"]
#[doc = "assert_eq!(usize::MAX.saturating_pow(2), usize::MAX);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn saturating_pow(self, exp: u32) -> Self {
match self.checked_pow(exp) { Some(x) => x, None => Self::MAX, }
}
/// Wrapping (modular) addition. Computes `self + rhs`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(200usize.wrapping_add(55), 255);"]
#[doc = "assert_eq!(200usize.wrapping_add(usize::MAX), 199);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_add(self, rhs: Self) -> Self {
intrinsics::wrapping_add(self, rhs)
}
/// Wrapping (modular) addition with a signed integer. Computes
/// `self + rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1usize.wrapping_add_signed(2), 3);"]
#[doc = "assert_eq!(1usize.wrapping_add_signed(-2), usize::MAX);"]
#[doc = "assert_eq!((usize::MAX - 2).wrapping_add_signed(4), 1);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_add_signed(self, rhs: isize) -> Self {
self.wrapping_add(rhs as Self)
}
/// Wrapping (modular) subtraction. Computes `self - rhs`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100usize.wrapping_sub(100), 0);"]
#[doc = "assert_eq!(100usize.wrapping_sub(usize::MAX), 101);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_sub(self, rhs: Self) -> Self {
intrinsics::wrapping_sub(self, rhs)
}
/// Wrapping (modular) subtraction with a signed integer. Computes
/// `self - rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1usize.wrapping_sub_signed(2), usize::MAX);"]
#[doc = "assert_eq!(1usize.wrapping_sub_signed(-2), 3);"]
#[doc = "assert_eq!((usize::MAX - 2).wrapping_sub_signed(-4), 1);"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_sub_signed(self, rhs: isize) -> Self {
self.wrapping_sub(rhs as Self)
}
/// Wrapping (modular) multiplication. Computes `self *
/// rhs`, wrapping around at the boundary of the type.
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `u8` is used.
///
/// ```
/// assert_eq!(10u8.wrapping_mul(12), 120);
/// assert_eq!(25u8.wrapping_mul(12), 44);
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_mul(self, rhs: Self) -> Self {
intrinsics::wrapping_mul(self, rhs)
}
/// Wrapping (modular) division. Computes `self / rhs`.
///
/// Wrapped division on unsigned types is just normal division. There's
/// no way wrapping could ever happen. This function exists so that all
/// operations are accounted for in the wrapping operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100usize.wrapping_div(10), 10);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn wrapping_div(self, rhs: Self) -> Self { self / rhs }
/// Wrapping Euclidean division. Computes `self.div_euclid(rhs)`.
///
/// Wrapped division on unsigned types is just normal division. There's
/// no way wrapping could ever happen. This function exists so that all
/// operations are accounted for in the wrapping operations. Since, for
/// the positive integers, all common definitions of division are equal,
/// this is exactly equal to `self.wrapping_div(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100usize.wrapping_div_euclid(10), 10);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn wrapping_div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Wrapping (modular) remainder. Computes `self % rhs`.
///
/// Wrapped remainder calculation on unsigned types is just the regular
/// remainder calculation. There's no way wrapping could ever happen.
/// This function exists so that all operations are accounted for in the
/// wrapping operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100usize.wrapping_rem(10), 0);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn wrapping_rem(self, rhs: Self) -> Self { self % rhs }
/// Wrapping Euclidean modulo. Computes `self.rem_euclid(rhs)`.
///
/// Wrapped modulo calculation on unsigned types is just the regular
/// remainder calculation. There's no way wrapping could ever happen.
/// This function exists so that all operations are accounted for in the
/// wrapping operations. Since, for the positive integers, all common
/// definitions of division are equal, this is exactly equal to
/// `self.wrapping_rem(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100usize.wrapping_rem_euclid(10), 0);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn wrapping_rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Wrapping (modular) negation. Computes `-self`,
/// wrapping around at the boundary of the type.
///
/// Since unsigned types do not have negative equivalents
/// all applications of this function will wrap (except for `-0`).
/// For values smaller than the corresponding signed type's maximum
/// the result is the same as casting the corresponding signed value.
/// Any larger values are equivalent to `MAX + 1 - (val - MAX - 1)` where
/// `MAX` is the corresponding signed type's maximum.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0_usize.wrapping_neg(), 0);"]
#[doc = "assert_eq!(usize::MAX.wrapping_neg(), 1);"]
#[doc = "assert_eq!(13_usize.wrapping_neg(), (!13) + 1);"]
#[doc = "assert_eq!(42_usize.wrapping_neg(), !(42 - 1));"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_neg(self) -> Self { (0 as usize).wrapping_sub(self) }
/// Panic-free bitwise shift-left; yields `self << mask(rhs)`,
/// where `mask` removes any high-order bits of `rhs` that
/// would cause the shift to exceed the bitwidth of the type.
///
/// Beware that, unlike most other `wrapping_*` methods on integers, this
/// does *not* give the same result as doing the shift in infinite precision
/// then truncating as needed. Instead, the behaviour of this method matches what shift instructions
/// do on many processors, and is what the `<<` operator does when overflow
/// checks are disabled, but numerically it's weird. Consider, instead,
/// using [`Self::unbounded_shl`] which has nicer behaviour.
///
/// Note that this is *not* the same as a rotate-left; the
/// RHS of a wrapping shift-left is restricted to the range
/// of the type, rather than the bits shifted out of the LHS
/// being returned to the other end. The primitive integer
/// types all implement a [`rotate_left`](Self::rotate_left) function,
/// which may be what you want instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1_usize.wrapping_shl(7), 128);"]
#[doc = "assert_eq!(0b101_usize.wrapping_shl(0), 0b101);"]
#[doc = "assert_eq!(0b101_usize.wrapping_shl(1), 0b1010);"]
#[doc = "assert_eq!(0b101_usize.wrapping_shl(2), 0b10100);"]
#[doc = "assert_eq!(usize::MAX.wrapping_shl(2), usize::MAX - 3);"]
#[doc = "assert_eq!(42_usize.wrapping_shl(64), 42);"]
#[doc = "assert_eq!(42_usize.wrapping_shl(1).wrapping_shl(63), 0);"]
#[doc = "assert_eq!(1_usize.wrapping_shl(128), 1);"]
#[doc = "assert_eq!(5_usize.wrapping_shl(1025), 10);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_shl(self, rhs: u32) -> Self {
unsafe { self.unchecked_shl(rhs & (Self::BITS - 1)) }
}
/// Panic-free bitwise shift-right; yields `self >> mask(rhs)`,
/// where `mask` removes any high-order bits of `rhs` that
/// would cause the shift to exceed the bitwidth of the type.
///
/// Beware that, unlike most other `wrapping_*` methods on integers, this
/// does *not* give the same result as doing the shift in infinite precision
/// then truncating as needed. Instead, the behaviour of this method matches what shift instructions
/// do on many processors, and is what the `>>` operator does when overflow
/// checks are disabled, but numerically it's weird. Consider, instead,
/// using [`Self::unbounded_shr`] which has nicer behaviour.
///
/// Note that this is *not* the same as a rotate-right; the
/// RHS of a wrapping shift-right is restricted to the range
/// of the type, rather than the bits shifted out of the LHS
/// being returned to the other end. The primitive integer
/// types all implement a [`rotate_right`](Self::rotate_right) function,
/// which may be what you want instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128_usize.wrapping_shr(7), 1);"]
#[doc = "assert_eq!(0b1010_usize.wrapping_shr(0), 0b1010);"]
#[doc = "assert_eq!(0b1010_usize.wrapping_shr(1), 0b101);"]
#[doc = "assert_eq!(0b1010_usize.wrapping_shr(2), 0b10);"]
#[doc = "assert_eq!(usize::MAX.wrapping_shr(1), isize::MAX.cast_unsigned());"]
#[doc = "assert_eq!(42_usize.wrapping_shr(64), 42);"]
#[doc = "assert_eq!(42_usize.wrapping_shr(1).wrapping_shr(63), 0);"]
#[doc = "assert_eq!(128_usize.wrapping_shr(128), 128);"]
#[doc = "assert_eq!(10_usize.wrapping_shr(1025), 5);"]
/// ```
#[stable(feature = "num_wrapping", since = "1.2.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn wrapping_shr(self, rhs: u32) -> Self {
unsafe { self.unchecked_shr(rhs & (Self::BITS - 1)) }
}
/// Wrapping (modular) exponentiation. Computes `self.pow(exp)`,
/// wrapping around at the boundary of the type.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3usize.wrapping_pow(5), 243);"]
/// assert_eq!(3u8.wrapping_pow(6), 217);
#[doc = "assert_eq!(0_usize.wrapping_pow(0), 1);"]
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn wrapping_pow(self, exp: u32) -> Self {
let (a, _) = self.overflowing_pow(exp);
a
}
/// Calculates `self` + `rhs`.
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5usize.overflowing_add(2), (7, false));"]
#[doc = "assert_eq!(usize::MAX.overflowing_add(1), (0, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_add(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::add_with_overflow(self as u64, rhs as u64);
(a as Self, b)
}
/// Calculates `self` + `rhs` + `carry` and returns a tuple containing
/// the sum and the output carry (in that order).
///
/// Performs "ternary addition" of two integer operands and a carry-in
/// bit, and returns an output integer and a carry-out bit. This allows
/// chaining together multiple additions to create a wider addition, and
/// can be useful for bignum addition.
///
#[doc =
"This can be thought of as a 64-bit \"full adder\", in the electronics sense."]
///
/// If the input carry is false, this method is equivalent to
/// [`overflowing_add`](Self::overflowing_add), and the output carry is
/// equal to the overflow flag. Note that although carry and overflow
/// flags are similar for unsigned integers, they are different for
/// signed integers.
///
/// # Examples
///
/// ```
#[doc = "// 3 MAX (a = 3 \u{d7} 2^64 + 2^64 - 1)"]
#[doc = "// + 5 7 (b = 5 \u{d7} 2^64 + 7)"]
/// // ---------
#[doc = "// 9 6 (sum = 9 \u{d7} 2^64 + 6)"]
///
#[doc = "let (a1, a0): (usize, usize) = (3, usize::MAX);"]
#[doc = "let (b1, b0): (usize, usize) = (5, 7);"]
/// let carry0 = false;
///
/// let (sum0, carry1) = a0.carrying_add(b0, carry0);
/// assert_eq!(carry1, true);
/// let (sum1, carry2) = a1.carrying_add(b1, carry1);
/// assert_eq!(carry2, false);
///
/// assert_eq!((sum1, sum0), (9, 6));
/// ```
#[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
#[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue =
"152015")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_add(self, rhs: Self, carry: bool) -> (Self, bool) {
let (a, c1) = self.overflowing_add(rhs);
let (b, c2) = a.overflowing_add(carry as usize);
(b, unsafe { intrinsics::disjoint_bitor(c1, c2) })
}
/// Calculates `self` + `rhs` with a signed `rhs`.
///
/// Returns a tuple of the addition along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1usize.overflowing_add_signed(2), (3, false));"]
#[doc = "assert_eq!(1usize.overflowing_add_signed(-2), (usize::MAX, true));"]
#[doc = "assert_eq!((usize::MAX - 2).overflowing_add_signed(4), (1, true));"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_add_signed(self, rhs: isize) -> (Self, bool) {
let (res, overflowed) = self.overflowing_add(rhs as Self);
(res, overflowed ^ (rhs < 0))
}
/// Calculates `self` - `rhs`.
///
/// Returns a tuple of the subtraction along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5usize.overflowing_sub(2), (3, false));"]
#[doc = "assert_eq!(0usize.overflowing_sub(1), (usize::MAX, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_sub(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::sub_with_overflow(self as u64, rhs as u64);
(a as Self, b)
}
/// Calculates `self` − `rhs` − `borrow` and returns a tuple
/// containing the difference and the output borrow.
///
/// Performs "ternary subtraction" by subtracting both an integer
/// operand and a borrow-in bit from `self`, and returns an output
/// integer and a borrow-out bit. This allows chaining together multiple
/// subtractions to create a wider subtraction, and can be useful for
/// bignum subtraction.
///
/// # Examples
///
/// ```
#[doc = "// 9 6 (a = 9 \u{d7} 2^64 + 6)"]
#[doc = "// - 5 7 (b = 5 \u{d7} 2^64 + 7)"]
/// // ---------
#[doc = "// 3 MAX (diff = 3 \u{d7} 2^64 + 2^64 - 1)"]
///
#[doc = "let (a1, a0): (usize, usize) = (9, 6);"]
#[doc = "let (b1, b0): (usize, usize) = (5, 7);"]
/// let borrow0 = false;
///
/// let (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);
/// assert_eq!(borrow1, true);
/// let (diff1, borrow2) = a1.borrowing_sub(b1, borrow1);
/// assert_eq!(borrow2, false);
///
#[doc = "assert_eq!((diff1, diff0), (3, usize::MAX));"]
/// ```
#[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
#[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue =
"152015")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn borrowing_sub(self, rhs: Self, borrow: bool) -> (Self, bool) {
let (a, c1) = self.overflowing_sub(rhs);
let (b, c2) = a.overflowing_sub(borrow as usize);
(b, unsafe { intrinsics::disjoint_bitor(c1, c2) })
}
/// Calculates `self` - `rhs` with a signed `rhs`
///
/// Returns a tuple of the subtraction along with a boolean indicating
/// whether an arithmetic overflow would occur. If an overflow would
/// have occurred then the wrapped value is returned.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1usize.overflowing_sub_signed(2), (usize::MAX, true));"]
#[doc = "assert_eq!(1usize.overflowing_sub_signed(-2), (3, false));"]
#[doc = "assert_eq!((usize::MAX - 2).overflowing_sub_signed(-4), (1, true));"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_sub_signed(self, rhs: isize) -> (Self, bool) {
let (res, overflow) = self.overflowing_sub(rhs as Self);
(res, overflow ^ (rhs < 0))
}
/// Computes the absolute difference between `self` and `other`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100usize.abs_diff(80), 20usize);"]
#[doc = "assert_eq!(100usize.abs_diff(110), 10usize);"]
/// ```
#[stable(feature = "int_abs_diff", since = "1.60.0")]
#[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn abs_diff(self, other: Self) -> Self {
if size_of::<Self>() == 1 {
(self as i32).wrapping_sub(other as i32).unsigned_abs() as Self
} else { if self < other { other - self } else { self - other } }
}
/// Calculates the multiplication of `self` and `rhs`.
///
/// Returns a tuple of the multiplication along with a boolean
/// indicating whether an arithmetic overflow would occur. If an
/// overflow would have occurred then the wrapped value is returned.
///
/// If you want the *value* of the overflow, rather than just *whether*
/// an overflow occurred, see [`Self::carrying_mul`].
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `u32` is used.
///
/// ```
/// assert_eq!(5u32.overflowing_mul(2), (10, false));
/// assert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_mul(self, rhs: Self) -> (Self, bool) {
let (a, b) = intrinsics::mul_with_overflow(self as u64, rhs as u64);
(a as Self, b)
}
/// Calculates the "full multiplication" `self * rhs + carry`
/// without the possibility to overflow.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// Performs "long multiplication" which takes in an extra amount to add, and may return an
/// additional amount of overflow. This allows for chaining together multiple
/// multiplications to create "big integers" which represent larger values.
///
/// If you also need to add a value, then use [`Self::carrying_mul_add`].
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `u32` is used.
///
/// ```
/// assert_eq!(5u32.carrying_mul(2, 0), (10, 0));
/// assert_eq!(5u32.carrying_mul(2, 10), (20, 0));
/// assert_eq!(1_000_000_000u32.carrying_mul(10, 0), (1410065408, 2));
/// assert_eq!(1_000_000_000u32.carrying_mul(10, 10), (1410065418, 2));
#[doc =
"assert_eq!(usize::MAX.carrying_mul(usize::MAX, usize::MAX), (0, usize::MAX));"]
/// ```
///
/// This is the core operation needed for scalar multiplication when
/// implementing it for wider-than-native types.
///
/// ```
/// fn scalar_mul_eq(little_endian_digits: &mut Vec<u16>, multiplicand: u16) {
/// let mut carry = 0;
/// for d in little_endian_digits.iter_mut() {
/// (*d, carry) = d.carrying_mul(multiplicand, carry);
/// }
/// if carry != 0 {
/// little_endian_digits.push(carry);
/// }
/// }
///
/// let mut v = vec![10, 20];
/// scalar_mul_eq(&mut v, 3);
/// assert_eq!(v, [30, 60]);
///
/// assert_eq!(0x87654321_u64 * 0xFEED, 0x86D3D159E38D);
/// let mut v = vec![0x4321, 0x8765];
/// scalar_mul_eq(&mut v, 0xFEED);
/// assert_eq!(v, [0xE38D, 0xD159, 0x86D3]);
/// ```
///
/// If `carry` is zero, this is similar to [`overflowing_mul`](Self::overflowing_mul),
/// except that it gives the value of the overflow instead of just whether one happened:
///
/// ```
/// # #![allow(unused_features)]
/// #![feature(const_unsigned_bigint_helpers)]
/// let r = u8::carrying_mul(7, 13, 0);
/// assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(7, 13));
/// let r = u8::carrying_mul(13, 42, 0);
/// assert_eq!((r.0, r.1 != 0), u8::overflowing_mul(13, 42));
/// ```
///
/// The value of the first field in the returned tuple matches what you'd get
/// by combining the [`wrapping_mul`](Self::wrapping_mul) and
/// [`wrapping_add`](Self::wrapping_add) methods:
///
/// ```
/// # #![allow(unused_features)]
/// #![feature(const_unsigned_bigint_helpers)]
/// assert_eq!(
/// 789_u16.carrying_mul(456, 123).0,
/// 789_u16.wrapping_mul(456).wrapping_add(123),
/// );
/// ```
#[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
#[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue =
"152015")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_mul(self, rhs: Self, carry: Self) -> (Self, Self) {
Self::carrying_mul_add(self, rhs, carry, 0)
}
/// Calculates the "full multiplication" `self * rhs + carry + add`.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// This cannot overflow, as the double-width result has exactly enough
/// space for the largest possible result. This is equivalent to how, in
/// decimal, 9 × 9 + 9 + 9 = 81 + 18 = 99 = 9×10⁰ + 9×10¹ = 10² - 1.
///
/// Performs "long multiplication" which takes in an extra amount to add, and may return an
/// additional amount of overflow. This allows for chaining together multiple
/// multiplications to create "big integers" which represent larger values.
///
/// If you don't need the `add` part, then you can use [`Self::carrying_mul`] instead.
///
/// # Examples
///
/// Please note that this example is shared between integer types,
/// which explains why `u32` is used here.
///
/// ```
/// assert_eq!(5u32.carrying_mul_add(2, 0, 0), (10, 0));
/// assert_eq!(5u32.carrying_mul_add(2, 10, 10), (30, 0));
/// assert_eq!(1_000_000_000u32.carrying_mul_add(10, 0, 0), (1410065408, 2));
/// assert_eq!(1_000_000_000u32.carrying_mul_add(10, 10, 10), (1410065428, 2));
#[doc =
"assert_eq!(usize::MAX.carrying_mul_add(usize::MAX, usize::MAX, usize::MAX), (usize::MAX, usize::MAX));"]
/// ```
///
/// This is the core per-digit operation for "grade school" O(n²) multiplication.
///
/// Please note that this example is shared between integer types,
/// using `u8` for simplicity of the demonstration.
///
/// ```
/// fn quadratic_mul<const N: usize>(a: [u8; N], b: [u8; N]) -> [u8; N] {
/// let mut out = [0; N];
/// for j in 0..N {
/// let mut carry = 0;
/// for i in 0..(N - j) {
/// (out[j + i], carry) = u8::carrying_mul_add(a[i], b[j], out[j + i], carry);
/// }
/// }
/// out
/// }
///
/// // -1 * -1 == 1
/// assert_eq!(quadratic_mul([0xFF; 3], [0xFF; 3]), [1, 0, 0]);
///
/// assert_eq!(u32::wrapping_mul(0x9e3779b9, 0x7f4a7c15), 0xcffc982d);
/// assert_eq!(
/// quadratic_mul(u32::to_le_bytes(0x9e3779b9), u32::to_le_bytes(0x7f4a7c15)),
/// u32::to_le_bytes(0xcffc982d)
/// );
/// ```
#[stable(feature = "unsigned_bigint_helpers", since = "1.91.0")]
#[rustc_const_unstable(feature = "const_unsigned_bigint_helpers", issue =
"152015")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_mul_add(self, rhs: Self, carry: Self, add: Self)
-> (Self, Self) {
intrinsics::carrying_mul_add(self, rhs, carry, add)
}
/// Calculates the divisor when `self` is divided by `rhs`.
///
/// Returns a tuple of the divisor along with a boolean indicating
/// whether an arithmetic overflow would occur. Note that for unsigned
/// integers overflow never occurs, so the second value is always
/// `false`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5usize.overflowing_div(2), (2, false));"]
/// ```
#[inline(always)]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_overflowing_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[track_caller]
pub const fn overflowing_div(self, rhs: Self) -> (Self, bool) {
(self / rhs, false)
}
/// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`.
///
/// Returns a tuple of the divisor along with a boolean indicating
/// whether an arithmetic overflow would occur. Note that for unsigned
/// integers overflow never occurs, so the second value is always
/// `false`.
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self.overflowing_div(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5usize.overflowing_div_euclid(2), (2, false));"]
/// ```
#[inline(always)]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[track_caller]
pub const fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool) {
(self / rhs, false)
}
/// Calculates the remainder when `self` is divided by `rhs`.
///
/// Returns a tuple of the remainder after dividing along with a boolean
/// indicating whether an arithmetic overflow would occur. Note that for
/// unsigned integers overflow never occurs, so the second value is
/// always `false`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5usize.overflowing_rem(2), (1, false));"]
/// ```
#[inline(always)]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_overflowing_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[track_caller]
pub const fn overflowing_rem(self, rhs: Self) -> (Self, bool) {
(self % rhs, false)
}
/// Calculates the remainder `self.rem_euclid(rhs)` as if by Euclidean division.
///
/// Returns a tuple of the modulo after dividing along with a boolean
/// indicating whether an arithmetic overflow would occur. Note that for
/// unsigned integers overflow never occurs, so the second value is
/// always `false`.
/// Since, for the positive integers, all common
/// definitions of division are equal, this operation
/// is exactly equal to `self.overflowing_rem(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5usize.overflowing_rem_euclid(2), (1, false));"]
/// ```
#[inline(always)]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[track_caller]
pub const fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool) {
(self % rhs, false)
}
/// Negates self in an overflowing fashion.
///
/// Returns `!self + 1` using wrapping operations to return the value
/// that represents the negation of this unsigned value. Note that for
/// positive unsigned values overflow always occurs, but negating 0 does
/// not overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0usize.overflowing_neg(), (0, false));"]
#[doc = "assert_eq!(2usize.overflowing_neg(), (-2i32 as usize, true));"]
/// ```
#[inline(always)]
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn overflowing_neg(self) -> (Self, bool) {
((!self).wrapping_add(1), self != 0)
}
/// Shifts self left by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean
/// indicating whether the shift value was larger than or equal to the
/// number of bits. If the shift value is too large, then value is
/// masked (N-1) where N is the number of bits, and this value is then
/// used to perform the shift.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x1usize.overflowing_shl(4), (0x10, false));"]
#[doc = "assert_eq!(0x1usize.overflowing_shl(132), (0x10, true));"]
#[doc = "assert_eq!(0x10usize.overflowing_shl(63), (0, false));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_shl(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shl(rhs), rhs >= Self::BITS)
}
/// Shifts self right by `rhs` bits.
///
/// Returns a tuple of the shifted version of self along with a boolean
/// indicating whether the shift value was larger than or equal to the
/// number of bits. If the shift value is too large, then value is
/// masked (N-1) where N is the number of bits, and this value is then
/// used to perform the shift.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0x10usize.overflowing_shr(4), (0x1, false));"]
#[doc = "assert_eq!(0x10usize.overflowing_shr(132), (0x1, true));"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_wrapping_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn overflowing_shr(self, rhs: u32) -> (Self, bool) {
(self.wrapping_shr(rhs), rhs >= Self::BITS)
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// Returns a tuple of the exponentiation along with a bool indicating
/// whether an overflow happened.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3usize.overflowing_pow(5), (243, false));"]
#[doc = "assert_eq!(0_usize.overflowing_pow(0), (1, false));"]
/// assert_eq!(3u8.overflowing_pow(6), (217, true));
/// ```
#[stable(feature = "no_panic_pow", since = "1.34.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn overflowing_pow(self, mut exp: u32) -> (Self, bool) {
let mut base = self;
let mut acc: Self = 1;
let mut overflow = false;
let mut tmp_overflow;
if intrinsics::is_val_statically_known(base) && base.is_power_of_two() {
let k = base.ilog2();
let Some(shift) = k.checked_mul(exp) else { return (0, true) };
return ((1 as Self).unbounded_shl(shift), shift >= Self::BITS)
}
if exp == 0 { return (1, false); }
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 {
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
}
exp /= 2;
(base, tmp_overflow) = base.overflowing_mul(base);
overflow |= tmp_overflow;
}
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
return (acc, overflow);
}
loop {
if (exp & 1) == 1 {
(acc, tmp_overflow) = acc.overflowing_mul(base);
overflow |= tmp_overflow;
if exp == 1 { return (acc, overflow); }
}
exp /= 2;
(base, tmp_overflow) = base.overflowing_mul(base);
overflow |= tmp_overflow;
}
}
/// Raises self to the power of `exp`, using exponentiation by squaring.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2usize.pow(5), 32);"]
#[doc = "assert_eq!(0_usize.pow(0), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn pow(self, exp: u32) -> Self {
if intrinsics::overflow_checks() {
self.strict_pow(exp)
} else { self.wrapping_pow(exp) }
}
/// Returns the square root of the number, rounded down.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10usize.isqrt(), 3);"]
/// ```
#[stable(feature = "isqrt", since = "1.84.0")]
#[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn isqrt(self) -> Self {
let result = imp::int_sqrt::u64(self as u64) as Self;
unsafe {
const MAX_RESULT: usize = imp::int_sqrt::u64(<u64>::MAX) as usize;
crate::hint::assert_unchecked(result <= MAX_RESULT)
}
if self >= 1 { unsafe { crate::hint::assert_unchecked(result >= 1) } }
unsafe {
crate::hint::assert_unchecked(result.unchecked_mul(result) <= self);
crate::hint::assert_unchecked(result <= self);
}
result
}
/// Performs Euclidean division.
///
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self / rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7usize.div_euclid(4), 1); // or any other integer type"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Calculates the least remainder of `self` when divided by
/// `rhs`.
///
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self % rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7usize.rem_euclid(4), 3); // or any other integer type"]
/// ```
#[doc(alias = "modulo", alias = "mod")]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
///
/// This is the same as performing `self / rhs` for all unsigned integers.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "assert_eq!(7_usize.div_floor(4), 1);"]
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn div_floor(self, rhs: Self) -> Self { self / rhs }
/// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7_usize.div_ceil(4), 2);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_ceil(self, rhs: Self) -> Self {
let d = self / rhs;
let r = self % rhs;
if r > 0 { d + 1 } else { d }
}
/// Calculates the smallest value greater than or equal to `self` that
/// is a multiple of `rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// On overflow, this function will panic if overflow checks are enabled (default in debug
/// mode) and wrap if overflow checks are disabled (default in release mode).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(16_usize.next_multiple_of(8), 16);"]
#[doc = "assert_eq!(23_usize.next_multiple_of(8), 24);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_multiple_of(self, rhs: Self) -> Self {
match self % rhs { 0 => self, r => self + (rhs - r), }
}
/// Calculates the smallest value greater than or equal to `self` that
/// is a multiple of `rhs`. Returns `None` if `rhs` is zero or the
/// operation would result in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(16_usize.checked_next_multiple_of(8), Some(16));"]
#[doc = "assert_eq!(23_usize.checked_next_multiple_of(8), Some(24));"]
#[doc = "assert_eq!(1_usize.checked_next_multiple_of(0), None);"]
#[doc = "assert_eq!(usize::MAX.checked_next_multiple_of(2), None);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
match match self.checked_rem(rhs) { Some(x) => x, None => return None, } {
0 => Some(self),
r => self.checked_add(rhs - r),
}
}
/// Returns `true` if `self` is an integer multiple of `rhs`, and false otherwise.
///
/// This function is equivalent to `self % rhs == 0`, except that it will not panic
/// for `rhs == 0`. Instead, `0.is_multiple_of(0) == true`, and for any non-zero `n`,
/// `n.is_multiple_of(0) == false`.
///
/// # Examples
///
/// ```
#[doc = "assert!(6_usize.is_multiple_of(2));"]
#[doc = "assert!(!5_usize.is_multiple_of(2));"]
///
#[doc = "assert!(0_usize.is_multiple_of(0));"]
#[doc = "assert!(!6_usize.is_multiple_of(0));"]
/// ```
#[stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
#[rustc_const_stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
#[must_use]
#[inline]
pub const fn is_multiple_of(self, rhs: Self) -> bool {
match rhs { 0 => self == 0, _ => self % rhs == 0, }
}
/// Returns `true` if and only if `self == 2^k` for some unsigned integer `k`.
///
/// # Examples
///
/// ```
#[doc = "assert!(16usize.is_power_of_two());"]
#[doc = "assert!(!10usize.is_power_of_two());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
#[inline(always)]
pub const fn is_power_of_two(self) -> bool { self.count_ones() == 1 }
#[inline]
const fn one_less_than_next_power_of_two(self) -> Self {
if self <= 1 { return 0; }
let p = self - 1;
let z = unsafe { intrinsics::ctlz_nonzero(p) };
<usize>::MAX >> z
}
/// Returns the smallest power of two greater than or equal to `self`.
///
/// When return value overflows (i.e., `self > (1 << (N-1))` for type
/// `uN`), it panics in debug mode and the return value is wrapped to 0 in
/// release mode (the only situation in which this method can return 0).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2usize.next_power_of_two(), 2);"]
#[doc = "assert_eq!(3usize.next_power_of_two(), 4);"]
#[doc = "assert_eq!(0usize.next_power_of_two(), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_power_of_two(self) -> Self {
self.one_less_than_next_power_of_two() + 1
}
/// Returns the smallest power of two greater than or equal to `self`. If
/// the next power of two is greater than the type's maximum value,
/// `None` is returned, otherwise the power of two is wrapped in `Some`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2usize.checked_next_power_of_two(), Some(2));"]
#[doc = "assert_eq!(3usize.checked_next_power_of_two(), Some(4));"]
#[doc = "assert_eq!(usize::MAX.checked_next_power_of_two(), None);"]
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn checked_next_power_of_two(self) -> Option<Self> {
self.one_less_than_next_power_of_two().checked_add(1)
}
/// Returns the smallest power of two greater than or equal to `n`. If
/// the next power of two is greater than the type's maximum value,
/// the return value is wrapped to `0`.
///
/// # Examples
///
/// ```
/// #![feature(wrapping_next_power_of_two)]
///
#[doc = "assert_eq!(2usize.wrapping_next_power_of_two(), 2);"]
#[doc = "assert_eq!(3usize.wrapping_next_power_of_two(), 4);"]
#[doc = "assert_eq!(usize::MAX.wrapping_next_power_of_two(), 0);"]
/// ```
#[inline]
#[unstable(feature = "wrapping_next_power_of_two", issue = "32463", reason =
"needs decision on wrapping behavior")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn wrapping_next_power_of_two(self) -> Self {
self.one_less_than_next_power_of_two().wrapping_add(1)
}
/// Returns the memory representation of this integer as a byte array in
/// big-endian (network) byte order.
///
#[doc =
"
**Note**: This function returns an array of length 2, 4 or 8 bytes
depending on the target pointer size.
"]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234567890123456usize.to_be_bytes();"]
#[doc =
"assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
self.to_be().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// little-endian byte order.
///
#[doc =
"
**Note**: This function returns an array of length 2, 4 or 8 bytes
depending on the target pointer size.
"]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234567890123456usize.to_le_bytes();"]
#[doc =
"assert_eq!(bytes, [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
self.to_le().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code
/// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
/// instead.
///
#[doc =
"
**Note**: This function returns an array of length 2, 4 or 8 bytes
depending on the target pointer size.
"]
///
/// [`to_be_bytes`]: Self::to_be_bytes
/// [`to_le_bytes`]: Self::to_le_bytes
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234567890123456usize.to_ne_bytes();"]
/// assert_eq!(
/// bytes,
/// if cfg!(target_endian = "big") {
#[doc = " [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]"]
/// } else {
#[doc = " [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]"]
/// }
/// );
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[allow(unnecessary_transmutes)]
#[inline]
pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
unsafe { mem::transmute(self) }
}
/// Creates a native endian integer value from its representation
/// as a byte array in big endian.
///
#[doc =
"
**Note**: This function takes an array of length 2, 4 or 8 bytes
depending on the target pointer size.
"]
///
/// # Examples
///
/// ```
#[doc =
"let value = usize::from_be_bytes([0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]);"]
#[doc = "assert_eq!(value, 0x1234567890123456);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_be_usize(input: &mut &[u8]) -> usize {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<usize>());"]
/// *input = rest;
#[doc = " usize::from_be_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_be(Self::from_ne_bytes(bytes))
}
/// Creates a native endian integer value from its representation
/// as a byte array in little endian.
///
#[doc =
"
**Note**: This function takes an array of length 2, 4 or 8 bytes
depending on the target pointer size.
"]
///
/// # Examples
///
/// ```
#[doc =
"let value = usize::from_le_bytes([0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);"]
#[doc = "assert_eq!(value, 0x1234567890123456);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_le_usize(input: &mut &[u8]) -> usize {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<usize>());"]
/// *input = rest;
#[doc = " usize::from_le_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_le(Self::from_ne_bytes(bytes))
}
/// Creates a native endian integer value from its memory representation
/// as a byte array in native endianness.
///
/// As the target platform's native endianness is used, portable code
/// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
/// appropriate instead.
///
/// [`from_be_bytes`]: Self::from_be_bytes
/// [`from_le_bytes`]: Self::from_le_bytes
///
#[doc =
"
**Note**: This function takes an array of length 2, 4 or 8 bytes
depending on the target pointer size.
"]
///
/// # Examples
///
/// ```
#[doc = "let value = usize::from_ne_bytes(if cfg!(target_endian = \"big\") {"]
#[doc = " [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]"]
/// } else {
#[doc = " [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]"]
/// });
#[doc = "assert_eq!(value, 0x1234567890123456);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_ne_usize(input: &mut &[u8]) -> usize {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<usize>());"]
/// *input = rest;
#[doc = " usize::from_ne_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use]
#[inline]
pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
unsafe { mem::transmute(bytes) }
}
/// New code should prefer to use
#[doc = "[`usize::MIN`] instead."]
///
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_promotable]
#[inline(always)]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MIN` associated constant on this type")]
#[rustc_diagnostic_item = "usize_legacy_fn_min_value"]
pub const fn min_value() -> Self { Self::MIN }
/// New code should prefer to use
#[doc = "[`usize::MAX`] instead."]
///
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_promotable]
#[inline(always)]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MAX` associated constant on this type")]
#[rustc_diagnostic_item = "usize_legacy_fn_max_value"]
pub const fn max_value() -> Self { Self::MAX }
/// Truncate an integer to an integer of the same size or smaller, preserving the least
/// significant bits.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u8, 120usize.truncate());"]
/// assert_eq!(120u8, 376u32.truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
/// instead of truncating.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u8, 120usize.saturating_truncate());"]
/// assert_eq!(255u8, 376u32.saturating_truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn saturating_truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_saturating_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
/// is outside the bounds of the smaller type.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(Some(120u8), 120usize.checked_truncate());"]
/// assert_eq!(None, 376u32.checked_truncate::<u8>());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn checked_truncate<Target>(self) -> Option<Target> where
Self: [const] traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_checked_truncate(self)
}
/// Widen to an integer of the same size or larger, preserving its value.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u128, 120u8.widen());"]
/// ```
#[must_use =
"this returns the widened value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn widen<Target>(self) -> Target where Self: [const]
traits::WidenTarget<Target> {
traits::WidenTarget::internal_widen(self)
}
/// Converts `self` to the target integer type, saturating at the numeric
/// bounds instead of overflowing.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(255u8, usize::MAX.saturating_cast());"]
#[doc = "assert_eq!(127i8, usize::MAX.saturating_cast());"]
#[doc = "assert_eq!(42i8, 42usize.saturating_cast());"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn saturating_cast<T: [const] BoundedCastFromInt<Self>>(self) -> T {
T::saturating_cast_from(self)
}
/// Converts `self` to the target integer type, wrapping around at the
/// boundary of the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(255u8, usize::MAX.wrapping_cast());"]
#[doc = "assert_eq!(42i8, 42usize.wrapping_cast());"]
#[doc = "assert_eq!(usize::MAX as i8, usize::MAX.wrapping_cast());"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn wrapping_cast<T: [const] BoundedCastFromInt<Self>>(self) -> T {
T::wrapping_cast_from(self)
}
/// Converts `self` to the target integer type, returning `None` if the value
/// is not representable by the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(Some(42u8), 42usize.checked_cast());"]
#[doc = "assert_eq!(128usize.checked_cast::<i8>(), None);"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const fn checked_cast<T: [const] CheckedCastFromInt<Self>>(self)
-> Option<T> {
T::checked_cast_from(self)
}
/// Converts `self` to the target integer type, panicking if the value
/// is not representable by the target type.
///
/// # Panics
///
/// This function will panic if the value is not representable by the target type.
///
/// # Examples
///
/// ```
/// #![feature(integer_casts)]
#[doc = "assert_eq!(42u8, 42usize.strict_cast());"]
/// ```
///
/// The following will panic:
///
/// ```should_panic
/// #![feature(integer_casts)]
#[doc = "let _ = 128usize.strict_cast::<i8>();"]
/// ```
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
#[track_caller]
pub const fn strict_cast<T: [const] CheckedCastFromInt<Self>>(self) -> T {
T::strict_cast_from(self)
}
/// Converts `self` to the target integer type, assuming the value is
/// representable by the target type.
///
/// # Safety
///
/// This results in undefined behavior if the integer value of `self` is bigger than `T::MAX`,
/// or smaller than `T::MIN`, where `T` is the target type.
#[must_use = "this returns the cast result and does not modify the original"]
#[unstable(feature = "integer_casts", issue = "157388")]
#[rustc_const_unstable(feature = "integer_casts", issue = "157388")]
#[inline(always)]
pub const unsafe fn unchecked_cast<T: [const] CheckedCastFromInt<Self>>(self)
-> T {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(in_bounds: bool) {
if !in_bounds {
let msg =
"unsafe precondition(s) violated: usize::unchecked_cast must fit in the target type\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check({
let cast_val = self.checked_cast::<T>();
let ret = cast_val.is_some();
core::mem::forget(cast_val);
ret
});
}
};
unsafe { T::unchecked_cast_from(self) }
}uint_impl! {
1450Self = usize,
1451 ActualT = u64,
1452 SignedT = isize,
1453 BITS = 64,
1454 BITS_MINUS_ONE = 63,
1455 MAX = 18446744073709551615,
1456 rot = 12,
1457 rot_op = "0xaa00000000006e1",
1458 rot_result = "0x6e10aa",
1459 fsh_op = "0x2fe78e45983acd98",
1460 fshl_result = "0x6e12fe",
1461 fshr_result = "0x6e12fe78e45983ac",
1462 clmul_lhs = "0x7890123456789012",
1463 clmul_rhs = "0xdd358416f52ecd34",
1464 clmul_result = "0xa6299579b980928",
1465 swap_op = "0x1234567890123456",
1466 swapped = "0x5634129078563412",
1467 reversed = "0x6a2c48091e6a2c48",
1468 le_bytes = "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
1469 be_bytes = "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
1470 to_xe_bytes_doc = usize_isize_to_xe_bytes_doc!(),
1471 from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(),
1472 bound_condition = " on 64-bit targets",
1473 }1474/// Calculates the midpoint (average) between `self` and `rhs`.
///
/// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
/// sufficiently-large unsigned integral type. This implies that the result is
/// always rounded towards zero and that no overflow will ever occur.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(0usize.midpoint(4), 2);"]
#[doc = "assert_eq!(1usize.midpoint(4), 2);"]
/// ```
#[stable(feature = "num_midpoint", since = "1.85.0")]
#[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[doc(alias = "average_floor")]
#[doc(alias = "average")]
#[inline]
pub const fn midpoint(self, rhs: usize) -> usize {
((self as u128 + rhs as u128) / 2) as usize
}midpoint_impl! { usize, u128, unsigned }1475/// Calculates the "full carryless multiplication" without the possibility to overflow.
///
/// This returns the low-order (wrapping) bits and the high-order (overflow) bits
/// of the result as two separate values, in that order.
///
/// # Examples
///
/// Please note that this example is shared among integer types, which is why `u8` is used.
///
/// ```
/// #![feature(uint_carryless_mul)]
///
/// assert_eq!(0b1000_0000u8.carrying_carryless_mul(0b1000_0000, 0b0000), (0, 0b0100_0000));
/// assert_eq!(0b1000_0000u8.carrying_carryless_mul(0b1000_0000, 0b1111), (0b1111, 0b0100_0000));
#[doc =
"assert_eq!(usize::MAX.carrying_carryless_mul(usize::MAX, usize::MAX), (!(usize::MAX / 3), usize::MAX / 3));"]
/// ```
#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
#[doc(alias = "clmul")]
#[unstable(feature = "uint_carryless_mul", issue = "152080")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn carrying_carryless_mul(self, rhs: Self, carry: Self)
-> (Self, Self) {
let p = (self as u128).carryless_mul(rhs as u128);
let lo = (p as usize);
let hi = (p >> Self::BITS) as usize;
(lo ^ carry, hi)
}carrying_carryless_mul_impl! { usize, u128 }1476}
14771478impl usize {
1479/// Returns an `usize` where every byte is equal to `x`.
1480#[inline]
1481pub(crate) const fn repeat_u8(x: u8) -> usize {
1482usize::from_ne_bytes([x; size_of::<usize>()])
1483 }
14841485/// Returns an `usize` where every byte pair is equal to `x`.
1486#[inline]
1487pub(crate) const fn repeat_u16(x: u16) -> usize {
1488let mut r = 0usize;
1489let mut i = 0;
1490while i < size_of::<usize>() {
1491// Use `wrapping_shl` to make it work on targets with 16-bit `usize`
1492r = r.wrapping_shl(16) | (x as usize);
1493 i += 2;
1494 }
1495r1496 }
1497}
14981499/// A classification of floating point numbers.
1500///
1501/// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
1502/// their documentation for more.
1503///
1504/// # Examples
1505///
1506/// ```
1507/// use std::num::FpCategory;
1508///
1509/// let num = 12.4_f32;
1510/// let inf = f32::INFINITY;
1511/// let zero = 0f32;
1512/// let sub: f32 = 1.1754942e-38;
1513/// let nan = f32::NAN;
1514///
1515/// assert_eq!(num.classify(), FpCategory::Normal);
1516/// assert_eq!(inf.classify(), FpCategory::Infinite);
1517/// assert_eq!(zero.classify(), FpCategory::Zero);
1518/// assert_eq!(sub.classify(), FpCategory::Subnormal);
1519/// assert_eq!(nan.classify(), FpCategory::Nan);
1520/// ```
1521#[derive(#[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl crate::marker::Copy for FpCategory { }Copy, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl crate::clone::Clone for FpCategory {
#[inline]
fn clone(&self) -> FpCategory { *self }
}Clone, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl crate::cmp::PartialEq for FpCategory {
#[inline]
fn eq(&self, other: &FpCategory) -> bool {
let __self_discr = crate::intrinsics::discriminant_value(self);
let __arg1_discr = crate::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl crate::cmp::Eq for FpCategory {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl crate::fmt::Debug for FpCategory {
#[inline]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
crate::fmt::Formatter::write_str(f,
match self {
FpCategory::Nan => "Nan",
FpCategory::Infinite => "Infinite",
FpCategory::Zero => "Zero",
FpCategory::Subnormal => "Subnormal",
FpCategory::Normal => "Normal",
})
}
}Debug)]
1522#[stable(feature = "rust1", since = "1.0.0")]
1523pub enum FpCategory {
1524/// NaN (not a number): this value results from calculations like `(-1.0).sqrt()`.
1525 ///
1526 /// See [the documentation for `f32`](f32) for more information on the unusual properties
1527 /// of NaN.
1528#[stable(feature = "rust1", since = "1.0.0")]
1529Nan,
15301531/// Positive or negative infinity, which often results from dividing a nonzero number
1532 /// by zero.
1533#[stable(feature = "rust1", since = "1.0.0")]
1534Infinite,
15351536/// Positive or negative zero.
1537 ///
1538 /// See [the documentation for `f32`](f32) for more information on the signedness of zeroes.
1539#[stable(feature = "rust1", since = "1.0.0")]
1540Zero,
15411542/// “Subnormal” or “denormal” floating point representation (less precise, relative to
1543 /// their magnitude, than [`Normal`]).
1544 ///
1545 /// Subnormal numbers are larger in magnitude than [`Zero`] but smaller in magnitude than all
1546 /// [`Normal`] numbers.
1547 ///
1548 /// [`Normal`]: Self::Normal
1549 /// [`Zero`]: Self::Zero
1550#[stable(feature = "rust1", since = "1.0.0")]
1551Subnormal,
15521553/// A regular floating point number, not any of the exceptional categories.
1554 ///
1555 /// The smallest positive normal numbers are [`f32::MIN_POSITIVE`] and [`f64::MIN_POSITIVE`],
1556 /// and the largest positive normal numbers are [`f32::MAX`] and [`f64::MAX`]. (Unlike signed
1557 /// integers, floating point numbers are symmetric in their range, so negating any of these
1558 /// constants will produce their negative counterpart.)
1559#[stable(feature = "rust1", since = "1.0.0")]
1560Normal,
1561}
15621563/// Determines if a string of text of that length of that radix could be guaranteed to be
1564/// stored in the given type T.
1565/// Note that if the radix is known to the compiler, it is just the check of digits.len that
1566/// is done at runtime.
1567#[doc(hidden)]
1568#[inline(always)]
1569#[unstable(issue = "none", feature = "std_internals")]
1570pub const fn can_not_overflow<T>(radix: u32, is_signed_ty: bool, digits: &[u8]) -> bool {
1571radix <= 16 && digits.len() <= size_of::<T>() * 2 - is_signed_tyas usize1572}
15731574#[cfg_attr(not(panic = "immediate-abort"), inline(never))]
1575#[cfg_attr(panic = "immediate-abort", inline)]
1576#[cold]
1577#[track_caller]
1578const fn from_ascii_radix_panic(radix: u32) -> ! {
1579{
#[rustc_allow_const_fn_unstable(const_eval_select)]
#[inline(always)]
#[track_caller]
const fn do_panic(radix: u32) -> ! {
{
#[inline]
#[track_caller]
fn runtime(radix: u32) -> ! {
{
{
crate::panicking::panic_fmt(format_args!("from_ascii_radix: radix must lie in the range `[2, 36]` - found {0}",
radix));
}
}
}
#[inline]
#[track_caller]
const fn compiletime(radix: u32) -> ! {
let _ = radix;
{
{
crate::panicking::panic_fmt(format_args!("from_ascii_radix: radix must lie in the range `[2, 36]`"));
}
}
}
const_eval_select((radix,), compiletime, runtime)
}
}
do_panic(radix)
}const_panic!(
1580"from_ascii_radix: radix must lie in the range `[2, 36]`",
1581"from_ascii_radix: radix must lie in the range `[2, 36]` - found {radix}",
1582 radix: u32 = radix,
1583 )1584}
15851586macro_rules!from_str_int_impl {
1587 ($signedness:ident $($int_ty:ty)+) => {$(
1588#[stable(feature = "rust1", since = "1.0.0")]
1589 #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1590const impl FromStr for $int_ty {
1591type Err = ParseIntError;
15921593/// Parses an integer from a string slice with decimal digits.
1594 ///
1595 /// The characters are expected to be an optional
1596#[doc = sign_dependent_expr!{
1597$signedness ?
1598if signed {
1599" `+` or `-` "
1600}
1601if unsigned {
1602" `+` "
1603}
1604 }]
1605/// sign followed by only digits. Leading and trailing non-digit characters (including
1606 /// whitespace) represent an error. Underscores (which are accepted in Rust literals)
1607 /// also represent an error.
1608 ///
1609 /// # See also
1610 /// For parsing numbers in other bases, such as binary or hexadecimal,
1611 /// see [`from_str_radix`][Self::from_str_radix].
1612 ///
1613 /// # Examples
1614 ///
1615 /// ```
1616 /// use std::str::FromStr;
1617 ///
1618#[doc = concat!("assert_eq!(", stringify!($int_ty), "::from_str(\"+10\"), Ok(10));")]
1619/// ```
1620 /// Trailing space returns error:
1621 /// ```
1622 /// # use std::str::FromStr;
1623 /// #
1624#[doc = concat!("assert!(", stringify!($int_ty), "::from_str(\"1 \").is_err());")]
1625/// ```
1626#[inline]
1627fn from_str(src: &str) -> Result<$int_ty, ParseIntError> {
1628 <$int_ty>::from_str_radix(src, 10)
1629 }
1630 }
16311632impl $int_ty {
1633/// Parses an integer from a string slice with digits in a given base.
1634 ///
1635 /// The string is expected to be an optional
1636#[doc = sign_dependent_expr!{
1637$signedness ?
1638if signed {
1639" `+` or `-` "
1640}
1641if unsigned {
1642" `+` "
1643}
1644 }]
1645/// sign followed by only digits. Leading and trailing non-digit characters (including
1646 /// whitespace) represent an error. Underscores (which are accepted in Rust literals)
1647 /// also represent an error.
1648 ///
1649 /// Digits are a subset of these characters, depending on `radix`:
1650 /// * `0-9`
1651 /// * `a-z`
1652 /// * `A-Z`
1653 ///
1654 /// # Panics
1655 ///
1656 /// This function panics if `radix` is not in the range from 2 to 36.
1657 ///
1658 /// # See also
1659 /// If the string to be parsed is in base 10 (decimal),
1660 /// [`from_str`] or [`str::parse`] can also be used.
1661 ///
1662// FIXME(#122566): These HTML links work around a rustdoc-json test failure.
1663/// [`from_str`]: #method.from_str
1664 /// [`str::parse`]: primitive.str.html#method.parse
1665 ///
1666 /// # Examples
1667 ///
1668 /// ```
1669#[doc = concat!("assert_eq!(", stringify!($int_ty), "::from_str_radix(\"A\", 16), Ok(10));")]
1670/// ```
1671 /// Trailing space returns error:
1672 /// ```
1673#[doc = concat!("assert!(", stringify!($int_ty), "::from_str_radix(\"1 \", 10).is_err());")]
1674/// ```
1675#[stable(feature = "rust1", since = "1.0.0")]
1676 #[rustc_const_stable(feature = "const_int_from_str", since = "1.82.0")]
1677 #[inline]
1678pub const fn from_str_radix(src: &str, radix: u32) -> Result<$int_ty, ParseIntError> {
1679 <$int_ty>::from_ascii_radix(src.as_bytes(), radix)
1680 }
16811682/// Parses an integer from an ASCII-byte slice with decimal digits.
1683 ///
1684 /// The characters are expected to be an optional
1685#[doc = sign_dependent_expr!{
1686$signedness ?
1687if signed {
1688" `+` or `-` "
1689}
1690if unsigned {
1691" `+` "
1692}
1693 }]
1694/// sign followed by only digits. Leading and trailing non-digit characters (including
1695 /// whitespace) represent an error. Underscores (which are accepted in Rust literals)
1696 /// also represent an error.
1697 ///
1698 /// # Examples
1699 ///
1700 /// ```
1701 /// #![feature(int_from_ascii)]
1702 ///
1703#[doc = concat!("assert_eq!(", stringify!($int_ty), "::from_ascii(b\"+10\"), Ok(10));")]
1704/// ```
1705 /// Trailing space returns error:
1706 /// ```
1707 /// # #![feature(int_from_ascii)]
1708 /// #
1709#[doc = concat!("assert!(", stringify!($int_ty), "::from_ascii(b\"1 \").is_err());")]
1710/// ```
1711#[unstable(feature = "int_from_ascii", issue = "134821")]
1712 #[inline]
1713pub const fn from_ascii(src: &[u8]) -> Result<$int_ty, ParseIntError> {
1714 <$int_ty>::from_ascii_radix(src, 10)
1715 }
17161717/// Parses an integer from an ASCII-byte slice with digits in a given base.
1718 ///
1719 /// The characters are expected to be an optional
1720#[doc = sign_dependent_expr!{
1721$signedness ?
1722if signed {
1723" `+` or `-` "
1724}
1725if unsigned {
1726" `+` "
1727}
1728 }]
1729/// sign followed by only digits. Leading and trailing non-digit characters (including
1730 /// whitespace) represent an error. Underscores (which are accepted in Rust literals)
1731 /// also represent an error.
1732 ///
1733 /// Digits are a subset of these characters, depending on `radix`:
1734 /// * `0-9`
1735 /// * `a-z`
1736 /// * `A-Z`
1737 ///
1738 /// # Panics
1739 ///
1740 /// This function panics if `radix` is not in the range from 2 to 36.
1741 ///
1742 /// # Examples
1743 ///
1744 /// ```
1745 /// #![feature(int_from_ascii)]
1746 ///
1747#[doc = concat!("assert_eq!(", stringify!($int_ty), "::from_ascii_radix(b\"A\", 16), Ok(10));")]
1748/// ```
1749 /// Trailing space returns error:
1750 /// ```
1751 /// # #![feature(int_from_ascii)]
1752 /// #
1753#[doc = concat!("assert!(", stringify!($int_ty), "::from_ascii_radix(b\"1 \", 10).is_err());")]
1754/// ```
1755#[unstable(feature = "int_from_ascii", issue = "134821")]
1756 #[inline]
1757pub const fn from_ascii_radix(src: &[u8], radix: u32) -> Result<$int_ty, ParseIntError> {
1758use self::IntErrorKind::*;
1759use self::ParseIntError as PIE;
17601761if 2 > radix || radix > 36 {
1762 from_ascii_radix_panic(radix);
1763 }
17641765if src.is_empty() {
1766return Err(PIE { kind: Empty });
1767 }
17681769#[allow(unused_comparisons)]
1770let is_signed_ty = 0 > <$int_ty>::MIN;
17711772let (is_positive, mut digits) = match src {
1773 [b'+' | b'-'] => {
1774return Err(PIE { kind: InvalidDigit });
1775 }
1776 [b'+', rest @ ..] => (true, rest),
1777 [b'-', rest @ ..] if is_signed_ty => (false, rest),
1778_ => (true, src),
1779 };
17801781let mut result = 0;
17821783macro_rules! unwrap_or_PIE {
1784 ($option:expr, $kind:ident) => {
1785match $option {
1786Some(value) => value,
1787None => return Err(PIE { kind: $kind }),
1788 }
1789 };
1790 }
17911792if can_not_overflow::<$int_ty>(radix, is_signed_ty, digits) {
1793// If the len of the str is short compared to the range of the type
1794 // we are parsing into, then we can be certain that an overflow will not occur.
1795 // This bound is when `radix.pow(digits.len()) - 1 <= T::MAX` but the condition
1796 // above is a faster (conservative) approximation of this.
1797 //
1798 // Consider radix 16 as it has the highest information density per digit and will thus overflow the earliest:
1799 // `u8::MAX` is `ff` - any str of len 2 is guaranteed to not overflow.
1800 // `i8::MAX` is `7f` - only a str of len 1 is guaranteed to not overflow.
1801macro_rules! run_unchecked_loop {
1802 ($unchecked_additive_op:tt) => {{
1803while let [c, rest @ ..] = digits {
1804 result = result * (radix as $int_ty);
1805let x = unwrap_or_PIE!((*c as char).to_digit(radix), InvalidDigit);
1806 result = result $unchecked_additive_op (x as $int_ty);
1807 digits = rest;
1808 }
1809 }};
1810 }
1811if is_positive {
1812run_unchecked_loop!(+)
1813 } else {
1814run_unchecked_loop!(-)
1815 };
1816 } else {
1817macro_rules! run_checked_loop {
1818 ($checked_additive_op:ident, $overflow_err:ident) => {{
1819while let [c, rest @ ..] = digits {
1820// When `radix` is passed in as a literal, rather than doing a slow `imul`
1821 // the compiler can use shifts if `radix` can be expressed as a
1822 // sum of powers of 2 (x*10 can be written as x*8 + x*2).
1823 // When the compiler can't use these optimisations,
1824 // the latency of the multiplication can be hidden by issuing it
1825 // before the result is needed to improve performance on
1826 // modern out-of-order CPU as multiplication here is slower
1827 // than the other instructions, we can get the end result faster
1828 // doing multiplication first and let the CPU spends other cycles
1829 // doing other computation and get multiplication result later.
1830let mul = result.checked_mul(radix as $int_ty);
1831let x = unwrap_or_PIE!((*c as char).to_digit(radix), InvalidDigit) as $int_ty;
1832 result = unwrap_or_PIE!(mul, $overflow_err);
1833 result = unwrap_or_PIE!(<$int_ty>::$checked_additive_op(result, x), $overflow_err);
1834 digits = rest;
1835 }
1836 }};
1837 }
1838if is_positive {
1839run_checked_loop!(checked_add, PosOverflow)
1840 } else {
1841run_checked_loop!(checked_sub, NegOverflow)
1842 };
1843 }
1844Ok(result)
1845 }
1846 }
1847 )*}
1848}
18491850#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
const impl FromStr for i128 {
type Err = ParseIntError;
/// Parses an integer from a string slice with decimal digits.
///
/// The characters are expected to be an optional
#[doc = " `+` or `-` "]
/// sign followed by only digits. Leading and trailing non-digit characters (including
/// whitespace) represent an error. Underscores (which are accepted in Rust literals)
/// also represent an error.
///
/// # See also
/// For parsing numbers in other bases, such as binary or hexadecimal,
/// see [`from_str_radix`][Self::from_str_radix].
///
/// # Examples
///
/// ```
/// use std::str::FromStr;
///
#[doc = "assert_eq!(i128::from_str(\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # use std::str::FromStr;
/// #
#[doc = "assert!(i128::from_str(\"1 \").is_err());"]
/// ```
#[inline]
fn from_str(src: &str) -> Result<i128, ParseIntError> {
<i128>::from_str_radix(src, 10)
}
}
impl i128 {
/// Parses an integer from a string slice with digits in a given base.
///
/// The string is expected to be an optional
#[doc = " `+` or `-` "]
/// sign followed by only digits. Leading and trailing non-digit characters (including
/// whitespace) represent an error. Underscores (which are accepted in Rust literals)
/// also represent an error.
///
/// Digits are a subset of these characters, depending on `radix`:
/// * `0-9`
/// * `a-z`
/// * `A-Z`
///
/// # Panics
///
/// This function panics if `radix` is not in the range from 2 to 36.
///
/// # See also
/// If the string to be parsed is in base 10 (decimal),
/// [`from_str`] or [`str::parse`] can also be used.
///
/// [`from_str`]: #method.from_str
/// [`str::parse`]: primitive.str.html#method.parse
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i128::from_str_radix(\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
#[doc = "assert!(i128::from_str_radix(\"1 \", 10).is_err());"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_from_str", since = "1.82.0")]
#[inline]
pub const fn from_str_radix(src: &str, radix: u32)
-> Result<i128, ParseIntError> {
<i128>::from_ascii_radix(src.as_bytes(), radix)
}
/// Parses an integer from an ASCII-byte slice with decimal digits.
///
/// The characters are expected to be an optional
#[doc = " `+` or `-` "]
/// sign followed by only digits. Leading and trailing non-digit characters (including
/// whitespace) represent an error. Underscores (which are accepted in Rust literals)
/// also represent an error.
///
/// # Examples
///
/// ```
/// #![feature(int_from_ascii)]
///
#[doc = "assert_eq!(i128::from_ascii(b\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(i128::from_ascii(b\"1 \").is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[inline]
pub const fn from_ascii(src: &[u8]) -> Result<i128, ParseIntError> {
<i128>::from_ascii_radix(src, 10)
}
/// Parses an integer from an ASCII-byte slice with digits in a given base.
///
/// The characters are expected to be an optional
#[doc = " `+` or `-` "]
/// sign followed by only digits. Leading and trailing non-digit characters (including
/// whitespace) represent an error. Underscores (which are accepted in Rust literals)
/// also represent an error.
///
/// Digits are a subset of these characters, depending on `radix`:
/// * `0-9`
/// * `a-z`
/// * `A-Z`
///
/// # Panics
///
/// This function panics if `radix` is not in the range from 2 to 36.
///
/// # Examples
///
/// ```
/// #![feature(int_from_ascii)]
///
#[doc = "assert_eq!(i128::from_ascii_radix(b\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(i128::from_ascii_radix(b\"1 \", 10).is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[inline]
pub const fn from_ascii_radix(src: &[u8], radix: u32)
-> Result<i128, ParseIntError> {
use self::IntErrorKind::*;
use self::ParseIntError as PIE;
if 2 > radix || radix > 36 { from_ascii_radix_panic(radix); }
if src.is_empty() { return Err(PIE { kind: Empty }); }
#[allow(unused_comparisons)]
let is_signed_ty = 0 > <i128>::MIN;
let (is_positive, mut digits) =
match src {
[b'+' | b'-'] => { return Err(PIE { kind: InvalidDigit }); }
[b'+', rest @ ..] => (true, rest),
[b'-', rest @ ..] if is_signed_ty => (false, rest),
_ => (true, src),
};
let mut result = 0;
macro_rules! unwrap_or_PIE {
($option : expr, $kind : ident) =>
{
match $option
{
Some(value) => value, None => return
Err(PIE { kind : $kind }),
}
};
}
if can_not_overflow::<i128>(radix, is_signed_ty, digits) {
macro_rules! run_unchecked_loop {
($unchecked_additive_op : tt) =>
{{
while let [c, rest @ ..] = digits
{
result = result * (radix as i128); let x = unwrap_or_PIE!
((* c as char).to_digit(radix), InvalidDigit); result =
result $unchecked_additive_op(x as i128); digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
result = result * (radix as i128);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result + (x as i128);
digits = rest;
}
}
} else {
{
while let [c, rest @ ..] = digits {
result = result * (radix as i128);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result - (x as i128);
digits = rest;
}
}
};
} else {
macro_rules! run_checked_loop {
($checked_additive_op : ident, $overflow_err : ident) =>
{{
while let [c, rest @ ..] = digits
{
let mul = result.checked_mul(radix as i128); let x =
unwrap_or_PIE! ((* c as char).to_digit(radix), InvalidDigit)
as i128; result = unwrap_or_PIE! (mul, $overflow_err);
result = unwrap_or_PIE!
(< i128 > :: $checked_additive_op(result, x),
$overflow_err); digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
let mul = result.checked_mul(radix as i128);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as i128;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: PosOverflow }),
};
result =
match <i128>::checked_add(result, x) {
Some(value) => value,
None => return Err(PIE { kind: PosOverflow }),
};
digits = rest;
}
}
} else {
{
while let [c, rest @ ..] = digits {
let mul = result.checked_mul(radix as i128);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as i128;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
result =
match <i128>::checked_sub(result, x) {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
digits = rest;
}
}
};
}
Ok(result)
}
}from_str_int_impl! { signed isizei8i16i32i64i128 }1851#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
const impl FromStr for u128 {
type Err = ParseIntError;
/// Parses an integer from a string slice with decimal digits.
///
/// The characters are expected to be an optional
#[doc = " `+` "]
/// sign followed by only digits. Leading and trailing non-digit characters (including
/// whitespace) represent an error. Underscores (which are accepted in Rust literals)
/// also represent an error.
///
/// # See also
/// For parsing numbers in other bases, such as binary or hexadecimal,
/// see [`from_str_radix`][Self::from_str_radix].
///
/// # Examples
///
/// ```
/// use std::str::FromStr;
///
#[doc = "assert_eq!(u128::from_str(\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # use std::str::FromStr;
/// #
#[doc = "assert!(u128::from_str(\"1 \").is_err());"]
/// ```
#[inline]
fn from_str(src: &str) -> Result<u128, ParseIntError> {
<u128>::from_str_radix(src, 10)
}
}
impl u128 {
/// Parses an integer from a string slice with digits in a given base.
///
/// The string is expected to be an optional
#[doc = " `+` "]
/// sign followed by only digits. Leading and trailing non-digit characters (including
/// whitespace) represent an error. Underscores (which are accepted in Rust literals)
/// also represent an error.
///
/// Digits are a subset of these characters, depending on `radix`:
/// * `0-9`
/// * `a-z`
/// * `A-Z`
///
/// # Panics
///
/// This function panics if `radix` is not in the range from 2 to 36.
///
/// # See also
/// If the string to be parsed is in base 10 (decimal),
/// [`from_str`] or [`str::parse`] can also be used.
///
/// [`from_str`]: #method.from_str
/// [`str::parse`]: primitive.str.html#method.parse
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(u128::from_str_radix(\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
#[doc = "assert!(u128::from_str_radix(\"1 \", 10).is_err());"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_from_str", since = "1.82.0")]
#[inline]
pub const fn from_str_radix(src: &str, radix: u32)
-> Result<u128, ParseIntError> {
<u128>::from_ascii_radix(src.as_bytes(), radix)
}
/// Parses an integer from an ASCII-byte slice with decimal digits.
///
/// The characters are expected to be an optional
#[doc = " `+` "]
/// sign followed by only digits. Leading and trailing non-digit characters (including
/// whitespace) represent an error. Underscores (which are accepted in Rust literals)
/// also represent an error.
///
/// # Examples
///
/// ```
/// #![feature(int_from_ascii)]
///
#[doc = "assert_eq!(u128::from_ascii(b\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(u128::from_ascii(b\"1 \").is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[inline]
pub const fn from_ascii(src: &[u8]) -> Result<u128, ParseIntError> {
<u128>::from_ascii_radix(src, 10)
}
/// Parses an integer from an ASCII-byte slice with digits in a given base.
///
/// The characters are expected to be an optional
#[doc = " `+` "]
/// sign followed by only digits. Leading and trailing non-digit characters (including
/// whitespace) represent an error. Underscores (which are accepted in Rust literals)
/// also represent an error.
///
/// Digits are a subset of these characters, depending on `radix`:
/// * `0-9`
/// * `a-z`
/// * `A-Z`
///
/// # Panics
///
/// This function panics if `radix` is not in the range from 2 to 36.
///
/// # Examples
///
/// ```
/// #![feature(int_from_ascii)]
///
#[doc = "assert_eq!(u128::from_ascii_radix(b\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(u128::from_ascii_radix(b\"1 \", 10).is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[inline]
pub const fn from_ascii_radix(src: &[u8], radix: u32)
-> Result<u128, ParseIntError> {
use self::IntErrorKind::*;
use self::ParseIntError as PIE;
if 2 > radix || radix > 36 { from_ascii_radix_panic(radix); }
if src.is_empty() { return Err(PIE { kind: Empty }); }
#[allow(unused_comparisons)]
let is_signed_ty = 0 > <u128>::MIN;
let (is_positive, mut digits) =
match src {
[b'+' | b'-'] => { return Err(PIE { kind: InvalidDigit }); }
[b'+', rest @ ..] => (true, rest),
[b'-', rest @ ..] if is_signed_ty => (false, rest),
_ => (true, src),
};
let mut result = 0;
macro_rules! unwrap_or_PIE {
($option : expr, $kind : ident) =>
{
match $option
{
Some(value) => value, None => return
Err(PIE { kind : $kind }),
}
};
}
if can_not_overflow::<u128>(radix, is_signed_ty, digits) {
macro_rules! run_unchecked_loop {
($unchecked_additive_op : tt) =>
{{
while let [c, rest @ ..] = digits
{
result = result * (radix as u128); let x = unwrap_or_PIE!
((* c as char).to_digit(radix), InvalidDigit); result =
result $unchecked_additive_op(x as u128); digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
result = result * (radix as u128);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result + (x as u128);
digits = rest;
}
}
} else {
{
while let [c, rest @ ..] = digits {
result = result * (radix as u128);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result - (x as u128);
digits = rest;
}
}
};
} else {
macro_rules! run_checked_loop {
($checked_additive_op : ident, $overflow_err : ident) =>
{{
while let [c, rest @ ..] = digits
{
let mul = result.checked_mul(radix as u128); let x =
unwrap_or_PIE! ((* c as char).to_digit(radix), InvalidDigit)
as u128; result = unwrap_or_PIE! (mul, $overflow_err);
result = unwrap_or_PIE!
(< u128 > :: $checked_additive_op(result, x),
$overflow_err); digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
let mul = result.checked_mul(radix as u128);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as u128;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: PosOverflow }),
};
result =
match <u128>::checked_add(result, x) {
Some(value) => value,
None => return Err(PIE { kind: PosOverflow }),
};
digits = rest;
}
}
} else {
{
while let [c, rest @ ..] = digits {
let mul = result.checked_mul(radix as u128);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as u128;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
result =
match <u128>::checked_sub(result, x) {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
digits = rest;
}
}
};
}
Ok(result)
}
}from_str_int_impl! { unsigned usizeu8u16u32u64u128 }