1//! Numeric traits and functions for the built-in numeric types.
23#![stable(feature = "rust1", since = "1.0.0")]
4#![expect(clippy::manual_is_ascii_check, reason = "this module implements various is_ascii checks")]
56use crate::convert::{BoundedCastFromInt, CheckedCastFromInt};
7use crate::panic::const_panic;
8use crate::str::FromStr;
9use crate::ub_checks::assert_unsafe_precondition;
10use crate::{ascii, intrinsics, mem};
1112// FIXME(const-hack): Used because the `?` operator is not allowed in a const context.
13macro_rules!try_opt {
14 ($e:expr) => {
15match $e {
16Some(x) => x,
17None => return None,
18 }
19 };
20}
2122// Use this when the generated code should differ between signed and unsigned types.
23macro_rules!sign_dependent_expr {
24 (signed ? if signed { $signed_case:expr } if unsigned { $unsigned_case:expr } ) => {
25$signed_case
26};
27 (unsigned ? if signed { $signed_case:expr } if unsigned { $unsigned_case:expr } ) => {
28$unsigned_case
29};
30}
3132// These modules are public only for testing.
33#[doc(hidden)]
34#[unstable(
35 feature = "num_internals",
36 reason = "internal routines only exposed for testing",
37 issue = "none"
38)]
39pub mod imp;
4041#[macro_use]
42mod int_macros; // import int_impl!
43#[macro_use]
44mod uint_macros; // import uint_impl!
4546mod complex;
47mod error;
48#[cfg(not(no_fp_fmt_parse))]
49mod float_parse;
50mod nonzero;
51mod saturating;
52mod traits;
53mod wrapping;
5455/// 100% perma-unstable
56#[doc(hidden)]
57pub mod niche_types;
5859#[unstable(feature = "complex_numbers", issue = "154023")]
60pub use complex::Complex;
61#[stable(feature = "int_error_matching", since = "1.55.0")]
62pub use error::IntErrorKind;
63#[stable(feature = "rust1", since = "1.0.0")]
64pub use error::ParseIntError;
65#[stable(feature = "try_from", since = "1.34.0")]
66pub use error::TryFromIntError;
67#[stable(feature = "rust1", since = "1.0.0")]
68#[cfg(not(no_fp_fmt_parse))]
69pub use float_parse::ParseFloatError;
70#[stable(feature = "generic_nonzero", since = "1.79.0")]
71pub use nonzero::NonZero;
72#[unstable(
73 feature = "nonzero_internals",
74 reason = "implementation detail which may disappear or be replaced at any time",
75 issue = "none"
76)]
77pub use nonzero::ZeroablePrimitive;
78#[stable(feature = "signed_nonzero", since = "1.34.0")]
79pub use nonzero::{NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize};
80#[stable(feature = "nonzero", since = "1.28.0")]
81pub use nonzero::{NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroUsize};
82#[stable(feature = "saturating_int_impl", since = "1.74.0")]
83pub use saturating::Saturating;
84#[stable(feature = "rust1", since = "1.0.0")]
85pub use wrapping::Wrapping;
8687macro_rules!u8_xe_bytes_doc {
88 () => {
89"
9091**Note**: This function is meaningless on `u8`. Byte order does not exist as a
92concept for byte-sized integers. This function is only provided in symmetry
93with larger integer types.
9495"
96};
97}
9899macro_rules!i8_xe_bytes_doc {
100 () => {
101"
102103**Note**: This function is meaningless on `i8`. Byte order does not exist as a
104concept for byte-sized integers. This function is only provided in symmetry
105with larger integer types. You can cast from and to `u8` using
106[`cast_signed`](u8::cast_signed) and [`cast_unsigned`](Self::cast_unsigned).
107108"
109};
110}
111112macro_rules!usize_isize_to_xe_bytes_doc {
113 () => {
114"
115116**Note**: This function returns an array of length 2, 4 or 8 bytes
117depending on the target pointer size.
118119"
120};
121}
122123macro_rules!usize_isize_from_xe_bytes_doc {
124 () => {
125"
126127**Note**: This function takes an array of length 2, 4 or 8 bytes
128depending on the target pointer size.
129130"
131};
132}
133134macro_rules!midpoint_impl {
135 ($SelfT:ty, unsigned) => {
136/// Calculates the midpoint (average) between `self` and `rhs`.
137 ///
138 /// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
139 /// sufficiently-large unsigned integral type. This implies that the result is
140 /// always rounded towards zero and that no overflow will ever occur.
141 ///
142 /// # Examples
143 ///
144 /// ```
145#[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(4), 2);")]
146 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".midpoint(4), 2);")]
147/// ```
148#[stable(feature = "num_midpoint", since = "1.85.0")]
149 #[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
150 #[must_use = "this returns the result of the operation, \
151 without modifying the original"]
152 #[doc(alias = "average_floor")]
153 #[doc(alias = "average")]
154 #[inline]
155pub const fn midpoint(self, rhs: $SelfT) -> $SelfT {
156// Use the well known branchless algorithm from Hacker's Delight to compute
157 // `(a + b) / 2` without overflowing: `((a ^ b) >> 1) + (a & b)`.
158((self ^ rhs) >> 1) + (self & rhs)
159 }
160 };
161 ($SelfT:ty, signed) => {
162/// Calculates the midpoint (average) between `self` and `rhs`.
163 ///
164 /// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
165 /// sufficiently-large signed integral type. This implies that the result is
166 /// always rounded towards zero and that no overflow will ever occur.
167 ///
168 /// # Examples
169 ///
170 /// ```
171#[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(4), 2);")]
172 #[doc = concat!("assert_eq!((-1", stringify!($SelfT), ").midpoint(2), 0);")]
173 #[doc = concat!("assert_eq!((-7", stringify!($SelfT), ").midpoint(0), -3);")]
174 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(-7), -3);")]
175 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(7), 3);")]
176/// ```
177#[stable(feature = "num_midpoint_signed", since = "1.87.0")]
178 #[rustc_const_stable(feature = "num_midpoint_signed", since = "1.87.0")]
179 #[must_use = "this returns the result of the operation, \
180 without modifying the original"]
181 #[doc(alias = "average_floor")]
182 #[doc(alias = "average_ceil")]
183 #[doc(alias = "average")]
184 #[inline]
185pub const fn midpoint(self, rhs: Self) -> Self {
186// Use the well known branchless algorithm from Hacker's Delight to compute
187 // `(a + b) / 2` without overflowing: `((a ^ b) >> 1) + (a & b)`.
188let t = ((self ^ rhs) >> 1) + (self & rhs);
189// Except that it fails for integers whose sum is an odd negative number as
190 // their floor is one less than their average. So we adjust the result.
191t + (if t < 0 { 1 } else { 0 } & (self ^ rhs))
192 }
193 };
194 ($SelfT:ty, $WideT:ty, unsigned) => {
195/// Calculates the midpoint (average) between `self` and `rhs`.
196 ///
197 /// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
198 /// sufficiently-large unsigned integral type. This implies that the result is
199 /// always rounded towards zero and that no overflow will ever occur.
200 ///
201 /// # Examples
202 ///
203 /// ```
204#[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(4), 2);")]
205 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".midpoint(4), 2);")]
206/// ```
207#[stable(feature = "num_midpoint", since = "1.85.0")]
208 #[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
209 #[must_use = "this returns the result of the operation, \
210 without modifying the original"]
211 #[doc(alias = "average_floor")]
212 #[doc(alias = "average")]
213 #[inline]
214pub const fn midpoint(self, rhs: $SelfT) -> $SelfT {
215 ((self as $WideT + rhs as $WideT) / 2) as $SelfT
216}
217 };
218 ($SelfT:ty, $WideT:ty, signed) => {
219/// Calculates the midpoint (average) between `self` and `rhs`.
220 ///
221 /// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
222 /// sufficiently-large signed integral type. This implies that the result is
223 /// always rounded towards zero and that no overflow will ever occur.
224 ///
225 /// # Examples
226 ///
227 /// ```
228#[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(4), 2);")]
229 #[doc = concat!("assert_eq!((-1", stringify!($SelfT), ").midpoint(2), 0);")]
230 #[doc = concat!("assert_eq!((-7", stringify!($SelfT), ").midpoint(0), -3);")]
231 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(-7), -3);")]
232 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(7), 3);")]
233/// ```
234#[stable(feature = "num_midpoint_signed", since = "1.87.0")]
235 #[rustc_const_stable(feature = "num_midpoint_signed", since = "1.87.0")]
236 #[must_use = "this returns the result of the operation, \
237 without modifying the original"]
238 #[doc(alias = "average_floor")]
239 #[doc(alias = "average_ceil")]
240 #[doc(alias = "average")]
241 #[inline]
242pub const fn midpoint(self, rhs: $SelfT) -> $SelfT {
243 ((self as $WideT + rhs as $WideT) / 2) as $SelfT
244}
245 };
246}
247248macro_rules!widening_mul_impl {
249 ($SelfT:ty, $WideT:ty) => {
250/// Widening multiplication. Computes `self * rhs`, widening to a larger integer.
251 ///
252 /// The returned value is always exact and can never overflow.
253 ///
254 /// Note that this method is semantically equivalent to [`carrying_mul`] with a
255 /// carry of zero, with the latter instead returning a tuple denoting the low and
256 /// high parts of the result. Consider using it instead if you need
257 /// interoperability with other big int helper functions, or if this method isn't
258 /// available for a given type.
259 ///
260 /// [`carrying_mul`]: Self::carrying_mul
261 ///
262 /// # Examples
263 ///
264 /// ```
265 /// #![feature(widening_mul)]
266 ///
267#[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.widening_mul(0_", stringify!($SelfT), "), 0);")]
268 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.widening_mul(", stringify!($SelfT), "::MAX), ", stringify!($SelfT), "::MAX as ", stringify!($WideT), " * ", stringify!($SelfT), "::MAX as ", stringify!($WideT), ");")]
269/// ```
270#[unstable(feature = "widening_mul", issue = "152016")]
271 #[rustc_const_unstable(feature = "widening_mul", issue = "152016")]
272 #[must_use = "this returns the result of the operation, \
273 without modifying the original"]
274 #[inline]
275pub const fn widening_mul(self, rhs: Self) -> $WideT {
276self as $WideT * rhs as $WideT
277}
278 }
279}
280281macro_rules!widening_carryless_mul_impl {
282 ($SelfT:ty, $WideT:ty) => {
283/// Performs a widening carry-less multiplication.
284 ///
285 /// # Examples
286 ///
287 /// ```
288 /// #![feature(uint_carryless_mul)]
289 ///
290#[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.widening_carryless_mul(",
291stringify!($SelfT), "::MAX), ", stringify!($WideT), "::MAX / 3);")]
292/// ```
293#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
294 #[doc(alias = "clmul")]
295 #[unstable(feature = "uint_carryless_mul", issue = "152080")]
296 #[must_use = "this returns the result of the operation, \
297 without modifying the original"]
298 #[inline]
299pub const fn widening_carryless_mul(self, rhs: $SelfT) -> $WideT {
300 (self as $WideT).carryless_mul(rhs as $WideT)
301 }
302 }
303}
304305macro_rules!carrying_carryless_mul_impl {
306 (u128, u256) => {
307carrying_carryless_mul_impl! { @internal u128 =>
308pub const fn carrying_carryless_mul(self, rhs: Self, carry: Self) -> (Self, Self) {
309let x0 = self as u64;
310let x1 = (self >> 64) as u64;
311let y0 = rhs as u64;
312let y1 = (rhs >> 64) as u64;
313314let z0 = u64::widening_carryless_mul(x0, y0);
315let z2 = u64::widening_carryless_mul(x1, y1);
316317// The grade school algorithm would compute:
318 // z1 = x0y1 ^ x1y0
319320 // Instead, Karatsuba first computes:
321let z3 = u64::widening_carryless_mul(x0 ^ x1, y0 ^ y1);
322// Since it distributes over XOR,
323 // z3 == x0y0 ^ x0y1 ^ x1y0 ^ x1y1
324 // |--| |---------| |--|
325 // == z0 ^ z1 ^ z2
326 // so we can compute z1 as
327let z1 = z3 ^ z0 ^ z2;
328329let lo = z0 ^ (z1 << 64);
330let hi = z2 ^ (z1 >> 64);
331332 (lo ^ carry, hi)
333 }
334 }
335 };
336 ($SelfT:ty, $WideT:ty) => {
337carrying_carryless_mul_impl! { @internal $SelfT =>
338pub const fn carrying_carryless_mul(self, rhs: Self, carry: Self) -> (Self, Self) {
339// Can't use widening_carryless_mul because it's not implemented for usize.
340let p = (self as $WideT).carryless_mul(rhs as $WideT);
341342let lo = (p as $SelfT);
343let hi = (p >> Self::BITS) as $SelfT;
344345 (lo ^ carry, hi)
346 }
347 }
348 };
349 (@internal $SelfT:ty => $($fn:tt)*) => {
350/// Calculates the "full carryless multiplication" without the possibility to overflow.
351 ///
352 /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
353 /// of the result as two separate values, in that order.
354 ///
355 /// # Examples
356 ///
357 /// Please note that this example is shared among integer types, which is why `u8` is used.
358 ///
359 /// ```
360 /// #![feature(uint_carryless_mul)]
361 ///
362 /// assert_eq!(0b1000_0000u8.carrying_carryless_mul(0b1000_0000, 0b0000), (0, 0b0100_0000));
363 /// assert_eq!(0b1000_0000u8.carrying_carryless_mul(0b1000_0000, 0b1111), (0b1111, 0b0100_0000));
364#[doc = concat!("assert_eq!(",
365stringify!($SelfT), "::MAX.carrying_carryless_mul(", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX), ",
366"(!(", stringify!($SelfT), "::MAX / 3), ", stringify!($SelfT), "::MAX / 3));"
367)]
368/// ```
369#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
370 #[doc(alias = "clmul")]
371 #[unstable(feature = "uint_carryless_mul", issue = "152080")]
372 #[must_use = "this returns the result of the operation, \
373 without modifying the original"]
374 #[inline]
375$($fn)*
376 }
377}
378379impl i8 {
380/// 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 = 0x0a;"]
///
#[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 = 0x0ai8;"]
#[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 = "1.99.0", 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 = "1.99.0", 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! {
381Self = i8,
382 ActualT = i8,
383 UnsignedT = u8,
384 BITS = 8,
385 BITS_MINUS_ONE = 7,
386 Min = -128,
387 Max = 127,
388 rot = 2,
389 rot_op = "-0x7e",
390 rot_result = "0x0a",
391 swap_op = "0x12",
392 swapped = "0x12",
393 reversed = "0x48",
394 le_bytes = "[0x12]",
395 be_bytes = "[0x12]",
396 to_xe_bytes_doc = i8_xe_bytes_doc!(),
397 from_xe_bytes_doc = i8_xe_bytes_doc!(),
398 bound_condition = "",
399 }400/// 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 }401/// 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 }402}
403404impl i16 {
405/// 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 = 0x003a;"]
///
#[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 = 0x003ai16;"]
#[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 = "1.99.0", 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 = "1.99.0", 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! {
406Self = i16,
407 ActualT = i16,
408 UnsignedT = u16,
409 BITS = 16,
410 BITS_MINUS_ONE = 15,
411 Min = -32768,
412 Max = 32767,
413 rot = 4,
414 rot_op = "-0x5ffd",
415 rot_result = "0x003a",
416 swap_op = "0x1234",
417 swapped = "0x3412",
418 reversed = "0x2c48",
419 le_bytes = "[0x34, 0x12]",
420 be_bytes = "[0x12, 0x34]",
421 to_xe_bytes_doc = "",
422 from_xe_bytes_doc = "",
423 bound_condition = "",
424 }425/// 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 }426/// 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 }427}
428429impl i32 {
430/// 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 = 0x010000b3i32;"]
#[doc = "let m = 0x0000b301;"]
///
#[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 = 0x0000b301i32;"]
#[doc = "let m = 0x010000b3;"]
///
#[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 = "1.99.0", 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 = "1.99.0", 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! {
431Self = i32,
432 ActualT = i32,
433 UnsignedT = u32,
434 BITS = 32,
435 BITS_MINUS_ONE = 31,
436 Min = -2147483648,
437 Max = 2147483647,
438 rot = 8,
439 rot_op = "0x010000b3",
440 rot_result = "0x0000b301",
441 swap_op = "0x12345678",
442 swapped = "0x78563412",
443 reversed = "0x1e6a2c48",
444 le_bytes = "[0x78, 0x56, 0x34, 0x12]",
445 be_bytes = "[0x12, 0x34, 0x56, 0x78]",
446 to_xe_bytes_doc = "",
447 from_xe_bytes_doc = "",
448 bound_condition = "",
449 }450/// 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 }451/// 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 }452}
453454impl i64 {
455/// 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 = 0x0aa00000000006e1i64;"]
#[doc = "let m = 0x00000000006e10aa;"]
///
#[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 = 0x00000000006e10aai64;"]
#[doc = "let m = 0x0aa00000000006e1;"]
///
#[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 = "1.99.0", 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 = "1.99.0", 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! {
456Self = i64,
457 ActualT = i64,
458 UnsignedT = u64,
459 BITS = 64,
460 BITS_MINUS_ONE = 63,
461 Min = -9223372036854775808,
462 Max = 9223372036854775807,
463 rot = 12,
464 rot_op = "0x0aa00000000006e1",
465 rot_result = "0x00000000006e10aa",
466 swap_op = "0x1234567890123456",
467 swapped = "0x5634129078563412",
468 reversed = "0x6a2c48091e6a2c48",
469 le_bytes = "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
470 be_bytes = "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
471 to_xe_bytes_doc = "",
472 from_xe_bytes_doc = "",
473 bound_condition = "",
474 }475/// 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 }476/// 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 }477}
478479impl i128 {
480/// 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 = 0x0000000000000000000000004f7613f4;"]
///
#[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 = 0x0000000000000000000000004f7613f4i128;"]
#[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 = "1.99.0", 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 = "1.99.0", 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! {
481Self = i128,
482 ActualT = i128,
483 UnsignedT = u128,
484 BITS = 128,
485 BITS_MINUS_ONE = 127,
486 Min = -170141183460469231731687303715884105728,
487 Max = 170141183460469231731687303715884105727,
488 rot = 16,
489 rot_op = "0x13f40000000000000000000000004f76",
490 rot_result = "0x0000000000000000000000004f7613f4",
491 swap_op = "0x12345678901234567890123456789012",
492 swapped = "0x12907856341290785634129078563412",
493 reversed = "0x48091e6a2c48091e6a2c48091e6a2c48",
494 le_bytes = "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
495 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
496 be_bytes = "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
497 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
498 to_xe_bytes_doc = "",
499 from_xe_bytes_doc = "",
500 bound_condition = "",
501 }502/// 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 }503}
504505#[doc(auto_cfg = false)]
506#[cfg(target_pointer_width = "16")]
507impl isize {
508int_impl! {
509Self = isize,
510 ActualT = i16,
511 UnsignedT = usize,
512 BITS = 16,
513 BITS_MINUS_ONE = 15,
514 Min = -32768,
515 Max = 32767,
516 rot = 4,
517 rot_op = "-0x5ffd",
518 rot_result = "0x003a",
519 swap_op = "0x1234",
520 swapped = "0x3412",
521 reversed = "0x2c48",
522 le_bytes = "[0x34, 0x12]",
523 be_bytes = "[0x12, 0x34]",
524 to_xe_bytes_doc = usize_isize_to_xe_bytes_doc!(),
525 from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(),
526 bound_condition = " on 16-bit targets",
527 }
528midpoint_impl! { isize, i32, signed }
529}
530531#[doc(auto_cfg = false)]
532#[cfg(target_pointer_width = "32")]
533impl isize {
534int_impl! {
535Self = isize,
536 ActualT = i32,
537 UnsignedT = usize,
538 BITS = 32,
539 BITS_MINUS_ONE = 31,
540 Min = -2147483648,
541 Max = 2147483647,
542 rot = 8,
543 rot_op = "0x010000b3",
544 rot_result = "0x0000b301",
545 swap_op = "0x12345678",
546 swapped = "0x78563412",
547 reversed = "0x1e6a2c48",
548 le_bytes = "[0x78, 0x56, 0x34, 0x12]",
549 be_bytes = "[0x12, 0x34, 0x56, 0x78]",
550 to_xe_bytes_doc = usize_isize_to_xe_bytes_doc!(),
551 from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(),
552 bound_condition = " on 32-bit targets",
553 }
554midpoint_impl! { isize, i64, signed }
555}
556557#[doc(auto_cfg = false)]
558#[cfg(target_pointer_width = "64")]
559impl isize {
560/// 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 = 0x0aa00000000006e1isize;"]
#[doc = "let m = 0x00000000006e10aa;"]
///
#[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 = 0x00000000006e10aaisize;"]
#[doc = "let m = 0x0aa00000000006e1;"]
///
#[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 = "1.99.0", 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 = "1.99.0", 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! {
561Self = isize,
562 ActualT = i64,
563 UnsignedT = usize,
564 BITS = 64,
565 BITS_MINUS_ONE = 63,
566 Min = -9223372036854775808,
567 Max = 9223372036854775807,
568 rot = 12,
569 rot_op = "0x0aa00000000006e1",
570 rot_result = "0x00000000006e10aa",
571 swap_op = "0x1234567890123456",
572 swapped = "0x5634129078563412",
573 reversed = "0x6a2c48091e6a2c48",
574 le_bytes = "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
575 be_bytes = "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
576 to_xe_bytes_doc = usize_isize_to_xe_bytes_doc!(),
577 from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(),
578 bound_condition = " on 64-bit targets",
579 }580/// 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 }581}
582583/// If the bit selected by this mask is set, ascii is lower case.
584const ASCII_CASE_MASK: u8 = 0b0010_0000;
585586impl u8 {
587/// 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 = 0x0a;"]
///
#[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 = 0x0au8;"]
#[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.
///
/// This operation can be thought of as concatenating `self` and `right` into an
/// integer twice the size of
#[doc = "`u8`,"]
/// performing a left shift by `n`, and returning the **left half** of the result.
///
/// The name comes from "funneling" a wider integer to a narrower integer.
///
/// # Panics
///
/// ## Overflow behavior
///
/// If overflow checks are enabled (default in debug mode), this function will panic if `n`
/// is greater than or equal to the number of bits in `self`. If overflow checks are
/// disabled (default in release mode), there is no panic; instead, the value is shifted
/// by `n % Self::BITS`.
///
/// # Examples
///
/// ```
/// #![feature(funnel_shifts)]
///
#[doc = "let a = 0x82_u8;"]
#[doc = "let b = 0x36_u8;"]
///
#[doc = "assert_eq!(a.funnel_shl(b, 2), 0x08);"]
///
/// // Using zeros as the right operand acts as a normal shift left
#[doc = "assert_eq!(a.funnel_shl(0, 2), a << 2);"]
///
/// // Shifting by 0 returns `self` unchanged
#[doc = "assert_eq!(a.funnel_shl(b, 0), a);"]
///
/// // Using the same value as the right operand acts as a rotate
#[doc = "assert_eq!(a.funnel_shl(a, 2), a.rotate_left(2));"]
/// ```
///
/// Note that while `funnel_shl` can act as a rotate, it does not allow for
/// rotating by an unbounded amount like [`rotate_left`](Self::rotate_left) does:
///
/// ```should_panic
/// #![feature(funnel_shifts)]
/// # #![feature(cfg_overflow_checks)]
/// # #[cfg(overflow_checks)] {
///
#[doc = "let a = u8::MAX;"]
/// // Okay
#[doc = "let _ = a.rotate_left(u8::BITS);"]
/// // Panics (only when overflow checks are enabled)
#[doc = "let _ = a.funnel_shl(a, u8::BITS);"]
/// # }
/// # #[cfg(not(overflow_checks))] panic!("fulfill should_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)]
#[rustc_inherit_overflow_checks]
pub const fn funnel_shl(self, right: Self, n: u32) -> Self {
if intrinsics::overflow_checks() {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift left with overflow"));
}
};
}
unsafe {
let n = n & (Self::BITS - 1);
self.unchecked_funnel_shl(right, n)
}
}
/// Performs a right funnel shift.
///
/// This operation can be thought of as concatenating `self` and `right` into an
/// integer twice the size of
#[doc = "`u8`,"]
/// performing a right shift by `n`, and returning the **right half** of the result.
///
/// The name comes from "funneling" a wider integer to a narrower integer.
///
/// # Panics
///
/// ## Overflow behavior
///
/// If overflow checks are enabled (default in debug mode), this function will panic if `n`
/// is greater than or equal to the number of bits in `self`. If overflow checks are
/// disabled (default in release mode), there is no panic; instead, the value is shifted
/// by `n % Self::BITS`.
///
/// # Examples
///
/// ```
/// #![feature(funnel_shifts)]
///
#[doc = "let a = 0x82_u8;"]
#[doc = "let b = 0x36_u8;"]
///
#[doc = "assert_eq!(a.funnel_shr(b, 2), 0x8d);"]
///
/// // Using zeros as the left operand acts as a normal shift right
#[doc = "assert_eq!(0_u8.funnel_shr(a, 2), a >> 2);"]
///
/// // Shifting by 0 returns `right` unchanged
#[doc = "assert_eq!(b.funnel_shr(a, 0), a);"]
///
/// // Using the same value as the right operand acts as a rotate
#[doc = "assert_eq!(a.funnel_shr(a, 2), a.rotate_right(2));"]
/// ```
///
/// Note that while `funnel_shr` can act as a rotate, it does not allow for
/// rotating by an unbounded amount like [`rotate_right`](Self::rotate_right) does:
///
/// ```should_panic
/// #![feature(funnel_shifts)]
/// # #![feature(cfg_overflow_checks)]
/// # #[cfg(overflow_checks)] {
///
#[doc = "let a = u8::MAX;"]
/// // Okay
#[doc = "let _ = a.rotate_right(u8::BITS);"]
/// // Panics (only when overflow checks are enabled)
#[doc = "let _ = a.funnel_shr(a, u8::BITS);"]
/// # }
/// # #[cfg(not(overflow_checks))] panic!("fulfill should_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)]
#[rustc_inherit_overflow_checks]
pub const fn funnel_shr(self, right: Self, n: u32) -> Self {
if intrinsics::overflow_checks() {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift right with overflow"));
}
};
}
unsafe {
let n = n & (Self::BITS - 1);
self.unchecked_funnel_shr(right, 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, right: 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, right, 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, right: 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, right, 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 = "1.99.0", 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 = "1.99.0", 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! {
588Self = u8,
589 ActualT = u8,
590 SignedT = i8,
591 BITS = 8,
592 BITS_MINUS_ONE = 7,
593 MAX = 255,
594 rot = 2,
595 rot_op = "0x82",
596 rot_result = "0x0a",
597 fsh_op = "0x36",
598 fshl_result = "0x08",
599 fshr_result = "0x8d",
600 clmul_lhs = "0x12",
601 clmul_rhs = "0x34",
602 clmul_result = "0x28",
603 swap_op = "0x12",
604 swapped = "0x12",
605 reversed = "0x48",
606 le_bytes = "[0x12]",
607 be_bytes = "[0x12]",
608 to_xe_bytes_doc = u8_xe_bytes_doc!(),
609 from_xe_bytes_doc = u8_xe_bytes_doc!(),
610 bound_condition = "",
611 }612/// 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 }613/// 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 }614/// 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 }615/// 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 }616617/// Checks if the value is within the ASCII range.
618 ///
619 /// # Examples
620 ///
621 /// ```
622 /// let ascii = 97u8;
623 /// let non_ascii = 150u8;
624 ///
625 /// assert!(ascii.is_ascii());
626 /// assert!(!non_ascii.is_ascii());
627 /// ```
628#[must_use]
629 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
630 #[rustc_const_stable(feature = "const_u8_is_ascii", since = "1.43.0")]
631 #[inline]
632pub const fn is_ascii(&self) -> bool {
633*self <= 127
634}
635636/// If the value of this byte is within the ASCII range, returns it as an
637 /// [ASCII character](ascii::Char). Otherwise, returns `None`.
638#[must_use]
639 #[unstable(feature = "ascii_char", issue = "110998")]
640 #[inline]
641pub const fn as_ascii(&self) -> Option<ascii::Char> {
642 ascii::Char::from_u8(*self)
643 }
644645/// Converts this byte to an [ASCII character](ascii::Char), without
646 /// checking whether or not it's valid.
647 ///
648 /// # Safety
649 ///
650 /// This byte must be valid ASCII, or else this is UB.
651#[must_use]
652 #[unstable(feature = "ascii_char", issue = "110998")]
653 #[inline]
654pub const unsafe fn as_ascii_unchecked(&self) -> ascii::Char {
655{
#[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!(
656 check_library_ub,
657"as_ascii_unchecked requires that the byte is valid ASCII",
658 (it: &u8 = self) => it.is_ascii()
659 );
660661// SAFETY: the caller promised that this byte is ASCII.
662unsafe { ascii::Char::from_u8_unchecked(*self) }
663 }
664665/// Makes a copy of the value in its ASCII upper case equivalent.
666 ///
667 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
668 /// but non-ASCII letters are unchanged.
669 ///
670 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
671 ///
672 /// # Examples
673 ///
674 /// ```
675 /// let lowercase_a = 97u8;
676 ///
677 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
678 /// ```
679 ///
680 /// [`make_ascii_uppercase`]: Self::make_ascii_uppercase
681#[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"]
682 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
683 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
684 #[inline]
685pub const fn to_ascii_uppercase(&self) -> u8 {
686// Toggle the 6th bit if this is a lowercase letter
687*self ^ ((self.is_ascii_lowercase() as u8) * ASCII_CASE_MASK)
688 }
689690/// Makes a copy of the value in its ASCII lower case equivalent.
691 ///
692 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
693 /// but non-ASCII letters are unchanged.
694 ///
695 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
696 ///
697 /// # Examples
698 ///
699 /// ```
700 /// let uppercase_a = 65u8;
701 ///
702 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
703 /// ```
704 ///
705 /// [`make_ascii_lowercase`]: Self::make_ascii_lowercase
706#[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"]
707 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
708 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
709 #[inline]
710pub const fn to_ascii_lowercase(&self) -> u8 {
711// Set the 6th bit if this is an uppercase letter
712*self | (self.is_ascii_uppercase() as u8 * ASCII_CASE_MASK)
713 }
714715/// Assumes self is ascii
716#[inline]
717pub(crate) const fn ascii_change_case_unchecked(&self) -> u8 {
718*self ^ ASCII_CASE_MASK719 }
720721/// Checks that two values are an ASCII case-insensitive match.
722 ///
723 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
724 ///
725 /// # Examples
726 ///
727 /// ```
728 /// let lowercase_a = 97u8;
729 /// let uppercase_a = 65u8;
730 ///
731 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
732 /// ```
733#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
734 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
735 #[expect(clippy::manual_ignore_case_cmp, reason = "implements eq_ignore_ascii_case")]
736 #[inline]
737pub const fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
738self.to_ascii_lowercase() == other.to_ascii_lowercase()
739 }
740741/// Converts this value to its ASCII upper case equivalent in-place.
742 ///
743 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
744 /// but non-ASCII letters are unchanged.
745 ///
746 /// To return a new uppercased value without modifying the existing one, use
747 /// [`to_ascii_uppercase`].
748 ///
749 /// # Examples
750 ///
751 /// ```
752 /// let mut byte = b'a';
753 ///
754 /// byte.make_ascii_uppercase();
755 ///
756 /// assert_eq!(b'A', byte);
757 /// ```
758 ///
759 /// [`to_ascii_uppercase`]: Self::to_ascii_uppercase
760#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
761 #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
762 #[inline]
763pub const fn make_ascii_uppercase(&mut self) {
764*self = self.to_ascii_uppercase();
765 }
766767/// Converts this value to its ASCII lower case equivalent in-place.
768 ///
769 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
770 /// but non-ASCII letters are unchanged.
771 ///
772 /// To return a new lowercased value without modifying the existing one, use
773 /// [`to_ascii_lowercase`].
774 ///
775 /// # Examples
776 ///
777 /// ```
778 /// let mut byte = b'A';
779 ///
780 /// byte.make_ascii_lowercase();
781 ///
782 /// assert_eq!(b'a', byte);
783 /// ```
784 ///
785 /// [`to_ascii_lowercase`]: Self::to_ascii_lowercase
786#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
787 #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
788 #[inline]
789pub const fn make_ascii_lowercase(&mut self) {
790*self = self.to_ascii_lowercase();
791 }
792793/// Checks if the value is an ASCII alphabetic character:
794 ///
795 /// - U+0041 'A' ..= U+005A 'Z', or
796 /// - U+0061 'a' ..= U+007A 'z'.
797 ///
798 /// # Examples
799 ///
800 /// ```
801 /// let uppercase_a = b'A';
802 /// let uppercase_g = b'G';
803 /// let a = b'a';
804 /// let g = b'g';
805 /// let zero = b'0';
806 /// let percent = b'%';
807 /// let space = b' ';
808 /// let lf = b'\n';
809 /// let esc = b'\x1b';
810 ///
811 /// assert!(uppercase_a.is_ascii_alphabetic());
812 /// assert!(uppercase_g.is_ascii_alphabetic());
813 /// assert!(a.is_ascii_alphabetic());
814 /// assert!(g.is_ascii_alphabetic());
815 /// assert!(!zero.is_ascii_alphabetic());
816 /// assert!(!percent.is_ascii_alphabetic());
817 /// assert!(!space.is_ascii_alphabetic());
818 /// assert!(!lf.is_ascii_alphabetic());
819 /// assert!(!esc.is_ascii_alphabetic());
820 /// ```
821#[must_use]
822 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
823 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
824 #[inline]
825pub const fn is_ascii_alphabetic(&self) -> bool {
826#[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')827 }
828829/// Checks if the value is an ASCII uppercase character:
830 /// U+0041 'A' ..= U+005A 'Z'.
831 ///
832 /// # Examples
833 ///
834 /// ```
835 /// let uppercase_a = b'A';
836 /// let uppercase_g = b'G';
837 /// let a = b'a';
838 /// let g = b'g';
839 /// let zero = b'0';
840 /// let percent = b'%';
841 /// let space = b' ';
842 /// let lf = b'\n';
843 /// let esc = b'\x1b';
844 ///
845 /// assert!(uppercase_a.is_ascii_uppercase());
846 /// assert!(uppercase_g.is_ascii_uppercase());
847 /// assert!(!a.is_ascii_uppercase());
848 /// assert!(!g.is_ascii_uppercase());
849 /// assert!(!zero.is_ascii_uppercase());
850 /// assert!(!percent.is_ascii_uppercase());
851 /// assert!(!space.is_ascii_uppercase());
852 /// assert!(!lf.is_ascii_uppercase());
853 /// assert!(!esc.is_ascii_uppercase());
854 /// ```
855#[must_use]
856 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
857 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
858 #[inline]
859pub const fn is_ascii_uppercase(&self) -> bool {
860#[allow(non_exhaustive_omitted_patterns)] match *self {
b'A'..=b'Z' => true,
_ => false,
}matches!(*self, b'A'..=b'Z')861 }
862863/// Checks if the value is an ASCII lowercase character:
864 /// U+0061 'a' ..= U+007A 'z'.
865 ///
866 /// # Examples
867 ///
868 /// ```
869 /// let uppercase_a = b'A';
870 /// let uppercase_g = b'G';
871 /// let a = b'a';
872 /// let g = b'g';
873 /// let zero = b'0';
874 /// let percent = b'%';
875 /// let space = b' ';
876 /// let lf = b'\n';
877 /// let esc = b'\x1b';
878 ///
879 /// assert!(!uppercase_a.is_ascii_lowercase());
880 /// assert!(!uppercase_g.is_ascii_lowercase());
881 /// assert!(a.is_ascii_lowercase());
882 /// assert!(g.is_ascii_lowercase());
883 /// assert!(!zero.is_ascii_lowercase());
884 /// assert!(!percent.is_ascii_lowercase());
885 /// assert!(!space.is_ascii_lowercase());
886 /// assert!(!lf.is_ascii_lowercase());
887 /// assert!(!esc.is_ascii_lowercase());
888 /// ```
889#[must_use]
890 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
891 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
892 #[inline]
893pub const fn is_ascii_lowercase(&self) -> bool {
894#[allow(non_exhaustive_omitted_patterns)] match *self {
b'a'..=b'z' => true,
_ => false,
}matches!(*self, b'a'..=b'z')895 }
896897/// Checks if the value is an ASCII alphanumeric character:
898 ///
899 /// - U+0041 'A' ..= U+005A 'Z', or
900 /// - U+0061 'a' ..= U+007A 'z', or
901 /// - U+0030 '0' ..= U+0039 '9'.
902 ///
903 /// # Examples
904 ///
905 /// ```
906 /// let uppercase_a = b'A';
907 /// let uppercase_g = b'G';
908 /// let a = b'a';
909 /// let g = b'g';
910 /// let zero = b'0';
911 /// let percent = b'%';
912 /// let space = b' ';
913 /// let lf = b'\n';
914 /// let esc = b'\x1b';
915 ///
916 /// assert!(uppercase_a.is_ascii_alphanumeric());
917 /// assert!(uppercase_g.is_ascii_alphanumeric());
918 /// assert!(a.is_ascii_alphanumeric());
919 /// assert!(g.is_ascii_alphanumeric());
920 /// assert!(zero.is_ascii_alphanumeric());
921 /// assert!(!percent.is_ascii_alphanumeric());
922 /// assert!(!space.is_ascii_alphanumeric());
923 /// assert!(!lf.is_ascii_alphanumeric());
924 /// assert!(!esc.is_ascii_alphanumeric());
925 /// ```
926#[must_use]
927 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
928 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
929 #[inline]
930pub const fn is_ascii_alphanumeric(&self) -> bool {
931#[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')932 }
933934/// Checks if the value is an ASCII decimal digit:
935 /// U+0030 '0' ..= U+0039 '9'.
936 ///
937 /// # Examples
938 ///
939 /// ```
940 /// let uppercase_a = b'A';
941 /// let uppercase_g = b'G';
942 /// let a = b'a';
943 /// let g = b'g';
944 /// let zero = b'0';
945 /// let percent = b'%';
946 /// let space = b' ';
947 /// let lf = b'\n';
948 /// let esc = b'\x1b';
949 ///
950 /// assert!(!uppercase_a.is_ascii_digit());
951 /// assert!(!uppercase_g.is_ascii_digit());
952 /// assert!(!a.is_ascii_digit());
953 /// assert!(!g.is_ascii_digit());
954 /// assert!(zero.is_ascii_digit());
955 /// assert!(!percent.is_ascii_digit());
956 /// assert!(!space.is_ascii_digit());
957 /// assert!(!lf.is_ascii_digit());
958 /// assert!(!esc.is_ascii_digit());
959 /// ```
960#[must_use]
961 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
962 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
963 #[inline]
964pub const fn is_ascii_digit(&self) -> bool {
965#[allow(non_exhaustive_omitted_patterns)] match *self {
b'0'..=b'9' => true,
_ => false,
}matches!(*self, b'0'..=b'9')966 }
967968/// Checks if the value is an ASCII octal digit:
969 /// U+0030 '0' ..= U+0037 '7'.
970 ///
971 /// # Examples
972 ///
973 /// ```
974 /// #![feature(is_ascii_octdigit)]
975 ///
976 /// let uppercase_a = b'A';
977 /// let a = b'a';
978 /// let zero = b'0';
979 /// let seven = b'7';
980 /// let nine = b'9';
981 /// let percent = b'%';
982 /// let lf = b'\n';
983 ///
984 /// assert!(!uppercase_a.is_ascii_octdigit());
985 /// assert!(!a.is_ascii_octdigit());
986 /// assert!(zero.is_ascii_octdigit());
987 /// assert!(seven.is_ascii_octdigit());
988 /// assert!(!nine.is_ascii_octdigit());
989 /// assert!(!percent.is_ascii_octdigit());
990 /// assert!(!lf.is_ascii_octdigit());
991 /// ```
992#[must_use]
993 #[unstable(feature = "is_ascii_octdigit", issue = "101288")]
994 #[inline]
995pub const fn is_ascii_octdigit(&self) -> bool {
996#[allow(non_exhaustive_omitted_patterns)] match *self {
b'0'..=b'7' => true,
_ => false,
}matches!(*self, b'0'..=b'7')997 }
998999/// Checks if the value is an ASCII hexadecimal digit:
1000 ///
1001 /// - U+0030 '0' ..= U+0039 '9', or
1002 /// - U+0041 'A' ..= U+0046 'F', or
1003 /// - U+0061 'a' ..= U+0066 'f'.
1004 ///
1005 /// # Examples
1006 ///
1007 /// ```
1008 /// let uppercase_a = b'A';
1009 /// let uppercase_g = b'G';
1010 /// let a = b'a';
1011 /// let g = b'g';
1012 /// let zero = b'0';
1013 /// let percent = b'%';
1014 /// let space = b' ';
1015 /// let lf = b'\n';
1016 /// let esc = b'\x1b';
1017 ///
1018 /// assert!(uppercase_a.is_ascii_hexdigit());
1019 /// assert!(!uppercase_g.is_ascii_hexdigit());
1020 /// assert!(a.is_ascii_hexdigit());
1021 /// assert!(!g.is_ascii_hexdigit());
1022 /// assert!(zero.is_ascii_hexdigit());
1023 /// assert!(!percent.is_ascii_hexdigit());
1024 /// assert!(!space.is_ascii_hexdigit());
1025 /// assert!(!lf.is_ascii_hexdigit());
1026 /// assert!(!esc.is_ascii_hexdigit());
1027 /// ```
1028#[must_use]
1029 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1030 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1031 #[inline]
1032pub const fn is_ascii_hexdigit(&self) -> bool {
1033#[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')1034 }
10351036/// Checks if the value is an ASCII punctuation or symbol character
1037 /// (i.e. not alphanumeric, whitespace, or control):
1038 ///
1039 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
1040 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
1041 /// - U+005B ..= U+0060 `` [ \ ] ^ _ ` ``, or
1042 /// - U+007B ..= U+007E `{ | } ~`
1043 ///
1044 /// # Examples
1045 ///
1046 /// ```
1047 /// let uppercase_a = b'A';
1048 /// let uppercase_g = b'G';
1049 /// let a = b'a';
1050 /// let g = b'g';
1051 /// let zero = b'0';
1052 /// let percent = b'%';
1053 /// let space = b' ';
1054 /// let lf = b'\n';
1055 /// let esc = b'\x1b';
1056 ///
1057 /// assert!(!uppercase_a.is_ascii_punctuation());
1058 /// assert!(!uppercase_g.is_ascii_punctuation());
1059 /// assert!(!a.is_ascii_punctuation());
1060 /// assert!(!g.is_ascii_punctuation());
1061 /// assert!(!zero.is_ascii_punctuation());
1062 /// assert!(percent.is_ascii_punctuation());
1063 /// assert!(!space.is_ascii_punctuation());
1064 /// assert!(!lf.is_ascii_punctuation());
1065 /// assert!(!esc.is_ascii_punctuation());
1066 /// ```
1067#[must_use]
1068 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1069 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1070 #[inline]
1071pub const fn is_ascii_punctuation(&self) -> bool {
1072#[allow(non_exhaustive_omitted_patterns)] match *self {
b'!'..=b'/' => true,
_ => false,
}matches!(*self, b'!'..=b'/')1073 | #[allow(non_exhaustive_omitted_patterns)] match *self {
b':'..=b'@' => true,
_ => false,
}matches!(*self, b':'..=b'@')1074 | #[allow(non_exhaustive_omitted_patterns)] match *self {
b'['..=b'`' => true,
_ => false,
}matches!(*self, b'['..=b'`')1075 | #[allow(non_exhaustive_omitted_patterns)] match *self {
b'{'..=b'~' => true,
_ => false,
}matches!(*self, b'{'..=b'~')1076 }
10771078/// Checks if the value is an ASCII graphic character
1079 /// (i.e. not whitespace or control):
1080 /// U+0021 '!' ..= U+007E '~'.
1081 ///
1082 /// # Examples
1083 ///
1084 /// ```
1085 /// let uppercase_a = b'A';
1086 /// let uppercase_g = b'G';
1087 /// let a = b'a';
1088 /// let g = b'g';
1089 /// let zero = b'0';
1090 /// let percent = b'%';
1091 /// let space = b' ';
1092 /// let lf = b'\n';
1093 /// let esc = b'\x1b';
1094 ///
1095 /// assert!(uppercase_a.is_ascii_graphic());
1096 /// assert!(uppercase_g.is_ascii_graphic());
1097 /// assert!(a.is_ascii_graphic());
1098 /// assert!(g.is_ascii_graphic());
1099 /// assert!(zero.is_ascii_graphic());
1100 /// assert!(percent.is_ascii_graphic());
1101 /// assert!(!space.is_ascii_graphic());
1102 /// assert!(!lf.is_ascii_graphic());
1103 /// assert!(!esc.is_ascii_graphic());
1104 /// ```
1105#[must_use]
1106 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1107 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1108 #[inline]
1109pub const fn is_ascii_graphic(&self) -> bool {
1110#[allow(non_exhaustive_omitted_patterns)] match *self {
b'!'..=b'~' => true,
_ => false,
}matches!(*self, b'!'..=b'~')1111 }
11121113/// Checks if the value is an ASCII whitespace character:
1114 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
1115 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
1116 ///
1117 /// **Warning:** Because the list above excludes U+000B VERTICAL TAB,
1118 /// `b.is_ascii_whitespace()` is **not** equivalent to `char::from(b).is_whitespace()`.
1119 ///
1120 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
1121 /// whitespace][infra-aw]. There are several other definitions in
1122 /// wide use. For instance, [the POSIX locale][pct] includes
1123 /// U+000B VERTICAL TAB as well as all the above characters,
1124 /// but—from the very same specification—[the default rule for
1125 /// "field splitting" in the Bourne shell][bfs] considers *only*
1126 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
1127 ///
1128 /// If you are writing a program that will process an existing
1129 /// file format, check what that format's definition of whitespace is
1130 /// before using this function.
1131 ///
1132 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
1133 /// [pct]: https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/V1_chap07.html#tag_07_03_01
1134 /// [bfs]: https://pubs.opengroup.org/onlinepubs/9799919799/utilities/V3_chap02.html#tag_19_06_05
1135 ///
1136 /// # Examples
1137 ///
1138 /// ```
1139 /// let uppercase_a = b'A';
1140 /// let uppercase_g = b'G';
1141 /// let a = b'a';
1142 /// let g = b'g';
1143 /// let zero = b'0';
1144 /// let percent = b'%';
1145 /// let space = b' ';
1146 /// let lf = b'\n';
1147 /// let esc = b'\x1b';
1148 ///
1149 /// assert!(!uppercase_a.is_ascii_whitespace());
1150 /// assert!(!uppercase_g.is_ascii_whitespace());
1151 /// assert!(!a.is_ascii_whitespace());
1152 /// assert!(!g.is_ascii_whitespace());
1153 /// assert!(!zero.is_ascii_whitespace());
1154 /// assert!(!percent.is_ascii_whitespace());
1155 /// assert!(space.is_ascii_whitespace());
1156 /// assert!(lf.is_ascii_whitespace());
1157 /// assert!(!esc.is_ascii_whitespace());
1158 /// ```
1159#[must_use]
1160 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1161 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1162 #[inline]
1163pub const fn is_ascii_whitespace(&self) -> bool {
1164#[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' ')1165 }
11661167/// Checks if the value is an ASCII control character:
1168 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
1169 /// Note that most ASCII whitespace characters are control
1170 /// characters, but SPACE is not.
1171 ///
1172 /// # Examples
1173 ///
1174 /// ```
1175 /// let uppercase_a = b'A';
1176 /// let uppercase_g = b'G';
1177 /// let a = b'a';
1178 /// let g = b'g';
1179 /// let zero = b'0';
1180 /// let percent = b'%';
1181 /// let space = b' ';
1182 /// let lf = b'\n';
1183 /// let esc = b'\x1b';
1184 ///
1185 /// assert!(!uppercase_a.is_ascii_control());
1186 /// assert!(!uppercase_g.is_ascii_control());
1187 /// assert!(!a.is_ascii_control());
1188 /// assert!(!g.is_ascii_control());
1189 /// assert!(!zero.is_ascii_control());
1190 /// assert!(!percent.is_ascii_control());
1191 /// assert!(!space.is_ascii_control());
1192 /// assert!(lf.is_ascii_control());
1193 /// assert!(esc.is_ascii_control());
1194 /// ```
1195#[must_use]
1196 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1197 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1198 #[inline]
1199pub const fn is_ascii_control(&self) -> bool {
1200#[allow(non_exhaustive_omitted_patterns)] match *self {
b'\0'..=b'\x1F' | b'\x7F' => true,
_ => false,
}matches!(*self, b'\0'..=b'\x1F' | b'\x7F')1201 }
12021203/// Returns an iterator that produces an escaped version of a `u8`,
1204 /// treating it as an ASCII character.
1205 ///
1206 /// The behavior is identical to [`ascii::escape_default`].
1207 ///
1208 /// # Examples
1209 ///
1210 /// ```
1211 /// assert_eq!("0", b'0'.escape_ascii().to_string());
1212 /// assert_eq!("\\t", b'\t'.escape_ascii().to_string());
1213 /// assert_eq!("\\r", b'\r'.escape_ascii().to_string());
1214 /// assert_eq!("\\n", b'\n'.escape_ascii().to_string());
1215 /// assert_eq!("\\'", b'\''.escape_ascii().to_string());
1216 /// assert_eq!("\\\"", b'"'.escape_ascii().to_string());
1217 /// assert_eq!("\\\\", b'\\'.escape_ascii().to_string());
1218 /// assert_eq!("\\x9d", b'\x9d'.escape_ascii().to_string());
1219 /// ```
1220#[must_use = "this returns the escaped byte as an iterator, \
1221 without modifying the original"]
1222 #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
1223 #[inline]
1224pub fn escape_ascii(self) -> ascii::EscapeDefault {
1225 ascii::escape_default(self)
1226 }
12271228#[inline]
1229pub(crate) const fn is_utf8_char_boundary(self) -> bool {
1230// This is bit magic equivalent to: b < 128 || b >= 192
1231(selfas i8) >= -0x40
1232}
1233}
12341235impl u16 {
1236/// 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 = 0x003a;"]
///
#[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 = 0x003au16;"]
#[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.
///
/// This operation can be thought of as concatenating `self` and `right` into an
/// integer twice the size of
#[doc = "`u16`,"]
/// performing a left shift by `n`, and returning the **left half** of the result.
///
/// The name comes from "funneling" a wider integer to a narrower integer.
///
/// # Panics
///
/// ## Overflow behavior
///
/// If overflow checks are enabled (default in debug mode), this function will panic if `n`
/// is greater than or equal to the number of bits in `self`. If overflow checks are
/// disabled (default in release mode), there is no panic; instead, the value is shifted
/// by `n % Self::BITS`.
///
/// # Examples
///
/// ```
/// #![feature(funnel_shifts)]
///
#[doc = "let a = 0xa003_u16;"]
#[doc = "let b = 0x02de_u16;"]
///
#[doc = "assert_eq!(a.funnel_shl(b, 4), 0x0030);"]
///
/// // Using zeros as the right operand acts as a normal shift left
#[doc = "assert_eq!(a.funnel_shl(0, 4), a << 4);"]
///
/// // Shifting by 0 returns `self` unchanged
#[doc = "assert_eq!(a.funnel_shl(b, 0), a);"]
///
/// // Using the same value as the right operand acts as a rotate
#[doc = "assert_eq!(a.funnel_shl(a, 4), a.rotate_left(4));"]
/// ```
///
/// Note that while `funnel_shl` can act as a rotate, it does not allow for
/// rotating by an unbounded amount like [`rotate_left`](Self::rotate_left) does:
///
/// ```should_panic
/// #![feature(funnel_shifts)]
/// # #![feature(cfg_overflow_checks)]
/// # #[cfg(overflow_checks)] {
///
#[doc = "let a = u16::MAX;"]
/// // Okay
#[doc = "let _ = a.rotate_left(u16::BITS);"]
/// // Panics (only when overflow checks are enabled)
#[doc = "let _ = a.funnel_shl(a, u16::BITS);"]
/// # }
/// # #[cfg(not(overflow_checks))] panic!("fulfill should_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)]
#[rustc_inherit_overflow_checks]
pub const fn funnel_shl(self, right: Self, n: u32) -> Self {
if intrinsics::overflow_checks() {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift left with overflow"));
}
};
}
unsafe {
let n = n & (Self::BITS - 1);
self.unchecked_funnel_shl(right, n)
}
}
/// Performs a right funnel shift.
///
/// This operation can be thought of as concatenating `self` and `right` into an
/// integer twice the size of
#[doc = "`u16`,"]
/// performing a right shift by `n`, and returning the **right half** of the result.
///
/// The name comes from "funneling" a wider integer to a narrower integer.
///
/// # Panics
///
/// ## Overflow behavior
///
/// If overflow checks are enabled (default in debug mode), this function will panic if `n`
/// is greater than or equal to the number of bits in `self`. If overflow checks are
/// disabled (default in release mode), there is no panic; instead, the value is shifted
/// by `n % Self::BITS`.
///
/// # Examples
///
/// ```
/// #![feature(funnel_shifts)]
///
#[doc = "let a = 0xa003_u16;"]
#[doc = "let b = 0x02de_u16;"]
///
#[doc = "assert_eq!(a.funnel_shr(b, 4), 0x302d);"]
///
/// // Using zeros as the left operand acts as a normal shift right
#[doc = "assert_eq!(0_u16.funnel_shr(a, 4), a >> 4);"]
///
/// // Shifting by 0 returns `right` unchanged
#[doc = "assert_eq!(b.funnel_shr(a, 0), a);"]
///
/// // Using the same value as the right operand acts as a rotate
#[doc = "assert_eq!(a.funnel_shr(a, 4), a.rotate_right(4));"]
/// ```
///
/// Note that while `funnel_shr` can act as a rotate, it does not allow for
/// rotating by an unbounded amount like [`rotate_right`](Self::rotate_right) does:
///
/// ```should_panic
/// #![feature(funnel_shifts)]
/// # #![feature(cfg_overflow_checks)]
/// # #[cfg(overflow_checks)] {
///
#[doc = "let a = u16::MAX;"]
/// // Okay
#[doc = "let _ = a.rotate_right(u16::BITS);"]
/// // Panics (only when overflow checks are enabled)
#[doc = "let _ = a.funnel_shr(a, u16::BITS);"]
/// # }
/// # #[cfg(not(overflow_checks))] panic!("fulfill should_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)]
#[rustc_inherit_overflow_checks]
pub const fn funnel_shr(self, right: Self, n: u32) -> Self {
if intrinsics::overflow_checks() {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift right with overflow"));
}
};
}
unsafe {
let n = n & (Self::BITS - 1);
self.unchecked_funnel_shr(right, 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, right: 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, right, 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, right: 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, right, 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), 0x0928);"]
/// ```
#[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 = "1.99.0", 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 = "1.99.0", 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! {
1237Self = u16,
1238 ActualT = u16,
1239 SignedT = i16,
1240 BITS = 16,
1241 BITS_MINUS_ONE = 15,
1242 MAX = 65535,
1243 rot = 4,
1244 rot_op = "0xa003",
1245 rot_result = "0x003a",
1246 fsh_op = "0x02de",
1247 fshl_result = "0x0030",
1248 fshr_result = "0x302d",
1249 clmul_lhs = "0x9012",
1250 clmul_rhs = "0xcd34",
1251 clmul_result = "0x0928",
1252 swap_op = "0x1234",
1253 swapped = "0x3412",
1254 reversed = "0x2c48",
1255 le_bytes = "[0x34, 0x12]",
1256 be_bytes = "[0x12, 0x34]",
1257 to_xe_bytes_doc = "",
1258 from_xe_bytes_doc = "",
1259 bound_condition = "",
1260 }1261/// 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 }1262/// 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 }1263/// 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 }1264/// 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 }12651266/// Checks if the value is a Unicode surrogate code point, which are disallowed values for [`char`].
1267 ///
1268 /// # Examples
1269 ///
1270 /// ```
1271 /// #![feature(utf16_extra)]
1272 ///
1273 /// let low_non_surrogate = 0xA000u16;
1274 /// let low_surrogate = 0xD800u16;
1275 /// let high_surrogate = 0xDC00u16;
1276 /// let high_non_surrogate = 0xE000u16;
1277 ///
1278 /// assert!(!low_non_surrogate.is_utf16_surrogate());
1279 /// assert!(low_surrogate.is_utf16_surrogate());
1280 /// assert!(high_surrogate.is_utf16_surrogate());
1281 /// assert!(!high_non_surrogate.is_utf16_surrogate());
1282 /// ```
1283#[must_use]
1284 #[unstable(feature = "utf16_extra", issue = "94919")]
1285 #[inline]
1286pub const fn is_utf16_surrogate(self) -> bool {
1287#[allow(non_exhaustive_omitted_patterns)] match self {
0xD800..=0xDFFF => true,
_ => false,
}matches!(self, 0xD800..=0xDFFF)1288 }
1289}
12901291impl u32 {
1292/// 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 = 0x010000b3u32;"]
#[doc = "let m = 0x0000b301;"]
///
#[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 = 0x0000b301u32;"]
#[doc = "let m = 0x010000b3;"]
///
#[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.
///
/// This operation can be thought of as concatenating `self` and `right` into an
/// integer twice the size of
#[doc = "`u32`,"]
/// performing a left shift by `n`, and returning the **left half** of the result.
///
/// The name comes from "funneling" a wider integer to a narrower integer.
///
/// # Panics
///
/// ## Overflow behavior
///
/// If overflow checks are enabled (default in debug mode), this function will panic if `n`
/// is greater than or equal to the number of bits in `self`. If overflow checks are
/// disabled (default in release mode), there is no panic; instead, the value is shifted
/// by `n % Self::BITS`.
///
/// # Examples
///
/// ```
/// #![feature(funnel_shifts)]
///
#[doc = "let a = 0x010000b3_u32;"]
#[doc = "let b = 0x2fe78e45_u32;"]
///
#[doc = "assert_eq!(a.funnel_shl(b, 8), 0x0000b32f);"]
///
/// // Using zeros as the right operand acts as a normal shift left
#[doc = "assert_eq!(a.funnel_shl(0, 8), a << 8);"]
///
/// // Shifting by 0 returns `self` unchanged
#[doc = "assert_eq!(a.funnel_shl(b, 0), a);"]
///
/// // Using the same value as the right operand acts as a rotate
#[doc = "assert_eq!(a.funnel_shl(a, 8), a.rotate_left(8));"]
/// ```
///
/// Note that while `funnel_shl` can act as a rotate, it does not allow for
/// rotating by an unbounded amount like [`rotate_left`](Self::rotate_left) does:
///
/// ```should_panic
/// #![feature(funnel_shifts)]
/// # #![feature(cfg_overflow_checks)]
/// # #[cfg(overflow_checks)] {
///
#[doc = "let a = u32::MAX;"]
/// // Okay
#[doc = "let _ = a.rotate_left(u32::BITS);"]
/// // Panics (only when overflow checks are enabled)
#[doc = "let _ = a.funnel_shl(a, u32::BITS);"]
/// # }
/// # #[cfg(not(overflow_checks))] panic!("fulfill should_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)]
#[rustc_inherit_overflow_checks]
pub const fn funnel_shl(self, right: Self, n: u32) -> Self {
if intrinsics::overflow_checks() {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift left with overflow"));
}
};
}
unsafe {
let n = n & (Self::BITS - 1);
self.unchecked_funnel_shl(right, n)
}
}
/// Performs a right funnel shift.
///
/// This operation can be thought of as concatenating `self` and `right` into an
/// integer twice the size of
#[doc = "`u32`,"]
/// performing a right shift by `n`, and returning the **right half** of the result.
///
/// The name comes from "funneling" a wider integer to a narrower integer.
///
/// # Panics
///
/// ## Overflow behavior
///
/// If overflow checks are enabled (default in debug mode), this function will panic if `n`
/// is greater than or equal to the number of bits in `self`. If overflow checks are
/// disabled (default in release mode), there is no panic; instead, the value is shifted
/// by `n % Self::BITS`.
///
/// # Examples
///
/// ```
/// #![feature(funnel_shifts)]
///
#[doc = "let a = 0x010000b3_u32;"]
#[doc = "let b = 0x2fe78e45_u32;"]
///
#[doc = "assert_eq!(a.funnel_shr(b, 8), 0xb32fe78e);"]
///
/// // Using zeros as the left operand acts as a normal shift right
#[doc = "assert_eq!(0_u32.funnel_shr(a, 8), a >> 8);"]
///
/// // Shifting by 0 returns `right` unchanged
#[doc = "assert_eq!(b.funnel_shr(a, 0), a);"]
///
/// // Using the same value as the right operand acts as a rotate
#[doc = "assert_eq!(a.funnel_shr(a, 8), a.rotate_right(8));"]
/// ```
///
/// Note that while `funnel_shr` can act as a rotate, it does not allow for
/// rotating by an unbounded amount like [`rotate_right`](Self::rotate_right) does:
///
/// ```should_panic
/// #![feature(funnel_shifts)]
/// # #![feature(cfg_overflow_checks)]
/// # #[cfg(overflow_checks)] {
///
#[doc = "let a = u32::MAX;"]
/// // Okay
#[doc = "let _ = a.rotate_right(u32::BITS);"]
/// // Panics (only when overflow checks are enabled)
#[doc = "let _ = a.funnel_shr(a, u32::BITS);"]
/// # }
/// # #[cfg(not(overflow_checks))] panic!("fulfill should_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)]
#[rustc_inherit_overflow_checks]
pub const fn funnel_shr(self, right: Self, n: u32) -> Self {
if intrinsics::overflow_checks() {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift right with overflow"));
}
};
}
unsafe {
let n = n & (Self::BITS - 1);
self.unchecked_funnel_shr(right, 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, right: 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, right, 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, right: 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, right, 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 = "1.99.0", 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 = "1.99.0", 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! {
1293Self = u32,
1294 ActualT = u32,
1295 SignedT = i32,
1296 BITS = 32,
1297 BITS_MINUS_ONE = 31,
1298 MAX = 4294967295,
1299 rot = 8,
1300 rot_op = "0x010000b3",
1301 rot_result = "0x0000b301",
1302 fsh_op = "0x2fe78e45",
1303 fshl_result = "0x0000b32f",
1304 fshr_result = "0xb32fe78e",
1305 clmul_lhs = "0x56789012",
1306 clmul_rhs = "0xf52ecd34",
1307 clmul_result = "0x9b980928",
1308 swap_op = "0x12345678",
1309 swapped = "0x78563412",
1310 reversed = "0x1e6a2c48",
1311 le_bytes = "[0x78, 0x56, 0x34, 0x12]",
1312 be_bytes = "[0x12, 0x34, 0x56, 0x78]",
1313 to_xe_bytes_doc = "",
1314 from_xe_bytes_doc = "",
1315 bound_condition = "",
1316 }1317/// 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 }1318/// 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 }1319/// 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 }1320/// 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 }1321}
13221323impl u64 {
1324/// 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 = 0x0aa00000000006e1u64;"]
#[doc = "let m = 0x00000000006e10aa;"]
///
#[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 = 0x00000000006e10aau64;"]
#[doc = "let m = 0x0aa00000000006e1;"]
///
#[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.
///
/// This operation can be thought of as concatenating `self` and `right` into an
/// integer twice the size of
#[doc = "`u64`,"]
/// performing a left shift by `n`, and returning the **left half** of the result.
///
/// The name comes from "funneling" a wider integer to a narrower integer.
///
/// # Panics
///
/// ## Overflow behavior
///
/// If overflow checks are enabled (default in debug mode), this function will panic if `n`
/// is greater than or equal to the number of bits in `self`. If overflow checks are
/// disabled (default in release mode), there is no panic; instead, the value is shifted
/// by `n % Self::BITS`.
///
/// # Examples
///
/// ```
/// #![feature(funnel_shifts)]
///
#[doc = "let a = 0x0aa00000000006e1_u64;"]
#[doc = "let b = 0x2fe78e45983acd98_u64;"]
///
#[doc = "assert_eq!(a.funnel_shl(b, 12), 0x00000000006e12fe);"]
///
/// // Using zeros as the right operand acts as a normal shift left
#[doc = "assert_eq!(a.funnel_shl(0, 12), a << 12);"]
///
/// // Shifting by 0 returns `self` unchanged
#[doc = "assert_eq!(a.funnel_shl(b, 0), a);"]
///
/// // Using the same value as the right operand acts as a rotate
#[doc = "assert_eq!(a.funnel_shl(a, 12), a.rotate_left(12));"]
/// ```
///
/// Note that while `funnel_shl` can act as a rotate, it does not allow for
/// rotating by an unbounded amount like [`rotate_left`](Self::rotate_left) does:
///
/// ```should_panic
/// #![feature(funnel_shifts)]
/// # #![feature(cfg_overflow_checks)]
/// # #[cfg(overflow_checks)] {
///
#[doc = "let a = u64::MAX;"]
/// // Okay
#[doc = "let _ = a.rotate_left(u64::BITS);"]
/// // Panics (only when overflow checks are enabled)
#[doc = "let _ = a.funnel_shl(a, u64::BITS);"]
/// # }
/// # #[cfg(not(overflow_checks))] panic!("fulfill should_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)]
#[rustc_inherit_overflow_checks]
pub const fn funnel_shl(self, right: Self, n: u32) -> Self {
if intrinsics::overflow_checks() {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift left with overflow"));
}
};
}
unsafe {
let n = n & (Self::BITS - 1);
self.unchecked_funnel_shl(right, n)
}
}
/// Performs a right funnel shift.
///
/// This operation can be thought of as concatenating `self` and `right` into an
/// integer twice the size of
#[doc = "`u64`,"]
/// performing a right shift by `n`, and returning the **right half** of the result.
///
/// The name comes from "funneling" a wider integer to a narrower integer.
///
/// # Panics
///
/// ## Overflow behavior
///
/// If overflow checks are enabled (default in debug mode), this function will panic if `n`
/// is greater than or equal to the number of bits in `self`. If overflow checks are
/// disabled (default in release mode), there is no panic; instead, the value is shifted
/// by `n % Self::BITS`.
///
/// # Examples
///
/// ```
/// #![feature(funnel_shifts)]
///
#[doc = "let a = 0x0aa00000000006e1_u64;"]
#[doc = "let b = 0x2fe78e45983acd98_u64;"]
///
#[doc = "assert_eq!(a.funnel_shr(b, 12), 0x6e12fe78e45983ac);"]
///
/// // Using zeros as the left operand acts as a normal shift right
#[doc = "assert_eq!(0_u64.funnel_shr(a, 12), a >> 12);"]
///
/// // Shifting by 0 returns `right` unchanged
#[doc = "assert_eq!(b.funnel_shr(a, 0), a);"]
///
/// // Using the same value as the right operand acts as a rotate
#[doc = "assert_eq!(a.funnel_shr(a, 12), a.rotate_right(12));"]
/// ```
///
/// Note that while `funnel_shr` can act as a rotate, it does not allow for
/// rotating by an unbounded amount like [`rotate_right`](Self::rotate_right) does:
///
/// ```should_panic
/// #![feature(funnel_shifts)]
/// # #![feature(cfg_overflow_checks)]
/// # #[cfg(overflow_checks)] {
///
#[doc = "let a = u64::MAX;"]
/// // Okay
#[doc = "let _ = a.rotate_right(u64::BITS);"]
/// // Panics (only when overflow checks are enabled)
#[doc = "let _ = a.funnel_shr(a, u64::BITS);"]
/// # }
/// # #[cfg(not(overflow_checks))] panic!("fulfill should_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)]
#[rustc_inherit_overflow_checks]
pub const fn funnel_shr(self, right: Self, n: u32) -> Self {
if intrinsics::overflow_checks() {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift right with overflow"));
}
};
}
unsafe {
let n = n & (Self::BITS - 1);
self.unchecked_funnel_shr(right, 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, right: 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, right, 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, right: 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, right, 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), 0x0a6299579b980928);"]
/// ```
#[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 = "1.99.0", 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 = "1.99.0", 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! {
1325Self = u64,
1326 ActualT = u64,
1327 SignedT = i64,
1328 BITS = 64,
1329 BITS_MINUS_ONE = 63,
1330 MAX = 18446744073709551615,
1331 rot = 12,
1332 rot_op = "0x0aa00000000006e1",
1333 rot_result = "0x00000000006e10aa",
1334 fsh_op = "0x2fe78e45983acd98",
1335 fshl_result = "0x00000000006e12fe",
1336 fshr_result = "0x6e12fe78e45983ac",
1337 clmul_lhs = "0x7890123456789012",
1338 clmul_rhs = "0xdd358416f52ecd34",
1339 clmul_result = "0x0a6299579b980928",
1340 swap_op = "0x1234567890123456",
1341 swapped = "0x5634129078563412",
1342 reversed = "0x6a2c48091e6a2c48",
1343 le_bytes = "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
1344 be_bytes = "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
1345 to_xe_bytes_doc = "",
1346 from_xe_bytes_doc = "",
1347 bound_condition = "",
1348 }1349/// 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 }1350/// 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 }1351/// 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 }1352/// 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 }1353}
13541355impl u128 {
1356/// 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 = 0x0000000000000000000000004f7613f4;"]
///
#[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 = 0x0000000000000000000000004f7613f4u128;"]
#[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.
///
/// This operation can be thought of as concatenating `self` and `right` into an
/// integer twice the size of
#[doc = "`u128`,"]
/// performing a left shift by `n`, and returning the **left half** of the result.
///
/// The name comes from "funneling" a wider integer to a narrower integer.
///
/// # Panics
///
/// ## Overflow behavior
///
/// If overflow checks are enabled (default in debug mode), this function will panic if `n`
/// is greater than or equal to the number of bits in `self`. If overflow checks are
/// disabled (default in release mode), there is no panic; instead, the value is shifted
/// by `n % Self::BITS`.
///
/// # Examples
///
/// ```
/// #![feature(funnel_shifts)]
///
#[doc = "let a = 0x13f40000000000000000000000004f76_u128;"]
#[doc = "let b = 0x02fe78e45983acd98039000008736273_u128;"]
///
#[doc =
"assert_eq!(a.funnel_shl(b, 16), 0x0000000000000000000000004f7602fe);"]
///
/// // Using zeros as the right operand acts as a normal shift left
#[doc = "assert_eq!(a.funnel_shl(0, 16), a << 16);"]
///
/// // Shifting by 0 returns `self` unchanged
#[doc = "assert_eq!(a.funnel_shl(b, 0), a);"]
///
/// // Using the same value as the right operand acts as a rotate
#[doc = "assert_eq!(a.funnel_shl(a, 16), a.rotate_left(16));"]
/// ```
///
/// Note that while `funnel_shl` can act as a rotate, it does not allow for
/// rotating by an unbounded amount like [`rotate_left`](Self::rotate_left) does:
///
/// ```should_panic
/// #![feature(funnel_shifts)]
/// # #![feature(cfg_overflow_checks)]
/// # #[cfg(overflow_checks)] {
///
#[doc = "let a = u128::MAX;"]
/// // Okay
#[doc = "let _ = a.rotate_left(u128::BITS);"]
/// // Panics (only when overflow checks are enabled)
#[doc = "let _ = a.funnel_shl(a, u128::BITS);"]
/// # }
/// # #[cfg(not(overflow_checks))] panic!("fulfill should_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)]
#[rustc_inherit_overflow_checks]
pub const fn funnel_shl(self, right: Self, n: u32) -> Self {
if intrinsics::overflow_checks() {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift left with overflow"));
}
};
}
unsafe {
let n = n & (Self::BITS - 1);
self.unchecked_funnel_shl(right, n)
}
}
/// Performs a right funnel shift.
///
/// This operation can be thought of as concatenating `self` and `right` into an
/// integer twice the size of
#[doc = "`u128`,"]
/// performing a right shift by `n`, and returning the **right half** of the result.
///
/// The name comes from "funneling" a wider integer to a narrower integer.
///
/// # Panics
///
/// ## Overflow behavior
///
/// If overflow checks are enabled (default in debug mode), this function will panic if `n`
/// is greater than or equal to the number of bits in `self`. If overflow checks are
/// disabled (default in release mode), there is no panic; instead, the value is shifted
/// by `n % Self::BITS`.
///
/// # Examples
///
/// ```
/// #![feature(funnel_shifts)]
///
#[doc = "let a = 0x13f40000000000000000000000004f76_u128;"]
#[doc = "let b = 0x02fe78e45983acd98039000008736273_u128;"]
///
#[doc =
"assert_eq!(a.funnel_shr(b, 16), 0x4f7602fe78e45983acd9803900000873);"]
///
/// // Using zeros as the left operand acts as a normal shift right
#[doc = "assert_eq!(0_u128.funnel_shr(a, 16), a >> 16);"]
///
/// // Shifting by 0 returns `right` unchanged
#[doc = "assert_eq!(b.funnel_shr(a, 0), a);"]
///
/// // Using the same value as the right operand acts as a rotate
#[doc = "assert_eq!(a.funnel_shr(a, 16), a.rotate_right(16));"]
/// ```
///
/// Note that while `funnel_shr` can act as a rotate, it does not allow for
/// rotating by an unbounded amount like [`rotate_right`](Self::rotate_right) does:
///
/// ```should_panic
/// #![feature(funnel_shifts)]
/// # #![feature(cfg_overflow_checks)]
/// # #[cfg(overflow_checks)] {
///
#[doc = "let a = u128::MAX;"]
/// // Okay
#[doc = "let _ = a.rotate_right(u128::BITS);"]
/// // Panics (only when overflow checks are enabled)
#[doc = "let _ = a.funnel_shr(a, u128::BITS);"]
/// # }
/// # #[cfg(not(overflow_checks))] panic!("fulfill should_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)]
#[rustc_inherit_overflow_checks]
pub const fn funnel_shr(self, right: Self, n: u32) -> Self {
if intrinsics::overflow_checks() {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift right with overflow"));
}
};
}
unsafe {
let n = n & (Self::BITS - 1);
self.unchecked_funnel_shr(right, 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, right: 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, right, 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, right: 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, right, 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 = "1.99.0", 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 = "1.99.0", 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! {
1357Self = u128,
1358 ActualT = u128,
1359 SignedT = i128,
1360 BITS = 128,
1361 BITS_MINUS_ONE = 127,
1362 MAX = 340282366920938463463374607431768211455,
1363 rot = 16,
1364 rot_op = "0x13f40000000000000000000000004f76",
1365 rot_result = "0x0000000000000000000000004f7613f4",
1366 fsh_op = "0x02fe78e45983acd98039000008736273",
1367 fshl_result = "0x0000000000000000000000004f7602fe",
1368 fshr_result = "0x4f7602fe78e45983acd9803900000873",
1369 clmul_lhs = "0x12345678901234567890123456789012",
1370 clmul_rhs = "0x4317e40ab4ddcf05dd358416f52ecd34",
1371 clmul_result = "0xb9cf660de35d0c170a6299579b980928",
1372 swap_op = "0x12345678901234567890123456789012",
1373 swapped = "0x12907856341290785634129078563412",
1374 reversed = "0x48091e6a2c48091e6a2c48091e6a2c48",
1375 le_bytes = "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
1376 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
1377 be_bytes = "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
1378 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
1379 to_xe_bytes_doc = "",
1380 from_xe_bytes_doc = "",
1381 bound_condition = "",
1382 }1383/// 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 }1384/// 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 }1385}
13861387#[doc(auto_cfg = false)]
1388#[cfg(target_pointer_width = "16")]
1389impl usize {
1390uint_impl! {
1391Self = usize,
1392 ActualT = u16,
1393 SignedT = isize,
1394 BITS = 16,
1395 BITS_MINUS_ONE = 15,
1396 MAX = 65535,
1397 rot = 4,
1398 rot_op = "0xa003",
1399 rot_result = "0x003a",
1400 fsh_op = "0x02de",
1401 fshl_result = "0x0030",
1402 fshr_result = "0x302d",
1403 clmul_lhs = "0x9012",
1404 clmul_rhs = "0xcd34",
1405 clmul_result = "0x0928",
1406 swap_op = "0x1234",
1407 swapped = "0x3412",
1408 reversed = "0x2c48",
1409 le_bytes = "[0x34, 0x12]",
1410 be_bytes = "[0x12, 0x34]",
1411 to_xe_bytes_doc = usize_isize_to_xe_bytes_doc!(),
1412 from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(),
1413 bound_condition = " on 16-bit targets",
1414 }
1415midpoint_impl! { usize, u32, unsigned }
1416carrying_carryless_mul_impl! { usize, u32 }
1417}
14181419#[doc(auto_cfg = false)]
1420#[cfg(target_pointer_width = "32")]
1421impl usize {
1422uint_impl! {
1423Self = usize,
1424 ActualT = u32,
1425 SignedT = isize,
1426 BITS = 32,
1427 BITS_MINUS_ONE = 31,
1428 MAX = 4294967295,
1429 rot = 8,
1430 rot_op = "0x010000b3",
1431 rot_result = "0x0000b301",
1432 fsh_op = "0x2fe78e45",
1433 fshl_result = "0x0000b32f",
1434 fshr_result = "0xb32fe78e",
1435 clmul_lhs = "0x56789012",
1436 clmul_rhs = "0xf52ecd34",
1437 clmul_result = "0x9b980928",
1438 swap_op = "0x12345678",
1439 swapped = "0x78563412",
1440 reversed = "0x1e6a2c48",
1441 le_bytes = "[0x78, 0x56, 0x34, 0x12]",
1442 be_bytes = "[0x12, 0x34, 0x56, 0x78]",
1443 to_xe_bytes_doc = usize_isize_to_xe_bytes_doc!(),
1444 from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(),
1445 bound_condition = " on 32-bit targets",
1446 }
1447midpoint_impl! { usize, u64, unsigned }
1448carrying_carryless_mul_impl! { usize, u64 }
1449}
14501451#[doc(auto_cfg = false)]
1452#[cfg(target_pointer_width = "64")]
1453impl usize {
1454/// 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 = 0x0aa00000000006e1usize;"]
#[doc = "let m = 0x00000000006e10aa;"]
///
#[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 = 0x00000000006e10aausize;"]
#[doc = "let m = 0x0aa00000000006e1;"]
///
#[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.
///
/// This operation can be thought of as concatenating `self` and `right` into an
/// integer twice the size of
#[doc = "`usize`,"]
/// performing a left shift by `n`, and returning the **left half** of the result.
///
/// The name comes from "funneling" a wider integer to a narrower integer.
///
/// # Panics
///
/// ## Overflow behavior
///
/// If overflow checks are enabled (default in debug mode), this function will panic if `n`
/// is greater than or equal to the number of bits in `self`. If overflow checks are
/// disabled (default in release mode), there is no panic; instead, the value is shifted
/// by `n % Self::BITS`.
///
/// # Examples
///
/// ```
/// #![feature(funnel_shifts)]
///
#[doc = "let a = 0x0aa00000000006e1_usize;"]
#[doc = "let b = 0x2fe78e45983acd98_usize;"]
///
#[doc = "assert_eq!(a.funnel_shl(b, 12), 0x00000000006e12fe);"]
///
/// // Using zeros as the right operand acts as a normal shift left
#[doc = "assert_eq!(a.funnel_shl(0, 12), a << 12);"]
///
/// // Shifting by 0 returns `self` unchanged
#[doc = "assert_eq!(a.funnel_shl(b, 0), a);"]
///
/// // Using the same value as the right operand acts as a rotate
#[doc = "assert_eq!(a.funnel_shl(a, 12), a.rotate_left(12));"]
/// ```
///
/// Note that while `funnel_shl` can act as a rotate, it does not allow for
/// rotating by an unbounded amount like [`rotate_left`](Self::rotate_left) does:
///
/// ```should_panic
/// #![feature(funnel_shifts)]
/// # #![feature(cfg_overflow_checks)]
/// # #[cfg(overflow_checks)] {
///
#[doc = "let a = usize::MAX;"]
/// // Okay
#[doc = "let _ = a.rotate_left(usize::BITS);"]
/// // Panics (only when overflow checks are enabled)
#[doc = "let _ = a.funnel_shl(a, usize::BITS);"]
/// # }
/// # #[cfg(not(overflow_checks))] panic!("fulfill should_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)]
#[rustc_inherit_overflow_checks]
pub const fn funnel_shl(self, right: Self, n: u32) -> Self {
if intrinsics::overflow_checks() {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift left with overflow"));
}
};
}
unsafe {
let n = n & (Self::BITS - 1);
self.unchecked_funnel_shl(right, n)
}
}
/// Performs a right funnel shift.
///
/// This operation can be thought of as concatenating `self` and `right` into an
/// integer twice the size of
#[doc = "`usize`,"]
/// performing a right shift by `n`, and returning the **right half** of the result.
///
/// The name comes from "funneling" a wider integer to a narrower integer.
///
/// # Panics
///
/// ## Overflow behavior
///
/// If overflow checks are enabled (default in debug mode), this function will panic if `n`
/// is greater than or equal to the number of bits in `self`. If overflow checks are
/// disabled (default in release mode), there is no panic; instead, the value is shifted
/// by `n % Self::BITS`.
///
/// # Examples
///
/// ```
/// #![feature(funnel_shifts)]
///
#[doc = "let a = 0x0aa00000000006e1_usize;"]
#[doc = "let b = 0x2fe78e45983acd98_usize;"]
///
#[doc = "assert_eq!(a.funnel_shr(b, 12), 0x6e12fe78e45983ac);"]
///
/// // Using zeros as the left operand acts as a normal shift right
#[doc = "assert_eq!(0_usize.funnel_shr(a, 12), a >> 12);"]
///
/// // Shifting by 0 returns `right` unchanged
#[doc = "assert_eq!(b.funnel_shr(a, 0), a);"]
///
/// // Using the same value as the right operand acts as a rotate
#[doc = "assert_eq!(a.funnel_shr(a, 12), a.rotate_right(12));"]
/// ```
///
/// Note that while `funnel_shr` can act as a rotate, it does not allow for
/// rotating by an unbounded amount like [`rotate_right`](Self::rotate_right) does:
///
/// ```should_panic
/// #![feature(funnel_shifts)]
/// # #![feature(cfg_overflow_checks)]
/// # #[cfg(overflow_checks)] {
///
#[doc = "let a = usize::MAX;"]
/// // Okay
#[doc = "let _ = a.rotate_right(usize::BITS);"]
/// // Panics (only when overflow checks are enabled)
#[doc = "let _ = a.funnel_shr(a, usize::BITS);"]
/// # }
/// # #[cfg(not(overflow_checks))] panic!("fulfill should_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)]
#[rustc_inherit_overflow_checks]
pub const fn funnel_shr(self, right: Self, n: u32) -> Self {
if intrinsics::overflow_checks() {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift right with overflow"));
}
};
}
unsafe {
let n = n & (Self::BITS - 1);
self.unchecked_funnel_shr(right, 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, right: 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, right, 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, right: 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, right, 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 = "1.99.0", 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 = "1.99.0", 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! {
1455Self = usize,
1456 ActualT = u64,
1457 SignedT = isize,
1458 BITS = 64,
1459 BITS_MINUS_ONE = 63,
1460 MAX = 18446744073709551615,
1461 rot = 12,
1462 rot_op = "0x0aa00000000006e1",
1463 rot_result = "0x00000000006e10aa",
1464 fsh_op = "0x2fe78e45983acd98",
1465 fshl_result = "0x00000000006e12fe",
1466 fshr_result = "0x6e12fe78e45983ac",
1467 clmul_lhs = "0x7890123456789012",
1468 clmul_rhs = "0xdd358416f52ecd34",
1469 clmul_result = "0xa6299579b980928",
1470 swap_op = "0x1234567890123456",
1471 swapped = "0x5634129078563412",
1472 reversed = "0x6a2c48091e6a2c48",
1473 le_bytes = "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
1474 be_bytes = "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
1475 to_xe_bytes_doc = usize_isize_to_xe_bytes_doc!(),
1476 from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(),
1477 bound_condition = " on 64-bit targets",
1478 }1479/// 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 }1480/// 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 }1481}
14821483impl usize {
1484/// Returns an `usize` where every byte is equal to `x`.
1485#[inline]
1486pub(crate) const fn repeat_u8(x: u8) -> usize {
1487usize::from_ne_bytes([x; size_of::<usize>()])
1488 }
14891490/// Returns an `usize` where every byte pair is equal to `x`.
1491#[inline]
1492pub(crate) const fn repeat_u16(x: u16) -> usize {
1493let mut r = 0usize;
1494let mut i = 0;
1495while i < size_of::<usize>() {
1496// Use `wrapping_shl` to make it work on targets with 16-bit `usize`
1497r = r.wrapping_shl(16) | (x as usize);
1498 i += 2;
1499 }
1500r1501 }
1502}
15031504/// A classification of floating point numbers.
1505///
1506/// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
1507/// their documentation for more.
1508///
1509/// # Examples
1510///
1511/// ```
1512/// use std::num::FpCategory;
1513///
1514/// let num = 12.4_f32;
1515/// let inf = f32::INFINITY;
1516/// let zero = 0f32;
1517/// let sub: f32 = 1.1754942e-38;
1518/// let nan = f32::NAN;
1519///
1520/// assert_eq!(num.classify(), FpCategory::Normal);
1521/// assert_eq!(inf.classify(), FpCategory::Infinite);
1522/// assert_eq!(zero.classify(), FpCategory::Zero);
1523/// assert_eq!(sub.classify(), FpCategory::Subnormal);
1524/// assert_eq!(nan.classify(), FpCategory::Nan);
1525/// ```
1526#[derive(#[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl crate::marker::Copy for FpCategory { }Copy, #[automatically_derived]
#[doc(hidden)]
#[stable(feature = "rust1", since = "1.0.0")]
unsafe impl crate::clone::TrivialClone for FpCategory { }
#[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::marker::StructuralPartialEq for FpCategory { }
#[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)]
1527#[stable(feature = "rust1", since = "1.0.0")]
1528pub enum FpCategory {
1529/// NaN (not a number): this value results from calculations like `(-1.0).sqrt()`.
1530 ///
1531 /// See [the documentation for `f32`](f32) for more information on the unusual properties
1532 /// of NaN.
1533#[stable(feature = "rust1", since = "1.0.0")]
1534Nan,
15351536/// Positive or negative infinity, which often results from dividing a nonzero number
1537 /// by zero.
1538#[stable(feature = "rust1", since = "1.0.0")]
1539Infinite,
15401541/// Positive or negative zero.
1542 ///
1543 /// See [the documentation for `f32`](f32) for more information on the signedness of zeroes.
1544#[stable(feature = "rust1", since = "1.0.0")]
1545Zero,
15461547/// “Subnormal” or “denormal” floating point representation (less precise, relative to
1548 /// their magnitude, than [`Normal`]).
1549 ///
1550 /// Subnormal numbers are larger in magnitude than [`Zero`] but smaller in magnitude than all
1551 /// [`Normal`] numbers.
1552 ///
1553 /// [`Normal`]: Self::Normal
1554 /// [`Zero`]: Self::Zero
1555#[stable(feature = "rust1", since = "1.0.0")]
1556Subnormal,
15571558/// A regular floating point number, not any of the exceptional categories.
1559 ///
1560 /// The smallest positive normal numbers are [`f32::MIN_POSITIVE`] and [`f64::MIN_POSITIVE`],
1561 /// and the largest positive normal numbers are [`f32::MAX`] and [`f64::MAX`]. (Unlike signed
1562 /// integers, floating point numbers are symmetric in their range, so negating any of these
1563 /// constants will produce their negative counterpart.)
1564#[stable(feature = "rust1", since = "1.0.0")]
1565Normal,
1566}
15671568/// Determines if a string of text of that length of that radix could be guaranteed to be
1569/// stored in the given type T.
1570/// Note that if the radix is known to the compiler, it is just the check of digits.len that
1571/// is done at runtime.
1572#[doc(hidden)]
1573#[inline(always)]
1574#[unstable(issue = "none", feature = "std_internals")]
1575pub const fn can_not_overflow<T>(radix: u32, is_signed_ty: bool, digits: &[u8]) -> bool {
1576radix <= 16 && digits.len() <= size_of::<T>() * 2 - is_signed_tyas usize1577}
15781579#[cfg_attr(not(panic = "immediate-abort"), inline(never))]
1580#[cfg_attr(panic = "immediate-abort", inline)]
1581#[cold]
1582#[track_caller]
1583const fn from_ascii_bytes_radix_panic(radix: u32) -> ! {
1584{
#[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_bytes_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_bytes_radix: radix must lie in the range `[2, 36]`"));
}
}
}
const_eval_select((radix,), compiletime, runtime)
}
}
do_panic(radix)
}const_panic!(
1585"from_ascii_bytes_radix: radix must lie in the range `[2, 36]`",
1586"from_ascii_bytes_radix: radix must lie in the range `[2, 36]` - found {radix}",
1587 radix: u32 = radix,
1588 )1589}
15901591macro_rules!from_str_int_impl {
1592 ($signedness:ident $($int_ty:ty)+) => {$(
1593#[stable(feature = "rust1", since = "1.0.0")]
1594 #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1595const impl FromStr for $int_ty {
1596type Err = ParseIntError;
15971598/// Parses an integer from a string slice with decimal digits.
1599 ///
1600 /// The characters are expected to be an optional
1601#[doc = sign_dependent_expr!{
1602$signedness ?
1603if signed {
1604" `+` or `-` "
1605}
1606if unsigned {
1607" `+` "
1608}
1609 }]
1610/// sign followed by only digits. Leading and trailing non-digit characters (including
1611 /// whitespace) represent an error. Underscores (which are accepted in Rust literals)
1612 /// also represent an error.
1613 ///
1614 /// # See also
1615 /// For parsing numbers in other bases, such as binary or hexadecimal,
1616 /// see [`from_str_radix`][Self::from_str_radix].
1617 ///
1618 /// # Examples
1619 ///
1620 /// ```
1621 /// use std::str::FromStr;
1622 ///
1623#[doc = concat!("assert_eq!(", stringify!($int_ty), "::from_str(\"+10\"), Ok(10));")]
1624/// ```
1625 /// Trailing space returns error:
1626 /// ```
1627 /// # use std::str::FromStr;
1628 /// #
1629#[doc = concat!("assert!(", stringify!($int_ty), "::from_str(\"1 \").is_err());")]
1630/// ```
1631#[inline]
1632fn from_str(src: &str) -> Result<$int_ty, ParseIntError> {
1633 <$int_ty>::from_str_radix(src, 10)
1634 }
1635 }
16361637impl $int_ty {
1638/// Parses an integer from a string slice with digits in a given base.
1639 ///
1640 /// The string is expected to be an optional
1641#[doc = sign_dependent_expr!{
1642$signedness ?
1643if signed {
1644" `+` or `-` "
1645}
1646if unsigned {
1647" `+` "
1648}
1649 }]
1650/// sign followed by only digits. Leading and trailing non-digit characters (including
1651 /// whitespace) represent an error. Underscores (which are accepted in Rust literals)
1652 /// also represent an error.
1653 ///
1654 /// Digits are a subset of these characters, depending on `radix`:
1655 /// * `0-9`
1656 /// * `a-z`
1657 /// * `A-Z`
1658 ///
1659 /// # Panics
1660 ///
1661 /// This function panics if `radix` is not in the range from 2 to 36.
1662 ///
1663 /// # See also
1664 /// If the string to be parsed is in base 10 (decimal),
1665 /// [`from_str`] or [`str::parse`] can also be used.
1666 ///
1667// FIXME(#122566): These HTML links work around a rustdoc-json test failure.
1668/// [`from_str`]: #method.from_str
1669 /// [`str::parse`]: primitive.str.html#method.parse
1670 ///
1671 /// # Examples
1672 ///
1673 /// ```
1674#[doc = concat!("assert_eq!(", stringify!($int_ty), "::from_str_radix(\"A\", 16), Ok(10));")]
1675/// ```
1676 /// Trailing space returns error:
1677 /// ```
1678#[doc = concat!("assert!(", stringify!($int_ty), "::from_str_radix(\"1 \", 10).is_err());")]
1679/// ```
1680#[stable(feature = "rust1", since = "1.0.0")]
1681 #[rustc_const_stable(feature = "const_int_from_str", since = "1.82.0")]
1682 #[inline]
1683pub const fn from_str_radix(src: &str, radix: u32) -> Result<$int_ty, ParseIntError> {
1684 <$int_ty>::from_ascii_bytes_radix_impl(src.as_bytes(), radix)
1685 }
16861687/// Parses an integer from an ASCII-byte slice with decimal digits.
1688 ///
1689 /// The characters are expected to be an optional
1690#[doc = sign_dependent_expr!{
1691$signedness ?
1692if signed {
1693" `+` or `-` "
1694}
1695if unsigned {
1696" `+` "
1697}
1698 }]
1699/// sign followed by only digits. Leading and trailing non-digit characters (including
1700 /// whitespace) represent an error. Underscores (which are accepted in Rust literals)
1701 /// also represent an error.
1702 ///
1703 /// # Examples
1704 ///
1705 /// ```
1706 /// #![feature(int_from_ascii)]
1707 ///
1708#[doc = concat!("assert_eq!(", stringify!($int_ty), "::from_ascii_bytes(b\"+10\"), Ok(10));")]
1709/// ```
1710 /// Trailing space returns error:
1711 /// ```
1712 /// # #![feature(int_from_ascii)]
1713 /// #
1714#[doc = concat!("assert!(", stringify!($int_ty), "::from_ascii_bytes(b\"1 \").is_err());")]
1715/// ```
1716#[unstable(feature = "int_from_ascii", issue = "134821")]
1717 #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1718 #[inline]
1719pub const fn from_ascii_bytes<T>(src: T) -> Result<$int_ty, ParseIntError>
1720where
1721T: [const] AsRef<[u8]> + [const] crate::marker::Destruct
1722 {
1723 <$int_ty>::from_ascii_bytes_radix(src.as_ref(), 10)
1724 }
17251726/// Parses an integer from an ASCII-byte slice with digits in a given base.
1727 ///
1728 /// The characters are expected to be an optional
1729#[doc = sign_dependent_expr!{
1730$signedness ?
1731if signed {
1732" `+` or `-` "
1733}
1734if unsigned {
1735" `+` "
1736}
1737 }]
1738/// sign followed by only digits. Leading and trailing non-digit characters (including
1739 /// whitespace) represent an error. Underscores (which are accepted in Rust literals)
1740 /// also represent an error.
1741 ///
1742 /// Digits are a subset of these characters, depending on `radix`:
1743 /// * `0-9`
1744 /// * `a-z`
1745 /// * `A-Z`
1746 ///
1747 /// # Panics
1748 ///
1749 /// This function panics if `radix` is not in the range from 2 to 36.
1750 ///
1751 /// # Examples
1752 ///
1753 /// ```
1754 /// #![feature(int_from_ascii)]
1755 ///
1756#[doc = concat!("assert_eq!(", stringify!($int_ty), "::from_ascii_bytes_radix(b\"A\", 16), Ok(10));")]
1757/// ```
1758 /// Trailing space returns error:
1759 /// ```
1760 /// # #![feature(int_from_ascii)]
1761 /// #
1762#[doc = concat!("assert!(", stringify!($int_ty), "::from_ascii_bytes_radix(b\"1 \", 10).is_err());")]
1763/// ```
1764#[unstable(feature = "int_from_ascii", issue = "134821")]
1765 #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1766 #[inline]
1767pub const fn from_ascii_bytes_radix<T>(src: T, radix: u32) -> Result<$int_ty, ParseIntError>
1768where
1769T: [const] AsRef<[u8]> + [const] crate::marker::Destruct
1770 {
1771 <$int_ty>::from_ascii_bytes_radix_impl(src.as_ref(), radix)
1772 }
17731774#[inline]
1775pub(super) const fn from_ascii_bytes_radix_impl(src: &[u8], radix: u32) -> Result<$int_ty, ParseIntError> {
1776use self::IntErrorKind::*;
1777use self::ParseIntError as PIE;
17781779if 2 > radix || radix > 36 {
1780 from_ascii_bytes_radix_panic(radix);
1781 }
17821783if src.is_empty() {
1784return Err(PIE { kind: Empty });
1785 }
17861787#[allow(unused_comparisons)]
1788let is_signed_ty = 0 > <$int_ty>::MIN;
17891790let (is_positive, mut digits) = match src {
1791 [b'+' | b'-'] => {
1792return Err(PIE { kind: InvalidDigit });
1793 }
1794 [b'+', rest @ ..] => (true, rest),
1795 [b'-', rest @ ..] if is_signed_ty => (false, rest),
1796_ => (true, src),
1797 };
17981799let mut result = 0;
18001801macro_rules! unwrap_or_PIE {
1802 ($option:expr, $kind:ident) => {
1803match $option {
1804Some(value) => value,
1805None => return Err(PIE { kind: $kind }),
1806 }
1807 };
1808 }
18091810if can_not_overflow::<$int_ty>(radix, is_signed_ty, digits) {
1811// If the len of the str is short compared to the range of the type
1812 // we are parsing into, then we can be certain that an overflow will not occur.
1813 // This bound is when `radix.pow(digits.len()) - 1 <= T::MAX` but the condition
1814 // above is a faster (conservative) approximation of this.
1815 //
1816 // Consider radix 16 as it has the highest information density per digit and will thus overflow the earliest:
1817 // `u8::MAX` is `ff` - any str of len 2 is guaranteed to not overflow.
1818 // `i8::MAX` is `7f` - only a str of len 1 is guaranteed to not overflow.
1819macro_rules! run_unchecked_loop {
1820 ($unchecked_additive_op:tt) => {{
1821while let [c, rest @ ..] = digits {
1822 result = result * (radix as $int_ty);
1823let x = unwrap_or_PIE!((*c as char).to_digit(radix), InvalidDigit);
1824 result = result $unchecked_additive_op (x as $int_ty);
1825 digits = rest;
1826 }
1827 }};
1828 }
1829if is_positive {
1830run_unchecked_loop!(+)
1831 } else {
1832run_unchecked_loop!(-)
1833 };
1834 } else {
1835macro_rules! run_checked_loop {
1836 ($checked_additive_op:ident, $overflow_err:ident) => {{
1837while let [c, rest @ ..] = digits {
1838// When `radix` is passed in as a literal, rather than doing a slow `imul`
1839 // the compiler can use shifts if `radix` can be expressed as a
1840 // sum of powers of 2 (x*10 can be written as x*8 + x*2).
1841 // When the compiler can't use these optimisations,
1842 // the latency of the multiplication can be hidden by issuing it
1843 // before the result is needed to improve performance on
1844 // modern out-of-order CPU as multiplication here is slower
1845 // than the other instructions, we can get the end result faster
1846 // doing multiplication first and let the CPU spends other cycles
1847 // doing other computation and get multiplication result later.
1848let mul = result.checked_mul(radix as $int_ty);
1849let x = unwrap_or_PIE!((*c as char).to_digit(radix), InvalidDigit) as $int_ty;
1850 result = unwrap_or_PIE!(mul, $overflow_err);
1851 result = unwrap_or_PIE!(<$int_ty>::$checked_additive_op(result, x), $overflow_err);
1852 digits = rest;
1853 }
1854 }};
1855 }
1856if is_positive {
1857run_checked_loop!(checked_add, PosOverflow)
1858 } else {
1859run_checked_loop!(checked_sub, NegOverflow)
1860 };
1861 }
1862Ok(result)
1863 }
1864 }
1865 )*}
1866}
18671868#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
const impl FromStr for isize {
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!(isize::from_str(\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # use std::str::FromStr;
/// #
#[doc = "assert!(isize::from_str(\"1 \").is_err());"]
/// ```
#[inline]
fn from_str(src: &str) -> Result<isize, ParseIntError> {
<isize>::from_str_radix(src, 10)
}
}
impl isize {
/// 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!(isize::from_str_radix(\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
#[doc = "assert!(isize::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<isize, ParseIntError> {
<isize>::from_ascii_bytes_radix_impl(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!(isize::from_ascii_bytes(b\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(isize::from_ascii_bytes(b\"1 \").is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[inline]
pub const fn from_ascii_bytes<T>(src: T) -> Result<isize, ParseIntError>
where T: [const] AsRef<[u8]> + [const] crate::marker::Destruct {
<isize>::from_ascii_bytes_radix(src.as_ref(), 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!(isize::from_ascii_bytes_radix(b\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(isize::from_ascii_bytes_radix(b\"1 \", 10).is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[inline]
pub const fn from_ascii_bytes_radix<T>(src: T, radix: u32)
-> Result<isize, ParseIntError> where T: [const] AsRef<[u8]> + [const]
crate::marker::Destruct {
<isize>::from_ascii_bytes_radix_impl(src.as_ref(), radix)
}
#[inline]
pub(super) const fn from_ascii_bytes_radix_impl(src: &[u8], radix: u32)
-> Result<isize, ParseIntError> {
use self::IntErrorKind::*;
use self::ParseIntError as PIE;
if 2 > radix || radix > 36 { from_ascii_bytes_radix_panic(radix); }
if src.is_empty() { return Err(PIE { kind: Empty }); }
#[allow(unused_comparisons)]
let is_signed_ty = 0 > <isize>::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::<isize>(radix, is_signed_ty, digits) {
macro_rules! run_unchecked_loop {
($unchecked_additive_op : tt) =>
{{
while let [c, rest @ ..] = digits
{
result = result * (radix as isize); let x = unwrap_or_PIE!
((* c as char).to_digit(radix), InvalidDigit); result =
result $unchecked_additive_op(x as isize); digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
result = result * (radix as isize);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result + (x as isize);
digits = rest;
}
}
} else {
{
while let [c, rest @ ..] = digits {
result = result * (radix as isize);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result - (x as isize);
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 isize); let x =
unwrap_or_PIE! ((* c as char).to_digit(radix), InvalidDigit)
as isize; result = unwrap_or_PIE! (mul, $overflow_err);
result = unwrap_or_PIE!
(< isize > :: $checked_additive_op(result, x),
$overflow_err); digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
let mul = result.checked_mul(radix as isize);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as isize;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: PosOverflow }),
};
result =
match <isize>::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 isize);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as isize;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
result =
match <isize>::checked_sub(result, x) {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
digits = rest;
}
}
};
}
Ok(result)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
const impl FromStr for i8 {
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!(i8::from_str(\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # use std::str::FromStr;
/// #
#[doc = "assert!(i8::from_str(\"1 \").is_err());"]
/// ```
#[inline]
fn from_str(src: &str) -> Result<i8, ParseIntError> {
<i8>::from_str_radix(src, 10)
}
}
impl i8 {
/// 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!(i8::from_str_radix(\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
#[doc = "assert!(i8::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<i8, ParseIntError> {
<i8>::from_ascii_bytes_radix_impl(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!(i8::from_ascii_bytes(b\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(i8::from_ascii_bytes(b\"1 \").is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[inline]
pub const fn from_ascii_bytes<T>(src: T) -> Result<i8, ParseIntError>
where T: [const] AsRef<[u8]> + [const] crate::marker::Destruct {
<i8>::from_ascii_bytes_radix(src.as_ref(), 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!(i8::from_ascii_bytes_radix(b\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(i8::from_ascii_bytes_radix(b\"1 \", 10).is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[inline]
pub const fn from_ascii_bytes_radix<T>(src: T, radix: u32)
-> Result<i8, ParseIntError> where T: [const] AsRef<[u8]> + [const]
crate::marker::Destruct {
<i8>::from_ascii_bytes_radix_impl(src.as_ref(), radix)
}
#[inline]
pub(super) const fn from_ascii_bytes_radix_impl(src: &[u8], radix: u32)
-> Result<i8, ParseIntError> {
use self::IntErrorKind::*;
use self::ParseIntError as PIE;
if 2 > radix || radix > 36 { from_ascii_bytes_radix_panic(radix); }
if src.is_empty() { return Err(PIE { kind: Empty }); }
#[allow(unused_comparisons)]
let is_signed_ty = 0 > <i8>::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::<i8>(radix, is_signed_ty, digits) {
macro_rules! run_unchecked_loop {
($unchecked_additive_op : tt) =>
{{
while let [c, rest @ ..] = digits
{
result = result * (radix as i8); let x = unwrap_or_PIE!
((* c as char).to_digit(radix), InvalidDigit); result =
result $unchecked_additive_op(x as i8); digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
result = result * (radix as i8);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result + (x as i8);
digits = rest;
}
}
} else {
{
while let [c, rest @ ..] = digits {
result = result * (radix as i8);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result - (x as i8);
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 i8); let x =
unwrap_or_PIE! ((* c as char).to_digit(radix), InvalidDigit)
as i8; result = unwrap_or_PIE! (mul, $overflow_err); result
= unwrap_or_PIE!
(< i8 > :: $checked_additive_op(result, x), $overflow_err);
digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
let mul = result.checked_mul(radix as i8);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as i8;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: PosOverflow }),
};
result =
match <i8>::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 i8);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as i8;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
result =
match <i8>::checked_sub(result, x) {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
digits = rest;
}
}
};
}
Ok(result)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
const impl FromStr for i16 {
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!(i16::from_str(\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # use std::str::FromStr;
/// #
#[doc = "assert!(i16::from_str(\"1 \").is_err());"]
/// ```
#[inline]
fn from_str(src: &str) -> Result<i16, ParseIntError> {
<i16>::from_str_radix(src, 10)
}
}
impl i16 {
/// 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!(i16::from_str_radix(\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
#[doc = "assert!(i16::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<i16, ParseIntError> {
<i16>::from_ascii_bytes_radix_impl(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!(i16::from_ascii_bytes(b\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(i16::from_ascii_bytes(b\"1 \").is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[inline]
pub const fn from_ascii_bytes<T>(src: T) -> Result<i16, ParseIntError>
where T: [const] AsRef<[u8]> + [const] crate::marker::Destruct {
<i16>::from_ascii_bytes_radix(src.as_ref(), 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!(i16::from_ascii_bytes_radix(b\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(i16::from_ascii_bytes_radix(b\"1 \", 10).is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[inline]
pub const fn from_ascii_bytes_radix<T>(src: T, radix: u32)
-> Result<i16, ParseIntError> where T: [const] AsRef<[u8]> + [const]
crate::marker::Destruct {
<i16>::from_ascii_bytes_radix_impl(src.as_ref(), radix)
}
#[inline]
pub(super) const fn from_ascii_bytes_radix_impl(src: &[u8], radix: u32)
-> Result<i16, ParseIntError> {
use self::IntErrorKind::*;
use self::ParseIntError as PIE;
if 2 > radix || radix > 36 { from_ascii_bytes_radix_panic(radix); }
if src.is_empty() { return Err(PIE { kind: Empty }); }
#[allow(unused_comparisons)]
let is_signed_ty = 0 > <i16>::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::<i16>(radix, is_signed_ty, digits) {
macro_rules! run_unchecked_loop {
($unchecked_additive_op : tt) =>
{{
while let [c, rest @ ..] = digits
{
result = result * (radix as i16); let x = unwrap_or_PIE!
((* c as char).to_digit(radix), InvalidDigit); result =
result $unchecked_additive_op(x as i16); digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
result = result * (radix as i16);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result + (x as i16);
digits = rest;
}
}
} else {
{
while let [c, rest @ ..] = digits {
result = result * (radix as i16);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result - (x as i16);
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 i16); let x =
unwrap_or_PIE! ((* c as char).to_digit(radix), InvalidDigit)
as i16; result = unwrap_or_PIE! (mul, $overflow_err); result
= unwrap_or_PIE!
(< i16 > :: $checked_additive_op(result, x), $overflow_err);
digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
let mul = result.checked_mul(radix as i16);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as i16;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: PosOverflow }),
};
result =
match <i16>::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 i16);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as i16;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
result =
match <i16>::checked_sub(result, x) {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
digits = rest;
}
}
};
}
Ok(result)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
const impl FromStr for i32 {
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!(i32::from_str(\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # use std::str::FromStr;
/// #
#[doc = "assert!(i32::from_str(\"1 \").is_err());"]
/// ```
#[inline]
fn from_str(src: &str) -> Result<i32, ParseIntError> {
<i32>::from_str_radix(src, 10)
}
}
impl i32 {
/// 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!(i32::from_str_radix(\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
#[doc = "assert!(i32::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<i32, ParseIntError> {
<i32>::from_ascii_bytes_radix_impl(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!(i32::from_ascii_bytes(b\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(i32::from_ascii_bytes(b\"1 \").is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[inline]
pub const fn from_ascii_bytes<T>(src: T) -> Result<i32, ParseIntError>
where T: [const] AsRef<[u8]> + [const] crate::marker::Destruct {
<i32>::from_ascii_bytes_radix(src.as_ref(), 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!(i32::from_ascii_bytes_radix(b\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(i32::from_ascii_bytes_radix(b\"1 \", 10).is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[inline]
pub const fn from_ascii_bytes_radix<T>(src: T, radix: u32)
-> Result<i32, ParseIntError> where T: [const] AsRef<[u8]> + [const]
crate::marker::Destruct {
<i32>::from_ascii_bytes_radix_impl(src.as_ref(), radix)
}
#[inline]
pub(super) const fn from_ascii_bytes_radix_impl(src: &[u8], radix: u32)
-> Result<i32, ParseIntError> {
use self::IntErrorKind::*;
use self::ParseIntError as PIE;
if 2 > radix || radix > 36 { from_ascii_bytes_radix_panic(radix); }
if src.is_empty() { return Err(PIE { kind: Empty }); }
#[allow(unused_comparisons)]
let is_signed_ty = 0 > <i32>::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::<i32>(radix, is_signed_ty, digits) {
macro_rules! run_unchecked_loop {
($unchecked_additive_op : tt) =>
{{
while let [c, rest @ ..] = digits
{
result = result * (radix as i32); let x = unwrap_or_PIE!
((* c as char).to_digit(radix), InvalidDigit); result =
result $unchecked_additive_op(x as i32); digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
result = result * (radix as i32);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result + (x as i32);
digits = rest;
}
}
} else {
{
while let [c, rest @ ..] = digits {
result = result * (radix as i32);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result - (x as i32);
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 i32); let x =
unwrap_or_PIE! ((* c as char).to_digit(radix), InvalidDigit)
as i32; result = unwrap_or_PIE! (mul, $overflow_err); result
= unwrap_or_PIE!
(< i32 > :: $checked_additive_op(result, x), $overflow_err);
digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
let mul = result.checked_mul(radix as i32);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as i32;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: PosOverflow }),
};
result =
match <i32>::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 i32);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as i32;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
result =
match <i32>::checked_sub(result, x) {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
digits = rest;
}
}
};
}
Ok(result)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
const impl FromStr for i64 {
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!(i64::from_str(\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # use std::str::FromStr;
/// #
#[doc = "assert!(i64::from_str(\"1 \").is_err());"]
/// ```
#[inline]
fn from_str(src: &str) -> Result<i64, ParseIntError> {
<i64>::from_str_radix(src, 10)
}
}
impl i64 {
/// 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!(i64::from_str_radix(\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
#[doc = "assert!(i64::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<i64, ParseIntError> {
<i64>::from_ascii_bytes_radix_impl(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!(i64::from_ascii_bytes(b\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(i64::from_ascii_bytes(b\"1 \").is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[inline]
pub const fn from_ascii_bytes<T>(src: T) -> Result<i64, ParseIntError>
where T: [const] AsRef<[u8]> + [const] crate::marker::Destruct {
<i64>::from_ascii_bytes_radix(src.as_ref(), 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!(i64::from_ascii_bytes_radix(b\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(i64::from_ascii_bytes_radix(b\"1 \", 10).is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[inline]
pub const fn from_ascii_bytes_radix<T>(src: T, radix: u32)
-> Result<i64, ParseIntError> where T: [const] AsRef<[u8]> + [const]
crate::marker::Destruct {
<i64>::from_ascii_bytes_radix_impl(src.as_ref(), radix)
}
#[inline]
pub(super) const fn from_ascii_bytes_radix_impl(src: &[u8], radix: u32)
-> Result<i64, ParseIntError> {
use self::IntErrorKind::*;
use self::ParseIntError as PIE;
if 2 > radix || radix > 36 { from_ascii_bytes_radix_panic(radix); }
if src.is_empty() { return Err(PIE { kind: Empty }); }
#[allow(unused_comparisons)]
let is_signed_ty = 0 > <i64>::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::<i64>(radix, is_signed_ty, digits) {
macro_rules! run_unchecked_loop {
($unchecked_additive_op : tt) =>
{{
while let [c, rest @ ..] = digits
{
result = result * (radix as i64); let x = unwrap_or_PIE!
((* c as char).to_digit(radix), InvalidDigit); result =
result $unchecked_additive_op(x as i64); digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
result = result * (radix as i64);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result + (x as i64);
digits = rest;
}
}
} else {
{
while let [c, rest @ ..] = digits {
result = result * (radix as i64);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result - (x as i64);
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 i64); let x =
unwrap_or_PIE! ((* c as char).to_digit(radix), InvalidDigit)
as i64; result = unwrap_or_PIE! (mul, $overflow_err); result
= unwrap_or_PIE!
(< i64 > :: $checked_additive_op(result, x), $overflow_err);
digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
let mul = result.checked_mul(radix as i64);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as i64;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: PosOverflow }),
};
result =
match <i64>::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 i64);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as i64;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
result =
match <i64>::checked_sub(result, x) {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
digits = rest;
}
}
};
}
Ok(result)
}
}
#[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_bytes_radix_impl(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_bytes(b\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(i128::from_ascii_bytes(b\"1 \").is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[inline]
pub const fn from_ascii_bytes<T>(src: T) -> Result<i128, ParseIntError>
where T: [const] AsRef<[u8]> + [const] crate::marker::Destruct {
<i128>::from_ascii_bytes_radix(src.as_ref(), 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_bytes_radix(b\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(i128::from_ascii_bytes_radix(b\"1 \", 10).is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[inline]
pub const fn from_ascii_bytes_radix<T>(src: T, radix: u32)
-> Result<i128, ParseIntError> where T: [const] AsRef<[u8]> + [const]
crate::marker::Destruct {
<i128>::from_ascii_bytes_radix_impl(src.as_ref(), radix)
}
#[inline]
pub(super) const fn from_ascii_bytes_radix_impl(src: &[u8], radix: u32)
-> Result<i128, ParseIntError> {
use self::IntErrorKind::*;
use self::ParseIntError as PIE;
if 2 > radix || radix > 36 { from_ascii_bytes_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 }1869#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
const impl FromStr for usize {
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!(usize::from_str(\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # use std::str::FromStr;
/// #
#[doc = "assert!(usize::from_str(\"1 \").is_err());"]
/// ```
#[inline]
fn from_str(src: &str) -> Result<usize, ParseIntError> {
<usize>::from_str_radix(src, 10)
}
}
impl usize {
/// 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!(usize::from_str_radix(\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
#[doc = "assert!(usize::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<usize, ParseIntError> {
<usize>::from_ascii_bytes_radix_impl(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!(usize::from_ascii_bytes(b\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(usize::from_ascii_bytes(b\"1 \").is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[inline]
pub const fn from_ascii_bytes<T>(src: T) -> Result<usize, ParseIntError>
where T: [const] AsRef<[u8]> + [const] crate::marker::Destruct {
<usize>::from_ascii_bytes_radix(src.as_ref(), 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!(usize::from_ascii_bytes_radix(b\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(usize::from_ascii_bytes_radix(b\"1 \", 10).is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[inline]
pub const fn from_ascii_bytes_radix<T>(src: T, radix: u32)
-> Result<usize, ParseIntError> where T: [const] AsRef<[u8]> + [const]
crate::marker::Destruct {
<usize>::from_ascii_bytes_radix_impl(src.as_ref(), radix)
}
#[inline]
pub(super) const fn from_ascii_bytes_radix_impl(src: &[u8], radix: u32)
-> Result<usize, ParseIntError> {
use self::IntErrorKind::*;
use self::ParseIntError as PIE;
if 2 > radix || radix > 36 { from_ascii_bytes_radix_panic(radix); }
if src.is_empty() { return Err(PIE { kind: Empty }); }
#[allow(unused_comparisons)]
let is_signed_ty = 0 > <usize>::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::<usize>(radix, is_signed_ty, digits) {
macro_rules! run_unchecked_loop {
($unchecked_additive_op : tt) =>
{{
while let [c, rest @ ..] = digits
{
result = result * (radix as usize); let x = unwrap_or_PIE!
((* c as char).to_digit(radix), InvalidDigit); result =
result $unchecked_additive_op(x as usize); digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
result = result * (radix as usize);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result + (x as usize);
digits = rest;
}
}
} else {
{
while let [c, rest @ ..] = digits {
result = result * (radix as usize);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result - (x as usize);
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 usize); let x =
unwrap_or_PIE! ((* c as char).to_digit(radix), InvalidDigit)
as usize; result = unwrap_or_PIE! (mul, $overflow_err);
result = unwrap_or_PIE!
(< usize > :: $checked_additive_op(result, x),
$overflow_err); digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
let mul = result.checked_mul(radix as usize);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as usize;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: PosOverflow }),
};
result =
match <usize>::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 usize);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as usize;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
result =
match <usize>::checked_sub(result, x) {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
digits = rest;
}
}
};
}
Ok(result)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
const impl FromStr for u8 {
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!(u8::from_str(\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # use std::str::FromStr;
/// #
#[doc = "assert!(u8::from_str(\"1 \").is_err());"]
/// ```
#[inline]
fn from_str(src: &str) -> Result<u8, ParseIntError> {
<u8>::from_str_radix(src, 10)
}
}
impl u8 {
/// 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!(u8::from_str_radix(\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
#[doc = "assert!(u8::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<u8, ParseIntError> {
<u8>::from_ascii_bytes_radix_impl(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!(u8::from_ascii_bytes(b\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(u8::from_ascii_bytes(b\"1 \").is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[inline]
pub const fn from_ascii_bytes<T>(src: T) -> Result<u8, ParseIntError>
where T: [const] AsRef<[u8]> + [const] crate::marker::Destruct {
<u8>::from_ascii_bytes_radix(src.as_ref(), 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!(u8::from_ascii_bytes_radix(b\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(u8::from_ascii_bytes_radix(b\"1 \", 10).is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[inline]
pub const fn from_ascii_bytes_radix<T>(src: T, radix: u32)
-> Result<u8, ParseIntError> where T: [const] AsRef<[u8]> + [const]
crate::marker::Destruct {
<u8>::from_ascii_bytes_radix_impl(src.as_ref(), radix)
}
#[inline]
pub(super) const fn from_ascii_bytes_radix_impl(src: &[u8], radix: u32)
-> Result<u8, ParseIntError> {
use self::IntErrorKind::*;
use self::ParseIntError as PIE;
if 2 > radix || radix > 36 { from_ascii_bytes_radix_panic(radix); }
if src.is_empty() { return Err(PIE { kind: Empty }); }
#[allow(unused_comparisons)]
let is_signed_ty = 0 > <u8>::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::<u8>(radix, is_signed_ty, digits) {
macro_rules! run_unchecked_loop {
($unchecked_additive_op : tt) =>
{{
while let [c, rest @ ..] = digits
{
result = result * (radix as u8); let x = unwrap_or_PIE!
((* c as char).to_digit(radix), InvalidDigit); result =
result $unchecked_additive_op(x as u8); digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
result = result * (radix as u8);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result + (x as u8);
digits = rest;
}
}
} else {
{
while let [c, rest @ ..] = digits {
result = result * (radix as u8);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result - (x as u8);
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 u8); let x =
unwrap_or_PIE! ((* c as char).to_digit(radix), InvalidDigit)
as u8; result = unwrap_or_PIE! (mul, $overflow_err); result
= unwrap_or_PIE!
(< u8 > :: $checked_additive_op(result, x), $overflow_err);
digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
let mul = result.checked_mul(radix as u8);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as u8;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: PosOverflow }),
};
result =
match <u8>::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 u8);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as u8;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
result =
match <u8>::checked_sub(result, x) {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
digits = rest;
}
}
};
}
Ok(result)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
const impl FromStr for u16 {
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!(u16::from_str(\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # use std::str::FromStr;
/// #
#[doc = "assert!(u16::from_str(\"1 \").is_err());"]
/// ```
#[inline]
fn from_str(src: &str) -> Result<u16, ParseIntError> {
<u16>::from_str_radix(src, 10)
}
}
impl u16 {
/// 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!(u16::from_str_radix(\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
#[doc = "assert!(u16::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<u16, ParseIntError> {
<u16>::from_ascii_bytes_radix_impl(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!(u16::from_ascii_bytes(b\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(u16::from_ascii_bytes(b\"1 \").is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[inline]
pub const fn from_ascii_bytes<T>(src: T) -> Result<u16, ParseIntError>
where T: [const] AsRef<[u8]> + [const] crate::marker::Destruct {
<u16>::from_ascii_bytes_radix(src.as_ref(), 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!(u16::from_ascii_bytes_radix(b\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(u16::from_ascii_bytes_radix(b\"1 \", 10).is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[inline]
pub const fn from_ascii_bytes_radix<T>(src: T, radix: u32)
-> Result<u16, ParseIntError> where T: [const] AsRef<[u8]> + [const]
crate::marker::Destruct {
<u16>::from_ascii_bytes_radix_impl(src.as_ref(), radix)
}
#[inline]
pub(super) const fn from_ascii_bytes_radix_impl(src: &[u8], radix: u32)
-> Result<u16, ParseIntError> {
use self::IntErrorKind::*;
use self::ParseIntError as PIE;
if 2 > radix || radix > 36 { from_ascii_bytes_radix_panic(radix); }
if src.is_empty() { return Err(PIE { kind: Empty }); }
#[allow(unused_comparisons)]
let is_signed_ty = 0 > <u16>::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::<u16>(radix, is_signed_ty, digits) {
macro_rules! run_unchecked_loop {
($unchecked_additive_op : tt) =>
{{
while let [c, rest @ ..] = digits
{
result = result * (radix as u16); let x = unwrap_or_PIE!
((* c as char).to_digit(radix), InvalidDigit); result =
result $unchecked_additive_op(x as u16); digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
result = result * (radix as u16);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result + (x as u16);
digits = rest;
}
}
} else {
{
while let [c, rest @ ..] = digits {
result = result * (radix as u16);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result - (x as u16);
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 u16); let x =
unwrap_or_PIE! ((* c as char).to_digit(radix), InvalidDigit)
as u16; result = unwrap_or_PIE! (mul, $overflow_err); result
= unwrap_or_PIE!
(< u16 > :: $checked_additive_op(result, x), $overflow_err);
digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
let mul = result.checked_mul(radix as u16);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as u16;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: PosOverflow }),
};
result =
match <u16>::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 u16);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as u16;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
result =
match <u16>::checked_sub(result, x) {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
digits = rest;
}
}
};
}
Ok(result)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
const impl FromStr for u32 {
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!(u32::from_str(\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # use std::str::FromStr;
/// #
#[doc = "assert!(u32::from_str(\"1 \").is_err());"]
/// ```
#[inline]
fn from_str(src: &str) -> Result<u32, ParseIntError> {
<u32>::from_str_radix(src, 10)
}
}
impl u32 {
/// 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!(u32::from_str_radix(\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
#[doc = "assert!(u32::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<u32, ParseIntError> {
<u32>::from_ascii_bytes_radix_impl(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!(u32::from_ascii_bytes(b\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(u32::from_ascii_bytes(b\"1 \").is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[inline]
pub const fn from_ascii_bytes<T>(src: T) -> Result<u32, ParseIntError>
where T: [const] AsRef<[u8]> + [const] crate::marker::Destruct {
<u32>::from_ascii_bytes_radix(src.as_ref(), 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!(u32::from_ascii_bytes_radix(b\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(u32::from_ascii_bytes_radix(b\"1 \", 10).is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[inline]
pub const fn from_ascii_bytes_radix<T>(src: T, radix: u32)
-> Result<u32, ParseIntError> where T: [const] AsRef<[u8]> + [const]
crate::marker::Destruct {
<u32>::from_ascii_bytes_radix_impl(src.as_ref(), radix)
}
#[inline]
pub(super) const fn from_ascii_bytes_radix_impl(src: &[u8], radix: u32)
-> Result<u32, ParseIntError> {
use self::IntErrorKind::*;
use self::ParseIntError as PIE;
if 2 > radix || radix > 36 { from_ascii_bytes_radix_panic(radix); }
if src.is_empty() { return Err(PIE { kind: Empty }); }
#[allow(unused_comparisons)]
let is_signed_ty = 0 > <u32>::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::<u32>(radix, is_signed_ty, digits) {
macro_rules! run_unchecked_loop {
($unchecked_additive_op : tt) =>
{{
while let [c, rest @ ..] = digits
{
result = result * (radix as u32); let x = unwrap_or_PIE!
((* c as char).to_digit(radix), InvalidDigit); result =
result $unchecked_additive_op(x as u32); digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
result = result * (radix as u32);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result + (x as u32);
digits = rest;
}
}
} else {
{
while let [c, rest @ ..] = digits {
result = result * (radix as u32);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result - (x as u32);
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 u32); let x =
unwrap_or_PIE! ((* c as char).to_digit(radix), InvalidDigit)
as u32; result = unwrap_or_PIE! (mul, $overflow_err); result
= unwrap_or_PIE!
(< u32 > :: $checked_additive_op(result, x), $overflow_err);
digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
let mul = result.checked_mul(radix as u32);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as u32;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: PosOverflow }),
};
result =
match <u32>::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 u32);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as u32;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
result =
match <u32>::checked_sub(result, x) {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
digits = rest;
}
}
};
}
Ok(result)
}
}
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
const impl FromStr for u64 {
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!(u64::from_str(\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # use std::str::FromStr;
/// #
#[doc = "assert!(u64::from_str(\"1 \").is_err());"]
/// ```
#[inline]
fn from_str(src: &str) -> Result<u64, ParseIntError> {
<u64>::from_str_radix(src, 10)
}
}
impl u64 {
/// 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!(u64::from_str_radix(\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
#[doc = "assert!(u64::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<u64, ParseIntError> {
<u64>::from_ascii_bytes_radix_impl(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!(u64::from_ascii_bytes(b\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(u64::from_ascii_bytes(b\"1 \").is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[inline]
pub const fn from_ascii_bytes<T>(src: T) -> Result<u64, ParseIntError>
where T: [const] AsRef<[u8]> + [const] crate::marker::Destruct {
<u64>::from_ascii_bytes_radix(src.as_ref(), 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!(u64::from_ascii_bytes_radix(b\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(u64::from_ascii_bytes_radix(b\"1 \", 10).is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[inline]
pub const fn from_ascii_bytes_radix<T>(src: T, radix: u32)
-> Result<u64, ParseIntError> where T: [const] AsRef<[u8]> + [const]
crate::marker::Destruct {
<u64>::from_ascii_bytes_radix_impl(src.as_ref(), radix)
}
#[inline]
pub(super) const fn from_ascii_bytes_radix_impl(src: &[u8], radix: u32)
-> Result<u64, ParseIntError> {
use self::IntErrorKind::*;
use self::ParseIntError as PIE;
if 2 > radix || radix > 36 { from_ascii_bytes_radix_panic(radix); }
if src.is_empty() { return Err(PIE { kind: Empty }); }
#[allow(unused_comparisons)]
let is_signed_ty = 0 > <u64>::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::<u64>(radix, is_signed_ty, digits) {
macro_rules! run_unchecked_loop {
($unchecked_additive_op : tt) =>
{{
while let [c, rest @ ..] = digits
{
result = result * (radix as u64); let x = unwrap_or_PIE!
((* c as char).to_digit(radix), InvalidDigit); result =
result $unchecked_additive_op(x as u64); digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
result = result * (radix as u64);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result + (x as u64);
digits = rest;
}
}
} else {
{
while let [c, rest @ ..] = digits {
result = result * (radix as u64);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result - (x as u64);
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 u64); let x =
unwrap_or_PIE! ((* c as char).to_digit(radix), InvalidDigit)
as u64; result = unwrap_or_PIE! (mul, $overflow_err); result
= unwrap_or_PIE!
(< u64 > :: $checked_additive_op(result, x), $overflow_err);
digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
let mul = result.checked_mul(radix as u64);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as u64;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: PosOverflow }),
};
result =
match <u64>::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 u64);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as u64;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
result =
match <u64>::checked_sub(result, x) {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
digits = rest;
}
}
};
}
Ok(result)
}
}
#[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_bytes_radix_impl(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_bytes(b\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(u128::from_ascii_bytes(b\"1 \").is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[inline]
pub const fn from_ascii_bytes<T>(src: T) -> Result<u128, ParseIntError>
where T: [const] AsRef<[u8]> + [const] crate::marker::Destruct {
<u128>::from_ascii_bytes_radix(src.as_ref(), 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_bytes_radix(b\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(u128::from_ascii_bytes_radix(b\"1 \", 10).is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
#[inline]
pub const fn from_ascii_bytes_radix<T>(src: T, radix: u32)
-> Result<u128, ParseIntError> where T: [const] AsRef<[u8]> + [const]
crate::marker::Destruct {
<u128>::from_ascii_bytes_radix_impl(src.as_ref(), radix)
}
#[inline]
pub(super) const fn from_ascii_bytes_radix_impl(src: &[u8], radix: u32)
-> Result<u128, ParseIntError> {
use self::IntErrorKind::*;
use self::ParseIntError as PIE;
if 2 > radix || radix > 36 { from_ascii_bytes_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 }