1//! Numeric traits and functions for the built-in numeric types.
23#![stable(feature = "rust1", since = "1.0.0")]
45use crate::panic::const_panic;
6use crate::str::FromStr;
7use crate::ub_checks::assert_unsafe_precondition;
8use crate::{ascii, intrinsics, mem};
910// FIXME(const-hack): Used because the `?` operator is not allowed in a const context.
11macro_rules!try_opt {
12 ($e:expr) => {
13match $e {
14Some(x) => x,
15None => return None,
16 }
17 };
18}
1920// Use this when the generated code should differ between signed and unsigned types.
21macro_rules!sign_dependent_expr {
22 (signed ? if signed { $signed_case:expr } if unsigned { $unsigned_case:expr } ) => {
23$signed_case
24};
25 (unsigned ? if signed { $signed_case:expr } if unsigned { $unsigned_case:expr } ) => {
26$unsigned_case
27};
28}
2930// These modules are public only for testing.
31#[doc(hidden)]
32#[unstable(
33 feature = "num_internals",
34 reason = "internal routines only exposed for testing",
35 issue = "none"
36)]
37pub mod imp;
3839#[macro_use]
40mod int_macros; // import int_impl!
41#[macro_use]
42mod uint_macros; // import uint_impl!
4344mod error;
45#[cfg(not(no_fp_fmt_parse))]
46mod float_parse;
47mod nonzero;
48mod saturating;
49mod traits;
50mod wrapping;
5152/// 100% perma-unstable
53#[doc(hidden)]
54pub mod niche_types;
5556#[stable(feature = "int_error_matching", since = "1.55.0")]
57pub use error::IntErrorKind;
58#[stable(feature = "rust1", since = "1.0.0")]
59pub use error::ParseIntError;
60#[stable(feature = "try_from", since = "1.34.0")]
61pub use error::TryFromIntError;
62#[stable(feature = "rust1", since = "1.0.0")]
63#[cfg(not(no_fp_fmt_parse))]
64pub use float_parse::ParseFloatError;
65#[stable(feature = "generic_nonzero", since = "1.79.0")]
66pub use nonzero::NonZero;
67#[unstable(
68 feature = "nonzero_internals",
69 reason = "implementation detail which may disappear or be replaced at any time",
70 issue = "none"
71)]
72pub use nonzero::ZeroablePrimitive;
73#[stable(feature = "signed_nonzero", since = "1.34.0")]
74pub use nonzero::{NonZeroI8, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI128, NonZeroIsize};
75#[stable(feature = "nonzero", since = "1.28.0")]
76pub use nonzero::{NonZeroU8, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU128, NonZeroUsize};
77#[stable(feature = "saturating_int_impl", since = "1.74.0")]
78pub use saturating::Saturating;
79#[stable(feature = "rust1", since = "1.0.0")]
80pub use wrapping::Wrapping;
8182macro_rules!u8_xe_bytes_doc {
83 () => {
84"
8586**Note**: This function is meaningless on `u8`. Byte order does not exist as a
87concept for byte-sized integers. This function is only provided in symmetry
88with larger integer types.
8990"
91};
92}
9394macro_rules!i8_xe_bytes_doc {
95 () => {
96"
9798**Note**: This function is meaningless on `i8`. Byte order does not exist as a
99concept for byte-sized integers. This function is only provided in symmetry
100with larger integer types. You can cast from and to `u8` using
101[`cast_signed`](u8::cast_signed) and [`cast_unsigned`](Self::cast_unsigned).
102103"
104};
105}
106107macro_rules!usize_isize_to_xe_bytes_doc {
108 () => {
109"
110111**Note**: This function returns an array of length 2, 4 or 8 bytes
112depending on the target pointer size.
113114"
115};
116}
117118macro_rules!usize_isize_from_xe_bytes_doc {
119 () => {
120"
121122**Note**: This function takes an array of length 2, 4 or 8 bytes
123depending on the target pointer size.
124125"
126};
127}
128129macro_rules!midpoint_impl {
130 ($SelfT:ty, unsigned) => {
131/// Calculates the midpoint (average) between `self` and `rhs`.
132 ///
133 /// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
134 /// sufficiently-large unsigned integral type. This implies that the result is
135 /// always rounded towards zero and that no overflow will ever occur.
136 ///
137 /// # Examples
138 ///
139 /// ```
140#[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(4), 2);")]
141 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".midpoint(4), 2);")]
142/// ```
143#[stable(feature = "num_midpoint", since = "1.85.0")]
144 #[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
145 #[must_use = "this returns the result of the operation, \
146 without modifying the original"]
147 #[doc(alias = "average_floor")]
148 #[doc(alias = "average")]
149 #[inline]
150pub const fn midpoint(self, rhs: $SelfT) -> $SelfT {
151// Use the well known branchless algorithm from Hacker's Delight to compute
152 // `(a + b) / 2` without overflowing: `((a ^ b) >> 1) + (a & b)`.
153((self ^ rhs) >> 1) + (self & rhs)
154 }
155 };
156 ($SelfT:ty, signed) => {
157/// Calculates the midpoint (average) between `self` and `rhs`.
158 ///
159 /// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
160 /// sufficiently-large signed integral type. This implies that the result is
161 /// always rounded towards zero and that no overflow will ever occur.
162 ///
163 /// # Examples
164 ///
165 /// ```
166#[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(4), 2);")]
167 #[doc = concat!("assert_eq!((-1", stringify!($SelfT), ").midpoint(2), 0);")]
168 #[doc = concat!("assert_eq!((-7", stringify!($SelfT), ").midpoint(0), -3);")]
169 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(-7), -3);")]
170 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(7), 3);")]
171/// ```
172#[stable(feature = "num_midpoint_signed", since = "1.87.0")]
173 #[rustc_const_stable(feature = "num_midpoint_signed", since = "1.87.0")]
174 #[must_use = "this returns the result of the operation, \
175 without modifying the original"]
176 #[doc(alias = "average_floor")]
177 #[doc(alias = "average_ceil")]
178 #[doc(alias = "average")]
179 #[inline]
180pub const fn midpoint(self, rhs: Self) -> Self {
181// Use the well known branchless algorithm from Hacker's Delight to compute
182 // `(a + b) / 2` without overflowing: `((a ^ b) >> 1) + (a & b)`.
183let t = ((self ^ rhs) >> 1) + (self & rhs);
184// Except that it fails for integers whose sum is an odd negative number as
185 // their floor is one less than their average. So we adjust the result.
186t + (if t < 0 { 1 } else { 0 } & (self ^ rhs))
187 }
188 };
189 ($SelfT:ty, $WideT:ty, unsigned) => {
190/// Calculates the midpoint (average) between `self` and `rhs`.
191 ///
192 /// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
193 /// sufficiently-large unsigned integral type. This implies that the result is
194 /// always rounded towards zero and that no overflow will ever occur.
195 ///
196 /// # Examples
197 ///
198 /// ```
199#[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(4), 2);")]
200 #[doc = concat!("assert_eq!(1", stringify!($SelfT), ".midpoint(4), 2);")]
201/// ```
202#[stable(feature = "num_midpoint", since = "1.85.0")]
203 #[rustc_const_stable(feature = "num_midpoint", since = "1.85.0")]
204 #[must_use = "this returns the result of the operation, \
205 without modifying the original"]
206 #[doc(alias = "average_floor")]
207 #[doc(alias = "average")]
208 #[inline]
209pub const fn midpoint(self, rhs: $SelfT) -> $SelfT {
210 ((self as $WideT + rhs as $WideT) / 2) as $SelfT
211}
212 };
213 ($SelfT:ty, $WideT:ty, signed) => {
214/// Calculates the midpoint (average) between `self` and `rhs`.
215 ///
216 /// `midpoint(a, b)` is `(a + b) / 2` as if it were performed in a
217 /// sufficiently-large signed integral type. This implies that the result is
218 /// always rounded towards zero and that no overflow will ever occur.
219 ///
220 /// # Examples
221 ///
222 /// ```
223#[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(4), 2);")]
224 #[doc = concat!("assert_eq!((-1", stringify!($SelfT), ").midpoint(2), 0);")]
225 #[doc = concat!("assert_eq!((-7", stringify!($SelfT), ").midpoint(0), -3);")]
226 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(-7), -3);")]
227 #[doc = concat!("assert_eq!(0", stringify!($SelfT), ".midpoint(7), 3);")]
228/// ```
229#[stable(feature = "num_midpoint_signed", since = "1.87.0")]
230 #[rustc_const_stable(feature = "num_midpoint_signed", since = "1.87.0")]
231 #[must_use = "this returns the result of the operation, \
232 without modifying the original"]
233 #[doc(alias = "average_floor")]
234 #[doc(alias = "average_ceil")]
235 #[doc(alias = "average")]
236 #[inline]
237pub const fn midpoint(self, rhs: $SelfT) -> $SelfT {
238 ((self as $WideT + rhs as $WideT) / 2) as $SelfT
239}
240 };
241}
242243macro_rules!widening_mul_impl {
244 ($SelfT:ty, $WideT:ty) => {
245/// Widening multiplication. Computes `self * rhs`, widening to a larger integer.
246 ///
247 /// The returned value is always exact and can never overflow.
248 ///
249 /// Note that this method is semantically equivalent to [`carrying_mul`] with a
250 /// carry of zero, with the latter instead returning a tuple denoting the low and
251 /// high parts of the result. Consider using it instead if you need
252 /// interoperability with other big int helper functions, or if this method isn't
253 /// available for a given type.
254 ///
255 /// [`carrying_mul`]: Self::carrying_mul
256 ///
257 /// # Examples
258 ///
259 /// ```
260 /// #![feature(widening_mul)]
261 ///
262#[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.widening_mul(0_", stringify!($SelfT), "), 0);")]
263 #[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.widening_mul(", stringify!($SelfT), "::MAX), ", stringify!($SelfT), "::MAX as ", stringify!($WideT), " * ", stringify!($SelfT), "::MAX as ", stringify!($WideT), ");")]
264/// ```
265#[unstable(feature = "widening_mul", issue = "152016")]
266 #[rustc_const_unstable(feature = "widening_mul", issue = "152016")]
267 #[must_use = "this returns the result of the operation, \
268 without modifying the original"]
269 #[inline]
270pub const fn widening_mul(self, rhs: Self) -> $WideT {
271self as $WideT * rhs as $WideT
272}
273 }
274}
275276macro_rules!widening_carryless_mul_impl {
277 ($SelfT:ty, $WideT:ty) => {
278/// Performs a widening carry-less multiplication.
279 ///
280 /// # Examples
281 ///
282 /// ```
283 /// #![feature(uint_carryless_mul)]
284 ///
285#[doc = concat!("assert_eq!(", stringify!($SelfT), "::MAX.widening_carryless_mul(",
286stringify!($SelfT), "::MAX), ", stringify!($WideT), "::MAX / 3);")]
287/// ```
288#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
289 #[doc(alias = "clmul")]
290 #[unstable(feature = "uint_carryless_mul", issue = "152080")]
291 #[must_use = "this returns the result of the operation, \
292 without modifying the original"]
293 #[inline]
294pub const fn widening_carryless_mul(self, rhs: $SelfT) -> $WideT {
295 (self as $WideT).carryless_mul(rhs as $WideT)
296 }
297 }
298}
299300macro_rules!carrying_carryless_mul_impl {
301 (u128, u256) => {
302carrying_carryless_mul_impl! { @internal u128 =>
303pub const fn carrying_carryless_mul(self, rhs: Self, carry: Self) -> (Self, Self) {
304let x0 = self as u64;
305let x1 = (self >> 64) as u64;
306let y0 = rhs as u64;
307let y1 = (rhs >> 64) as u64;
308309let z0 = u64::widening_carryless_mul(x0, y0);
310let z2 = u64::widening_carryless_mul(x1, y1);
311312// The grade school algorithm would compute:
313 // z1 = x0y1 ^ x1y0
314315 // Instead, Karatsuba first computes:
316let z3 = u64::widening_carryless_mul(x0 ^ x1, y0 ^ y1);
317// Since it distributes over XOR,
318 // z3 == x0y0 ^ x0y1 ^ x1y0 ^ x1y1
319 // |--| |---------| |--|
320 // == z0 ^ z1 ^ z2
321 // so we can compute z1 as
322let z1 = z3 ^ z0 ^ z2;
323324let lo = z0 ^ (z1 << 64);
325let hi = z2 ^ (z1 >> 64);
326327 (lo ^ carry, hi)
328 }
329 }
330 };
331 ($SelfT:ty, $WideT:ty) => {
332carrying_carryless_mul_impl! { @internal $SelfT =>
333pub const fn carrying_carryless_mul(self, rhs: Self, carry: Self) -> (Self, Self) {
334// Can't use widening_carryless_mul because it's not implemented for usize.
335let p = (self as $WideT).carryless_mul(rhs as $WideT);
336337let lo = (p as $SelfT);
338let hi = (p >> Self::BITS) as $SelfT;
339340 (lo ^ carry, hi)
341 }
342 }
343 };
344 (@internal $SelfT:ty => $($fn:tt)*) => {
345/// Calculates the "full carryless multiplication" without the possibility to overflow.
346 ///
347 /// This returns the low-order (wrapping) bits and the high-order (overflow) bits
348 /// of the result as two separate values, in that order.
349 ///
350 /// # Examples
351 ///
352 /// Please note that this example is shared among integer types, which is why `u8` is used.
353 ///
354 /// ```
355 /// #![feature(uint_carryless_mul)]
356 ///
357 /// assert_eq!(0b1000_0000u8.carrying_carryless_mul(0b1000_0000, 0b0000), (0, 0b0100_0000));
358 /// assert_eq!(0b1000_0000u8.carrying_carryless_mul(0b1000_0000, 0b1111), (0b1111, 0b0100_0000));
359#[doc = concat!("assert_eq!(",
360stringify!($SelfT), "::MAX.carrying_carryless_mul(", stringify!($SelfT), "::MAX, ", stringify!($SelfT), "::MAX), ",
361"(!(", stringify!($SelfT), "::MAX / 3), ", stringify!($SelfT), "::MAX / 3));"
362)]
363/// ```
364#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
365 #[doc(alias = "clmul")]
366 #[unstable(feature = "uint_carryless_mul", issue = "152080")]
367 #[must_use = "this returns the result of the operation, \
368 without modifying the original"]
369 #[inline]
370$($fn)*
371 }
372}
373374impl i8 {
375/// 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 =
"CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"CURRENT_RUSTC_VERSION")]
#[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 =
"CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"CURRENT_RUSTC_VERSION")]
#[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`.
///
/// # 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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since =
"CURRENT_RUSTC_VERSION")]
#[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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since =
"CURRENT_RUSTC_VERSION")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn lowest_one(self) -> Option<u32> { (self as u8).lowest_one() }
/// Returns the bit pattern of `self` reinterpreted as an unsigned integer of the same size.
///
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
/// the same.
///
/// # Examples
///
/// ```
#[doc = "let n = -1i8;"]
///
#[doc = "assert_eq!(n.cast_unsigned(), u8::MAX);"]
/// ```
#[stable(feature = "integer_sign_cast", since = "1.87.0")]
#[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_unsigned(self) -> u8 { self as u8 }
/// Saturating conversion of `self` to an unsigned integer of the same size.
///
/// Negative values are clamped to `0`.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`checked_cast_unsigned`](Self::checked_cast_unsigned),
/// or [`strict_cast_unsigned`](Self::strict_cast_unsigned).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = i8::MIN;"]
///
#[doc = "assert_eq!(n.saturating_cast_unsigned(), 0u8);"]
#[doc = "assert_eq!(64i8.saturating_cast_unsigned(), 64u8);"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_cast_unsigned(self) -> u8 {
if self >= 0 { self.cast_unsigned() } else { 0 }
}
/// Checked conversion of `self` to an unsigned integer of the same size,
/// returning `None` if `self` is negative.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`saturating_cast_unsigned`](Self::saturating_cast_unsigned),
/// or [`strict_cast_unsigned`](Self::strict_cast_unsigned).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = i8::MIN;"]
///
#[doc = "assert_eq!(n.checked_cast_unsigned(), None);"]
#[doc = "assert_eq!(64i8.checked_cast_unsigned(), Some(64u8));"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn checked_cast_unsigned(self) -> Option<u8> {
if self >= 0 { Some(self.cast_unsigned()) } else { None }
}
/// Strict conversion of `self` to an unsigned integer of the same size,
/// which panics if `self` is negative.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`checked_cast_unsigned`](Self::checked_cast_unsigned),
/// or [`saturating_cast_unsigned`](Self::saturating_cast_unsigned).
///
/// # Examples
///
/// ```should_panic
/// #![feature(integer_cast_extras)]
#[doc = "let _ = i8::MIN.strict_cast_unsigned();"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_cast_unsigned(self) -> u8 {
match self.checked_cast_unsigned() {
Some(n) => n,
None => imp::overflow_panic::cast_integer(),
}
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `<<` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = -0x7ei8;"]
#[doc = "let m = 0xa;"]
///
#[doc = "assert_eq!(n.rotate_left(2), m);"]
#[doc = "assert_eq!(n.rotate_left(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn rotate_left(self, n: u32) -> Self {
(self as u8).rotate_left(n) as Self
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `>>` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0xai8;"]
#[doc = "let m = -0x7e;"]
///
#[doc = "assert_eq!(n.rotate_right(2), m);"]
#[doc = "assert_eq!(n.rotate_right(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn rotate_right(self, n: u32) -> Self {
(self as u8).rotate_right(n) as Self
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x12i8;"]
///
/// let m = n.swap_bytes();
///
#[doc = "assert_eq!(m, 0x12);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn swap_bytes(self) -> Self { (self as u8).swap_bytes() as Self }
/// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
/// second least-significant bit becomes second most-significant bit, etc.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x12i8;"]
/// let m = n.reverse_bits();
///
#[doc = "assert_eq!(m, 0x48);"]
#[doc = "assert_eq!(0, 0i8.reverse_bits());"]
/// ```
#[stable(feature = "reverse_bits", since = "1.37.0")]
#[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn reverse_bits(self) -> Self {
(self as u8).reverse_bits() as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are swapped.
///
/// See also [from_be_bytes()](Self::from_be_bytes).
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai8;"]
///
/// if cfg!(target_endian = "big") {
#[doc = " assert_eq!(i8::from_be(n), n)"]
/// } else {
#[doc = " assert_eq!(i8::from_be(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn from_be(x: Self) -> Self { x.swap_bytes() }
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are swapped.
///
/// See also [from_le_bytes()](Self::from_le_bytes).
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai8;"]
///
/// if cfg!(target_endian = "little") {
#[doc = " assert_eq!(i8::from_le(n), n)"]
/// } else {
#[doc = " assert_eq!(i8::from_le(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn from_le(x: Self) -> Self { x }
/// Swaps bytes of `self` on little endian targets.
///
/// On big endian this is a no-op.
///
/// The returned value has the same type as `self`, and will be interpreted
/// as (a potentially different) value of a native-endian
#[doc = "`i8`."]
///
/// See [`to_be_bytes()`](Self::to_be_bytes) for a type-safe alternative.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai8;"]
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be(self) -> Self { self.swap_bytes() }
/// Swaps bytes of `self` on big endian targets.
///
/// On little endian this is a no-op.
///
/// The returned value has the same type as `self`, and will be interpreted
/// as (a potentially different) value of a native-endian
#[doc = "`i8`."]
///
/// See [`to_le_bytes()`](Self::to_le_bytes) for a type-safe alternative.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai8;"]
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le(self) -> Self { self }
/// Checked integer addition. Computes `self + rhs`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i8::MAX - 2).checked_add(1), Some(i8::MAX - 1));"]
#[doc = "assert_eq!((i8::MAX - 2).checked_add(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_add(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer addition. Computes `self + rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i8::MAX - 2).strict_add(1), i8::MAX - 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i8::MAX - 2).strict_add(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_add(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Unchecked integer addition. Computes `self + rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_add(y)` is semantically equivalent to calling
/// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_add`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self + rhs > i8::MAX` or `self + rhs < i8::MIN`,"]
/// i.e. when [`checked_add`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_add`]: i8::checked_add"]
#[doc = "[`wrapping_add`]: i8::wrapping_add"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i8, rhs: i8) {
if !!lhs.overflowing_add(rhs).1 {
let msg =
"unsafe precondition(s) violated: i8::unchecked_add cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_add(self, rhs) }
}
/// Checked addition with an unsigned integer. Computes `self + rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i8.checked_add_unsigned(2), Some(3));"]
#[doc = "assert_eq!((i8::MAX - 2).checked_add_unsigned(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add_unsigned(self, rhs: u8) -> Option<Self> {
let (a, b) = self.overflowing_add_unsigned(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict addition with an unsigned integer. Computes `self + rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i8.strict_add_unsigned(2), 3);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i8::MAX - 2).strict_add_unsigned(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add_unsigned(self, rhs: u8) -> Self {
let (a, b) = self.overflowing_add_unsigned(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Checked integer subtraction. Computes `self - rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i8::MIN + 2).checked_sub(1), Some(i8::MIN + 1));"]
#[doc = "assert_eq!((i8::MIN + 2).checked_sub(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_sub(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer subtraction. Computes `self - rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i8::MIN + 2).strict_sub(1), i8::MIN + 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i8::MIN + 2).strict_sub(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_sub(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
/// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_sub`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self - rhs > i8::MAX` or `self - rhs < i8::MIN`,"]
/// i.e. when [`checked_sub`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_sub`]: i8::checked_sub"]
#[doc = "[`wrapping_sub`]: i8::wrapping_sub"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i8, rhs: i8) {
if !!lhs.overflowing_sub(rhs).1 {
let msg =
"unsafe precondition(s) violated: i8::unchecked_sub cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_sub(self, rhs) }
}
/// Checked subtraction with an unsigned integer. Computes `self - rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i8.checked_sub_unsigned(2), Some(-1));"]
#[doc = "assert_eq!((i8::MIN + 2).checked_sub_unsigned(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub_unsigned(self, rhs: u8) -> Option<Self> {
let (a, b) = self.overflowing_sub_unsigned(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict subtraction with an unsigned integer. Computes `self - rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i8.strict_sub_unsigned(2), -1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i8::MIN + 2).strict_sub_unsigned(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub_unsigned(self, rhs: u8) -> Self {
let (a, b) = self.overflowing_sub_unsigned(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Checked integer multiplication. Computes `self * rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i8::MAX.checked_mul(1), Some(i8::MAX));"]
#[doc = "assert_eq!(i8::MAX.checked_mul(2), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer multiplication. Computes `self * rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i8::MAX.strict_mul(1), i8::MAX);"]
/// ```
///
/// The following panics because of overflow:
///
/// ``` should_panic
#[doc = "let _ = i8::MAX.strict_mul(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_mul(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_mul(rhs);
if b { imp::overflow_panic::mul() } else { a }
}
/// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
/// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_mul`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self * rhs > i8::MAX` or `self * rhs < i8::MIN`,"]
/// i.e. when [`checked_mul`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_mul`]: i8::checked_mul"]
#[doc = "[`wrapping_mul`]: i8::wrapping_mul"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i8, rhs: i8) {
if !!lhs.overflowing_mul(rhs).1 {
let msg =
"unsafe precondition(s) violated: i8::unchecked_mul cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_mul(self, rhs) }
}
/// Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
/// or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i8::MIN + 1).checked_div(-1), Some(127));"]
#[doc = "assert_eq!(i8::MIN.checked_div(-1), None);"]
#[doc = "assert_eq!((1i8).checked_div(0), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1)))
{
None
} else { Some(unsafe { intrinsics::unchecked_div(self, rhs) }) }
}
/// Strict integer division. Computes `self / rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is when one divides `MIN / -1` on a signed type (where
/// `MIN` 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.
///
/// # 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 {
let (a, b) = self.overflowing_div(rhs);
if b { imp::overflow_panic::div() } else { a }
}
/// 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` 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.
///
/// # 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 {
let (a, b) = self.overflowing_div_euclid(rhs);
if b { imp::overflow_panic::div() } else { a }
}
/// 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` 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` 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> {
if exp == 0 { return Some(1); }
let mut base = self;
let mut acc: Self = 1;
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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc: Self = 1;
loop {
if (exp & 1) == 1 {
acc = acc.strict_mul(base);
if exp == 1 { return acc; }
}
exp /= 2;
base = base.strict_mul(base);
}
}
/// 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` 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` 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` 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` 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` 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` 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` on a signed type (where `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` 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. The behaviour 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. The behaviour 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` 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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc: Self = 1;
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 { acc = acc.wrapping_mul(base); }
exp /= 2;
base = base.wrapping_mul(base);
}
acc.wrapping_mul(base)
} else {
loop {
if (exp & 1) == 1 {
acc = acc.wrapping_mul(base);
if exp == 1 { return acc; }
}
exp /= 2;
base = base.wrapping_mul(base);
}
}
}
/// 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) {
if exp == 0 { return (1, false); }
let mut base = self;
let mut acc: Self = 1;
let mut overflown = false;
let mut r;
loop {
if (exp & 1) == 1 {
r = acc.overflowing_mul(base);
if exp == 1 { r.1 |= overflown; return r; }
acc = r.0;
overflown |= r.1;
}
exp /= 2;
r = base.overflowing_mul(base);
base = r.0;
overflown |= r.1;
}
}
/// 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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc = 1;
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 { acc = acc * base; }
exp /= 2;
base = base * base;
}
acc * base
} else {
loop {
if (exp & 1) == 1 {
acc = acc * base;
if exp == 1 { return acc; }
}
exp /= 2;
base = base * base;
}
}
}
/// 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` can produce results more efficiently for base 2, and `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.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2i8.checked_ilog2(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog2(self) -> Option<u32> {
if self <= 0 {
None
} else {
let log =
(Self::BITS - 1) -
unsafe { intrinsics::ctlz_nonzero(self) as u32 };
Some(log)
}
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// Returns `None` if the number is negative or zero.
///
/// # Example
///
/// ```
#[doc = "assert_eq!(10i8.checked_ilog10(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog10(self) -> Option<u32> {
imp::int_log10::i8(self as i8)
}
/// Computes the absolute value of `self`.
///
/// # Overflow behavior
///
/// The absolute value of
#[doc = "`i8::MIN`"]
/// cannot be represented as an
#[doc = "`i8`,"]
/// and attempting to calculate it will cause an overflow. This means
/// that code in debug mode will trigger a panic on this case and
/// optimized code will return
#[doc = "`i8::MIN`"]
/// without a panic. If you do not want this behavior, consider
/// using [`unsigned_abs`](Self::unsigned_abs) instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i8.abs(), 10);"]
#[doc = "assert_eq!((-10i8).abs(), 10);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[allow(unused_attributes)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn abs(self) -> Self {
if self.is_negative() { -self } else { self }
}
/// Computes the absolute difference between `self` and `other`.
///
/// This function always returns the correct answer without overflow or
/// panics by returning an unsigned integer.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i8.abs_diff(80), 20u8);"]
#[doc = "assert_eq!(100i8.abs_diff(110), 10u8);"]
#[doc = "assert_eq!((-100i8).abs_diff(80), 180u8);"]
#[doc = "assert_eq!((-100i8).abs_diff(-120), 20u8);"]
#[doc = "assert_eq!(i8::MIN.abs_diff(i8::MAX), u8::MAX);"]
/// ```
#[stable(feature = "int_abs_diff", since = "1.60.0")]
#[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn abs_diff(self, other: Self) -> u8 {
if self < other {
(other as u8).wrapping_sub(self as u8)
} else { (self as u8).wrapping_sub(other as u8) }
}
/// Returns a number representing sign of `self`.
///
/// - `0` if the number is zero
/// - `1` if the number is positive
/// - `-1` if the number is negative
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i8.signum(), 1);"]
#[doc = "assert_eq!(0i8.signum(), 0);"]
#[doc = "assert_eq!((-10i8).signum(), -1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_sign", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn signum(self) -> Self {
crate::intrinsics::three_way_compare(self, 0) as Self
}
/// Returns `true` if `self` is positive and `false` if the number is zero or
/// negative.
///
/// # Examples
///
/// ```
#[doc = "assert!(10i8.is_positive());"]
#[doc = "assert!(!(-10i8).is_positive());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[inline(always)]
pub const fn is_positive(self) -> bool { self > 0 }
/// Returns `true` if `self` is negative and `false` if the number is zero or
/// positive.
///
/// # Examples
///
/// ```
#[doc = "assert!((-10i8).is_negative());"]
#[doc = "assert!(!10i8.is_negative());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[inline(always)]
pub const fn is_negative(self) -> bool { self < 0 }
/// Returns the memory representation of this integer as a byte array in
/// big-endian (network) byte order.
///
#[doc =
"
**Note**: This function is meaningless on `i8`. Byte order does not exist as a
concept for byte-sized integers. This function is only provided in symmetry
with larger integer types. You can cast from and to `u8` using
[`cast_signed`](u8::cast_signed) and [`cast_unsigned`](Self::cast_unsigned).
"]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12i8.to_be_bytes();"]
#[doc = "assert_eq!(bytes, [0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
self.to_be().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// little-endian byte order.
///
#[doc =
"
**Note**: This function is meaningless on `i8`. Byte order does not exist as a
concept for byte-sized integers. This function is only provided in symmetry
with larger integer types. You can cast from and to `u8` using
[`cast_signed`](u8::cast_signed) and [`cast_unsigned`](Self::cast_unsigned).
"]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12i8.to_le_bytes();"]
#[doc = "assert_eq!(bytes, [0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
self.to_le().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code
/// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
/// instead.
///
#[doc =
"
**Note**: This function is meaningless on `i8`. Byte order does not exist as a
concept for byte-sized integers. This function is only provided in symmetry
with larger integer types. You can cast from and to `u8` using
[`cast_signed`](u8::cast_signed) and [`cast_unsigned`](Self::cast_unsigned).
"]
///
/// [`to_be_bytes`]: Self::to_be_bytes
/// [`to_le_bytes`]: Self::to_le_bytes
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12i8.to_ne_bytes();"]
/// assert_eq!(
/// bytes,
/// if cfg!(target_endian = "big") {
#[doc = " [0x12]"]
/// } else {
#[doc = " [0x12]"]
/// }
/// );
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
unsafe { mem::transmute(self) }
}
/// Creates an integer value from its representation as a byte array in
/// big endian.
///
#[doc =
"
**Note**: This function is meaningless on `i8`. Byte order does not exist as a
concept for byte-sized integers. This function is only provided in symmetry
with larger integer types. You can cast from and to `u8` using
[`cast_signed`](u8::cast_signed) and [`cast_unsigned`](Self::cast_unsigned).
"]
///
/// # Examples
///
/// ```
#[doc = "let value = i8::from_be_bytes([0x12]);"]
#[doc = "assert_eq!(value, 0x12);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_be_i8(input: &mut &[u8]) -> i8 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i8>());"]
/// *input = rest;
#[doc = " i8::from_be_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_be(Self::from_ne_bytes(bytes))
}
/// Creates an integer value from its representation as a byte array in
/// little endian.
///
#[doc =
"
**Note**: This function is meaningless on `i8`. Byte order does not exist as a
concept for byte-sized integers. This function is only provided in symmetry
with larger integer types. You can cast from and to `u8` using
[`cast_signed`](u8::cast_signed) and [`cast_unsigned`](Self::cast_unsigned).
"]
///
/// # Examples
///
/// ```
#[doc = "let value = i8::from_le_bytes([0x12]);"]
#[doc = "assert_eq!(value, 0x12);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_le_i8(input: &mut &[u8]) -> i8 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i8>());"]
/// *input = rest;
#[doc = " i8::from_le_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_le(Self::from_ne_bytes(bytes))
}
/// Creates an integer value from its memory representation as a byte
/// array in native endianness.
///
/// As the target platform's native endianness is used, portable code
/// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
/// appropriate instead.
///
/// [`from_be_bytes`]: Self::from_be_bytes
/// [`from_le_bytes`]: Self::from_le_bytes
///
#[doc =
"
**Note**: This function is meaningless on `i8`. Byte order does not exist as a
concept for byte-sized integers. This function is only provided in symmetry
with larger integer types. You can cast from and to `u8` using
[`cast_signed`](u8::cast_signed) and [`cast_unsigned`](Self::cast_unsigned).
"]
///
/// # Examples
///
/// ```
#[doc = "let value = i8::from_ne_bytes(if cfg!(target_endian = \"big\") {"]
#[doc = " [0x12]"]
/// } else {
#[doc = " [0x12]"]
/// });
#[doc = "assert_eq!(value, 0x12);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_ne_i8(input: &mut &[u8]) -> i8 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i8>());"]
/// *input = rest;
#[doc = " i8::from_ne_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use]
#[inline]
pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
unsafe { mem::transmute(bytes) }
}
/// New code should prefer to use
#[doc = "[`i8::MIN`] instead."]
///
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MIN` associated constant on this type")]
#[rustc_diagnostic_item = "i8_legacy_fn_min_value"]
pub const fn min_value() -> Self { Self::MIN }
/// New code should prefer to use
#[doc = "[`i8::MAX`] instead."]
///
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MAX` associated constant on this type")]
#[rustc_diagnostic_item = "i8_legacy_fn_max_value"]
pub const fn max_value() -> Self { Self::MAX }
/// Clamps this number to a symmetric range centred around zero.
///
/// The method clamps the number's magnitude (absolute value) to be at most `limit`.
///
/// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
/// explicit about the intent.
///
/// # Examples
///
/// ```
/// #![feature(clamp_magnitude)]
#[doc = "assert_eq!(120i8.clamp_magnitude(100), 100);"]
#[doc = "assert_eq!(-120i8.clamp_magnitude(100), -100);"]
#[doc = "assert_eq!(80i8.clamp_magnitude(100), 80);"]
#[doc = "assert_eq!(-80i8.clamp_magnitude(100), -80);"]
/// ```
#[must_use =
"this returns the clamped value and does not modify the original"]
#[unstable(feature = "clamp_magnitude", issue = "148519")]
#[inline]
pub fn clamp_magnitude(self, limit: u8) -> Self {
if let Ok(limit) = core::convert::TryInto::<i8>::try_into(limit) {
self.clamp(-limit, limit)
} else { self }
}
/// Truncate an integer to an integer of the same size or smaller, preserving the least
/// significant bits.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i8, 120i8.truncate());"]
#[doc = "assert_eq!(-120i8, (-120i8).truncate());"]
/// assert_eq!(120i8, 376i32.truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
/// instead of truncating.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i8, 120i8.saturating_truncate());"]
#[doc = "assert_eq!(-120i8, (-120i8).saturating_truncate());"]
/// assert_eq!(127i8, 376i32.saturating_truncate());
/// assert_eq!(-128i8, (-1000i32).saturating_truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn saturating_truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_saturating_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
/// is outside the bounds of the smaller type.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(Some(120i8), 120i8.checked_truncate());"]
#[doc = "assert_eq!(Some(-120i8), (-120i8).checked_truncate());"]
/// assert_eq!(None, 376i32.checked_truncate::<i8>());
/// assert_eq!(None, (-1000i32).checked_truncate::<i8>());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn checked_truncate<Target>(self) -> Option<Target> where
Self: [const] traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_checked_truncate(self)
}
/// Widen to an integer of the same size or larger, preserving its value.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i128, 120i8.widen());"]
#[doc = "assert_eq!(-120i128, (-120i8).widen());"]
/// ```
#[must_use =
"this returns the widened value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn widen<Target>(self) -> Target where Self: [const]
traits::WidenTarget<Target> {
traits::WidenTarget::internal_widen(self)
}int_impl! {
376Self = i8,
377 ActualT = i8,
378 UnsignedT = u8,
379 BITS = 8,
380 BITS_MINUS_ONE = 7,
381 Min = -128,
382 Max = 127,
383 rot = 2,
384 rot_op = "-0x7e",
385 rot_result = "0xa",
386 swap_op = "0x12",
387 swapped = "0x12",
388 reversed = "0x48",
389 le_bytes = "[0x12]",
390 be_bytes = "[0x12]",
391 to_xe_bytes_doc = i8_xe_bytes_doc!(),
392 from_xe_bytes_doc = i8_xe_bytes_doc!(),
393 bound_condition = "",
394 }395/// 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 }396/// 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 }397}
398399impl i16 {
400/// 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 =
"CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"CURRENT_RUSTC_VERSION")]
#[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 =
"CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"CURRENT_RUSTC_VERSION")]
#[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`.
///
/// # 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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since =
"CURRENT_RUSTC_VERSION")]
#[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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since =
"CURRENT_RUSTC_VERSION")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn lowest_one(self) -> Option<u32> { (self as u16).lowest_one() }
/// Returns the bit pattern of `self` reinterpreted as an unsigned integer of the same size.
///
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
/// the same.
///
/// # Examples
///
/// ```
#[doc = "let n = -1i16;"]
///
#[doc = "assert_eq!(n.cast_unsigned(), u16::MAX);"]
/// ```
#[stable(feature = "integer_sign_cast", since = "1.87.0")]
#[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_unsigned(self) -> u16 { self as u16 }
/// Saturating conversion of `self` to an unsigned integer of the same size.
///
/// Negative values are clamped to `0`.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`checked_cast_unsigned`](Self::checked_cast_unsigned),
/// or [`strict_cast_unsigned`](Self::strict_cast_unsigned).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = i16::MIN;"]
///
#[doc = "assert_eq!(n.saturating_cast_unsigned(), 0u16);"]
#[doc = "assert_eq!(64i16.saturating_cast_unsigned(), 64u16);"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_cast_unsigned(self) -> u16 {
if self >= 0 { self.cast_unsigned() } else { 0 }
}
/// Checked conversion of `self` to an unsigned integer of the same size,
/// returning `None` if `self` is negative.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`saturating_cast_unsigned`](Self::saturating_cast_unsigned),
/// or [`strict_cast_unsigned`](Self::strict_cast_unsigned).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = i16::MIN;"]
///
#[doc = "assert_eq!(n.checked_cast_unsigned(), None);"]
#[doc = "assert_eq!(64i16.checked_cast_unsigned(), Some(64u16));"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn checked_cast_unsigned(self) -> Option<u16> {
if self >= 0 { Some(self.cast_unsigned()) } else { None }
}
/// Strict conversion of `self` to an unsigned integer of the same size,
/// which panics if `self` is negative.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`checked_cast_unsigned`](Self::checked_cast_unsigned),
/// or [`saturating_cast_unsigned`](Self::saturating_cast_unsigned).
///
/// # Examples
///
/// ```should_panic
/// #![feature(integer_cast_extras)]
#[doc = "let _ = i16::MIN.strict_cast_unsigned();"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_cast_unsigned(self) -> u16 {
match self.checked_cast_unsigned() {
Some(n) => n,
None => imp::overflow_panic::cast_integer(),
}
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `<<` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = -0x5ffdi16;"]
#[doc = "let m = 0x3a;"]
///
#[doc = "assert_eq!(n.rotate_left(4), m);"]
#[doc = "assert_eq!(n.rotate_left(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn rotate_left(self, n: u32) -> Self {
(self as u16).rotate_left(n) as Self
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `>>` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x3ai16;"]
#[doc = "let m = -0x5ffd;"]
///
#[doc = "assert_eq!(n.rotate_right(4), m);"]
#[doc = "assert_eq!(n.rotate_right(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn rotate_right(self, n: u32) -> Self {
(self as u16).rotate_right(n) as Self
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1234i16;"]
///
/// let m = n.swap_bytes();
///
#[doc = "assert_eq!(m, 0x3412);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn swap_bytes(self) -> Self { (self as u16).swap_bytes() as Self }
/// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
/// second least-significant bit becomes second most-significant bit, etc.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1234i16;"]
/// let m = n.reverse_bits();
///
#[doc = "assert_eq!(m, 0x2c48);"]
#[doc = "assert_eq!(0, 0i16.reverse_bits());"]
/// ```
#[stable(feature = "reverse_bits", since = "1.37.0")]
#[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn reverse_bits(self) -> Self {
(self as u16).reverse_bits() as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are swapped.
///
/// See also [from_be_bytes()](Self::from_be_bytes).
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai16;"]
///
/// if cfg!(target_endian = "big") {
#[doc = " assert_eq!(i16::from_be(n), n)"]
/// } else {
#[doc = " assert_eq!(i16::from_be(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn from_be(x: Self) -> Self { x.swap_bytes() }
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are swapped.
///
/// See also [from_le_bytes()](Self::from_le_bytes).
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai16;"]
///
/// if cfg!(target_endian = "little") {
#[doc = " assert_eq!(i16::from_le(n), n)"]
/// } else {
#[doc = " assert_eq!(i16::from_le(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn from_le(x: Self) -> Self { x }
/// Swaps bytes of `self` on little endian targets.
///
/// On big endian this is a no-op.
///
/// The returned value has the same type as `self`, and will be interpreted
/// as (a potentially different) value of a native-endian
#[doc = "`i16`."]
///
/// See [`to_be_bytes()`](Self::to_be_bytes) for a type-safe alternative.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai16;"]
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be(self) -> Self { self.swap_bytes() }
/// Swaps bytes of `self` on big endian targets.
///
/// On little endian this is a no-op.
///
/// The returned value has the same type as `self`, and will be interpreted
/// as (a potentially different) value of a native-endian
#[doc = "`i16`."]
///
/// See [`to_le_bytes()`](Self::to_le_bytes) for a type-safe alternative.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai16;"]
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le(self) -> Self { self }
/// Checked integer addition. Computes `self + rhs`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i16::MAX - 2).checked_add(1), Some(i16::MAX - 1));"]
#[doc = "assert_eq!((i16::MAX - 2).checked_add(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_add(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer addition. Computes `self + rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i16::MAX - 2).strict_add(1), i16::MAX - 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i16::MAX - 2).strict_add(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_add(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Unchecked integer addition. Computes `self + rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_add(y)` is semantically equivalent to calling
/// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_add`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self + rhs > i16::MAX` or `self + rhs < i16::MIN`,"]
/// i.e. when [`checked_add`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_add`]: i16::checked_add"]
#[doc = "[`wrapping_add`]: i16::wrapping_add"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i16, rhs: i16) {
if !!lhs.overflowing_add(rhs).1 {
let msg =
"unsafe precondition(s) violated: i16::unchecked_add cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_add(self, rhs) }
}
/// Checked addition with an unsigned integer. Computes `self + rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i16.checked_add_unsigned(2), Some(3));"]
#[doc = "assert_eq!((i16::MAX - 2).checked_add_unsigned(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add_unsigned(self, rhs: u16) -> Option<Self> {
let (a, b) = self.overflowing_add_unsigned(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict addition with an unsigned integer. Computes `self + rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i16.strict_add_unsigned(2), 3);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i16::MAX - 2).strict_add_unsigned(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add_unsigned(self, rhs: u16) -> Self {
let (a, b) = self.overflowing_add_unsigned(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Checked integer subtraction. Computes `self - rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i16::MIN + 2).checked_sub(1), Some(i16::MIN + 1));"]
#[doc = "assert_eq!((i16::MIN + 2).checked_sub(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_sub(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer subtraction. Computes `self - rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i16::MIN + 2).strict_sub(1), i16::MIN + 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i16::MIN + 2).strict_sub(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_sub(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
/// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_sub`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self - rhs > i16::MAX` or `self - rhs < i16::MIN`,"]
/// i.e. when [`checked_sub`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_sub`]: i16::checked_sub"]
#[doc = "[`wrapping_sub`]: i16::wrapping_sub"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i16, rhs: i16) {
if !!lhs.overflowing_sub(rhs).1 {
let msg =
"unsafe precondition(s) violated: i16::unchecked_sub cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_sub(self, rhs) }
}
/// Checked subtraction with an unsigned integer. Computes `self - rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i16.checked_sub_unsigned(2), Some(-1));"]
#[doc = "assert_eq!((i16::MIN + 2).checked_sub_unsigned(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub_unsigned(self, rhs: u16) -> Option<Self> {
let (a, b) = self.overflowing_sub_unsigned(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict subtraction with an unsigned integer. Computes `self - rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i16.strict_sub_unsigned(2), -1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i16::MIN + 2).strict_sub_unsigned(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub_unsigned(self, rhs: u16) -> Self {
let (a, b) = self.overflowing_sub_unsigned(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Checked integer multiplication. Computes `self * rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i16::MAX.checked_mul(1), Some(i16::MAX));"]
#[doc = "assert_eq!(i16::MAX.checked_mul(2), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer multiplication. Computes `self * rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i16::MAX.strict_mul(1), i16::MAX);"]
/// ```
///
/// The following panics because of overflow:
///
/// ``` should_panic
#[doc = "let _ = i16::MAX.strict_mul(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_mul(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_mul(rhs);
if b { imp::overflow_panic::mul() } else { a }
}
/// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
/// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_mul`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self * rhs > i16::MAX` or `self * rhs < i16::MIN`,"]
/// i.e. when [`checked_mul`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_mul`]: i16::checked_mul"]
#[doc = "[`wrapping_mul`]: i16::wrapping_mul"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i16, rhs: i16) {
if !!lhs.overflowing_mul(rhs).1 {
let msg =
"unsafe precondition(s) violated: i16::unchecked_mul cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_mul(self, rhs) }
}
/// Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
/// or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i16::MIN + 1).checked_div(-1), Some(32767));"]
#[doc = "assert_eq!(i16::MIN.checked_div(-1), None);"]
#[doc = "assert_eq!((1i16).checked_div(0), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1)))
{
None
} else { Some(unsafe { intrinsics::unchecked_div(self, rhs) }) }
}
/// Strict integer division. Computes `self / rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is when one divides `MIN / -1` on a signed type (where
/// `MIN` 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.
///
/// # 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 {
let (a, b) = self.overflowing_div(rhs);
if b { imp::overflow_panic::div() } else { a }
}
/// 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` 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.
///
/// # 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 {
let (a, b) = self.overflowing_div_euclid(rhs);
if b { imp::overflow_panic::div() } else { a }
}
/// 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` 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` 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> {
if exp == 0 { return Some(1); }
let mut base = self;
let mut acc: Self = 1;
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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc: Self = 1;
loop {
if (exp & 1) == 1 {
acc = acc.strict_mul(base);
if exp == 1 { return acc; }
}
exp /= 2;
base = base.strict_mul(base);
}
}
/// 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` 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` 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` 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` 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` 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` 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` on a signed type (where `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` 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. The behaviour 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. The behaviour 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` 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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc: Self = 1;
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 { acc = acc.wrapping_mul(base); }
exp /= 2;
base = base.wrapping_mul(base);
}
acc.wrapping_mul(base)
} else {
loop {
if (exp & 1) == 1 {
acc = acc.wrapping_mul(base);
if exp == 1 { return acc; }
}
exp /= 2;
base = base.wrapping_mul(base);
}
}
}
/// 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) {
if exp == 0 { return (1, false); }
let mut base = self;
let mut acc: Self = 1;
let mut overflown = false;
let mut r;
loop {
if (exp & 1) == 1 {
r = acc.overflowing_mul(base);
if exp == 1 { r.1 |= overflown; return r; }
acc = r.0;
overflown |= r.1;
}
exp /= 2;
r = base.overflowing_mul(base);
base = r.0;
overflown |= r.1;
}
}
/// 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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc = 1;
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 { acc = acc * base; }
exp /= 2;
base = base * base;
}
acc * base
} else {
loop {
if (exp & 1) == 1 {
acc = acc * base;
if exp == 1 { return acc; }
}
exp /= 2;
base = base * base;
}
}
}
/// 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` can produce results more efficiently for base 2, and `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.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2i16.checked_ilog2(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog2(self) -> Option<u32> {
if self <= 0 {
None
} else {
let log =
(Self::BITS - 1) -
unsafe { intrinsics::ctlz_nonzero(self) as u32 };
Some(log)
}
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// Returns `None` if the number is negative or zero.
///
/// # Example
///
/// ```
#[doc = "assert_eq!(10i16.checked_ilog10(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog10(self) -> Option<u32> {
imp::int_log10::i16(self as i16)
}
/// Computes the absolute value of `self`.
///
/// # Overflow behavior
///
/// The absolute value of
#[doc = "`i16::MIN`"]
/// cannot be represented as an
#[doc = "`i16`,"]
/// and attempting to calculate it will cause an overflow. This means
/// that code in debug mode will trigger a panic on this case and
/// optimized code will return
#[doc = "`i16::MIN`"]
/// without a panic. If you do not want this behavior, consider
/// using [`unsigned_abs`](Self::unsigned_abs) instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i16.abs(), 10);"]
#[doc = "assert_eq!((-10i16).abs(), 10);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[allow(unused_attributes)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn abs(self) -> Self {
if self.is_negative() { -self } else { self }
}
/// Computes the absolute difference between `self` and `other`.
///
/// This function always returns the correct answer without overflow or
/// panics by returning an unsigned integer.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i16.abs_diff(80), 20u16);"]
#[doc = "assert_eq!(100i16.abs_diff(110), 10u16);"]
#[doc = "assert_eq!((-100i16).abs_diff(80), 180u16);"]
#[doc = "assert_eq!((-100i16).abs_diff(-120), 20u16);"]
#[doc = "assert_eq!(i16::MIN.abs_diff(i16::MAX), u16::MAX);"]
/// ```
#[stable(feature = "int_abs_diff", since = "1.60.0")]
#[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn abs_diff(self, other: Self) -> u16 {
if self < other {
(other as u16).wrapping_sub(self as u16)
} else { (self as u16).wrapping_sub(other as u16) }
}
/// Returns a number representing sign of `self`.
///
/// - `0` if the number is zero
/// - `1` if the number is positive
/// - `-1` if the number is negative
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i16.signum(), 1);"]
#[doc = "assert_eq!(0i16.signum(), 0);"]
#[doc = "assert_eq!((-10i16).signum(), -1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_sign", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn signum(self) -> Self {
crate::intrinsics::three_way_compare(self, 0) as Self
}
/// Returns `true` if `self` is positive and `false` if the number is zero or
/// negative.
///
/// # Examples
///
/// ```
#[doc = "assert!(10i16.is_positive());"]
#[doc = "assert!(!(-10i16).is_positive());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[inline(always)]
pub const fn is_positive(self) -> bool { self > 0 }
/// Returns `true` if `self` is negative and `false` if the number is zero or
/// positive.
///
/// # Examples
///
/// ```
#[doc = "assert!((-10i16).is_negative());"]
#[doc = "assert!(!10i16.is_negative());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[inline(always)]
pub const fn is_negative(self) -> bool { self < 0 }
/// Returns the memory representation of this integer as a byte array in
/// big-endian (network) byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234i16.to_be_bytes();"]
#[doc = "assert_eq!(bytes, [0x12, 0x34]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
self.to_be().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// little-endian byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234i16.to_le_bytes();"]
#[doc = "assert_eq!(bytes, [0x34, 0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
self.to_le().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code
/// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
/// instead.
///
#[doc = ""]
///
/// [`to_be_bytes`]: Self::to_be_bytes
/// [`to_le_bytes`]: Self::to_le_bytes
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234i16.to_ne_bytes();"]
/// assert_eq!(
/// bytes,
/// if cfg!(target_endian = "big") {
#[doc = " [0x12, 0x34]"]
/// } else {
#[doc = " [0x34, 0x12]"]
/// }
/// );
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
unsafe { mem::transmute(self) }
}
/// Creates an integer value from its representation as a byte array in
/// big endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = i16::from_be_bytes([0x12, 0x34]);"]
#[doc = "assert_eq!(value, 0x1234);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_be_i16(input: &mut &[u8]) -> i16 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i16>());"]
/// *input = rest;
#[doc = " i16::from_be_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_be(Self::from_ne_bytes(bytes))
}
/// Creates an integer value from its representation as a byte array in
/// little endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = i16::from_le_bytes([0x34, 0x12]);"]
#[doc = "assert_eq!(value, 0x1234);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_le_i16(input: &mut &[u8]) -> i16 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i16>());"]
/// *input = rest;
#[doc = " i16::from_le_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_le(Self::from_ne_bytes(bytes))
}
/// Creates an integer value from its memory representation as a byte
/// array in native endianness.
///
/// As the target platform's native endianness is used, portable code
/// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
/// appropriate instead.
///
/// [`from_be_bytes`]: Self::from_be_bytes
/// [`from_le_bytes`]: Self::from_le_bytes
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = i16::from_ne_bytes(if cfg!(target_endian = \"big\") {"]
#[doc = " [0x12, 0x34]"]
/// } else {
#[doc = " [0x34, 0x12]"]
/// });
#[doc = "assert_eq!(value, 0x1234);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_ne_i16(input: &mut &[u8]) -> i16 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i16>());"]
/// *input = rest;
#[doc = " i16::from_ne_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use]
#[inline]
pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
unsafe { mem::transmute(bytes) }
}
/// New code should prefer to use
#[doc = "[`i16::MIN`] instead."]
///
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MIN` associated constant on this type")]
#[rustc_diagnostic_item = "i16_legacy_fn_min_value"]
pub const fn min_value() -> Self { Self::MIN }
/// New code should prefer to use
#[doc = "[`i16::MAX`] instead."]
///
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MAX` associated constant on this type")]
#[rustc_diagnostic_item = "i16_legacy_fn_max_value"]
pub const fn max_value() -> Self { Self::MAX }
/// Clamps this number to a symmetric range centred around zero.
///
/// The method clamps the number's magnitude (absolute value) to be at most `limit`.
///
/// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
/// explicit about the intent.
///
/// # Examples
///
/// ```
/// #![feature(clamp_magnitude)]
#[doc = "assert_eq!(120i16.clamp_magnitude(100), 100);"]
#[doc = "assert_eq!(-120i16.clamp_magnitude(100), -100);"]
#[doc = "assert_eq!(80i16.clamp_magnitude(100), 80);"]
#[doc = "assert_eq!(-80i16.clamp_magnitude(100), -80);"]
/// ```
#[must_use =
"this returns the clamped value and does not modify the original"]
#[unstable(feature = "clamp_magnitude", issue = "148519")]
#[inline]
pub fn clamp_magnitude(self, limit: u16) -> Self {
if let Ok(limit) = core::convert::TryInto::<i16>::try_into(limit) {
self.clamp(-limit, limit)
} else { self }
}
/// Truncate an integer to an integer of the same size or smaller, preserving the least
/// significant bits.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i8, 120i16.truncate());"]
#[doc = "assert_eq!(-120i8, (-120i16).truncate());"]
/// assert_eq!(120i8, 376i32.truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
/// instead of truncating.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i8, 120i16.saturating_truncate());"]
#[doc = "assert_eq!(-120i8, (-120i16).saturating_truncate());"]
/// assert_eq!(127i8, 376i32.saturating_truncate());
/// assert_eq!(-128i8, (-1000i32).saturating_truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn saturating_truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_saturating_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
/// is outside the bounds of the smaller type.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(Some(120i8), 120i16.checked_truncate());"]
#[doc = "assert_eq!(Some(-120i8), (-120i16).checked_truncate());"]
/// assert_eq!(None, 376i32.checked_truncate::<i8>());
/// assert_eq!(None, (-1000i32).checked_truncate::<i8>());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn checked_truncate<Target>(self) -> Option<Target> where
Self: [const] traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_checked_truncate(self)
}
/// Widen to an integer of the same size or larger, preserving its value.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i128, 120i8.widen());"]
#[doc = "assert_eq!(-120i128, (-120i8).widen());"]
/// ```
#[must_use =
"this returns the widened value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn widen<Target>(self) -> Target where Self: [const]
traits::WidenTarget<Target> {
traits::WidenTarget::internal_widen(self)
}int_impl! {
401Self = i16,
402 ActualT = i16,
403 UnsignedT = u16,
404 BITS = 16,
405 BITS_MINUS_ONE = 15,
406 Min = -32768,
407 Max = 32767,
408 rot = 4,
409 rot_op = "-0x5ffd",
410 rot_result = "0x3a",
411 swap_op = "0x1234",
412 swapped = "0x3412",
413 reversed = "0x2c48",
414 le_bytes = "[0x34, 0x12]",
415 be_bytes = "[0x12, 0x34]",
416 to_xe_bytes_doc = "",
417 from_xe_bytes_doc = "",
418 bound_condition = "",
419 }420/// 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 }421/// 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 }422}
423424impl i32 {
425/// 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 =
"CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"CURRENT_RUSTC_VERSION")]
#[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 =
"CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"CURRENT_RUSTC_VERSION")]
#[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`.
///
/// # 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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since =
"CURRENT_RUSTC_VERSION")]
#[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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since =
"CURRENT_RUSTC_VERSION")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn lowest_one(self) -> Option<u32> { (self as u32).lowest_one() }
/// Returns the bit pattern of `self` reinterpreted as an unsigned integer of the same size.
///
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
/// the same.
///
/// # Examples
///
/// ```
#[doc = "let n = -1i32;"]
///
#[doc = "assert_eq!(n.cast_unsigned(), u32::MAX);"]
/// ```
#[stable(feature = "integer_sign_cast", since = "1.87.0")]
#[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_unsigned(self) -> u32 { self as u32 }
/// Saturating conversion of `self` to an unsigned integer of the same size.
///
/// Negative values are clamped to `0`.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`checked_cast_unsigned`](Self::checked_cast_unsigned),
/// or [`strict_cast_unsigned`](Self::strict_cast_unsigned).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = i32::MIN;"]
///
#[doc = "assert_eq!(n.saturating_cast_unsigned(), 0u32);"]
#[doc = "assert_eq!(64i32.saturating_cast_unsigned(), 64u32);"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_cast_unsigned(self) -> u32 {
if self >= 0 { self.cast_unsigned() } else { 0 }
}
/// Checked conversion of `self` to an unsigned integer of the same size,
/// returning `None` if `self` is negative.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`saturating_cast_unsigned`](Self::saturating_cast_unsigned),
/// or [`strict_cast_unsigned`](Self::strict_cast_unsigned).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = i32::MIN;"]
///
#[doc = "assert_eq!(n.checked_cast_unsigned(), None);"]
#[doc = "assert_eq!(64i32.checked_cast_unsigned(), Some(64u32));"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn checked_cast_unsigned(self) -> Option<u32> {
if self >= 0 { Some(self.cast_unsigned()) } else { None }
}
/// Strict conversion of `self` to an unsigned integer of the same size,
/// which panics if `self` is negative.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`checked_cast_unsigned`](Self::checked_cast_unsigned),
/// or [`saturating_cast_unsigned`](Self::saturating_cast_unsigned).
///
/// # Examples
///
/// ```should_panic
/// #![feature(integer_cast_extras)]
#[doc = "let _ = i32::MIN.strict_cast_unsigned();"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_cast_unsigned(self) -> u32 {
match self.checked_cast_unsigned() {
Some(n) => n,
None => imp::overflow_panic::cast_integer(),
}
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `<<` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x10000b3i32;"]
#[doc = "let m = 0xb301;"]
///
#[doc = "assert_eq!(n.rotate_left(8), m);"]
#[doc = "assert_eq!(n.rotate_left(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn rotate_left(self, n: u32) -> Self {
(self as u32).rotate_left(n) as Self
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `>>` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0xb301i32;"]
#[doc = "let m = 0x10000b3;"]
///
#[doc = "assert_eq!(n.rotate_right(8), m);"]
#[doc = "assert_eq!(n.rotate_right(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn rotate_right(self, n: u32) -> Self {
(self as u32).rotate_right(n) as Self
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x12345678i32;"]
///
/// let m = n.swap_bytes();
///
#[doc = "assert_eq!(m, 0x78563412);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn swap_bytes(self) -> Self { (self as u32).swap_bytes() as Self }
/// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
/// second least-significant bit becomes second most-significant bit, etc.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x12345678i32;"]
/// let m = n.reverse_bits();
///
#[doc = "assert_eq!(m, 0x1e6a2c48);"]
#[doc = "assert_eq!(0, 0i32.reverse_bits());"]
/// ```
#[stable(feature = "reverse_bits", since = "1.37.0")]
#[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn reverse_bits(self) -> Self {
(self as u32).reverse_bits() as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are swapped.
///
/// See also [from_be_bytes()](Self::from_be_bytes).
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai32;"]
///
/// if cfg!(target_endian = "big") {
#[doc = " assert_eq!(i32::from_be(n), n)"]
/// } else {
#[doc = " assert_eq!(i32::from_be(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn from_be(x: Self) -> Self { x.swap_bytes() }
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are swapped.
///
/// See also [from_le_bytes()](Self::from_le_bytes).
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai32;"]
///
/// if cfg!(target_endian = "little") {
#[doc = " assert_eq!(i32::from_le(n), n)"]
/// } else {
#[doc = " assert_eq!(i32::from_le(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn from_le(x: Self) -> Self { x }
/// Swaps bytes of `self` on little endian targets.
///
/// On big endian this is a no-op.
///
/// The returned value has the same type as `self`, and will be interpreted
/// as (a potentially different) value of a native-endian
#[doc = "`i32`."]
///
/// See [`to_be_bytes()`](Self::to_be_bytes) for a type-safe alternative.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai32;"]
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be(self) -> Self { self.swap_bytes() }
/// Swaps bytes of `self` on big endian targets.
///
/// On little endian this is a no-op.
///
/// The returned value has the same type as `self`, and will be interpreted
/// as (a potentially different) value of a native-endian
#[doc = "`i32`."]
///
/// See [`to_le_bytes()`](Self::to_le_bytes) for a type-safe alternative.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai32;"]
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le(self) -> Self { self }
/// Checked integer addition. Computes `self + rhs`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i32::MAX - 2).checked_add(1), Some(i32::MAX - 1));"]
#[doc = "assert_eq!((i32::MAX - 2).checked_add(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_add(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer addition. Computes `self + rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i32::MAX - 2).strict_add(1), i32::MAX - 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i32::MAX - 2).strict_add(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_add(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Unchecked integer addition. Computes `self + rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_add(y)` is semantically equivalent to calling
/// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_add`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self + rhs > i32::MAX` or `self + rhs < i32::MIN`,"]
/// i.e. when [`checked_add`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_add`]: i32::checked_add"]
#[doc = "[`wrapping_add`]: i32::wrapping_add"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i32, rhs: i32) {
if !!lhs.overflowing_add(rhs).1 {
let msg =
"unsafe precondition(s) violated: i32::unchecked_add cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_add(self, rhs) }
}
/// Checked addition with an unsigned integer. Computes `self + rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i32.checked_add_unsigned(2), Some(3));"]
#[doc = "assert_eq!((i32::MAX - 2).checked_add_unsigned(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add_unsigned(self, rhs: u32) -> Option<Self> {
let (a, b) = self.overflowing_add_unsigned(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict addition with an unsigned integer. Computes `self + rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i32.strict_add_unsigned(2), 3);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i32::MAX - 2).strict_add_unsigned(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add_unsigned(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_add_unsigned(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Checked integer subtraction. Computes `self - rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i32::MIN + 2).checked_sub(1), Some(i32::MIN + 1));"]
#[doc = "assert_eq!((i32::MIN + 2).checked_sub(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_sub(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer subtraction. Computes `self - rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i32::MIN + 2).strict_sub(1), i32::MIN + 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i32::MIN + 2).strict_sub(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_sub(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
/// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_sub`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self - rhs > i32::MAX` or `self - rhs < i32::MIN`,"]
/// i.e. when [`checked_sub`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_sub`]: i32::checked_sub"]
#[doc = "[`wrapping_sub`]: i32::wrapping_sub"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i32, rhs: i32) {
if !!lhs.overflowing_sub(rhs).1 {
let msg =
"unsafe precondition(s) violated: i32::unchecked_sub cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_sub(self, rhs) }
}
/// Checked subtraction with an unsigned integer. Computes `self - rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i32.checked_sub_unsigned(2), Some(-1));"]
#[doc = "assert_eq!((i32::MIN + 2).checked_sub_unsigned(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub_unsigned(self, rhs: u32) -> Option<Self> {
let (a, b) = self.overflowing_sub_unsigned(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict subtraction with an unsigned integer. Computes `self - rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i32.strict_sub_unsigned(2), -1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i32::MIN + 2).strict_sub_unsigned(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub_unsigned(self, rhs: u32) -> Self {
let (a, b) = self.overflowing_sub_unsigned(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Checked integer multiplication. Computes `self * rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i32::MAX.checked_mul(1), Some(i32::MAX));"]
#[doc = "assert_eq!(i32::MAX.checked_mul(2), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer multiplication. Computes `self * rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i32::MAX.strict_mul(1), i32::MAX);"]
/// ```
///
/// The following panics because of overflow:
///
/// ``` should_panic
#[doc = "let _ = i32::MAX.strict_mul(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_mul(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_mul(rhs);
if b { imp::overflow_panic::mul() } else { a }
}
/// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
/// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_mul`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self * rhs > i32::MAX` or `self * rhs < i32::MIN`,"]
/// i.e. when [`checked_mul`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_mul`]: i32::checked_mul"]
#[doc = "[`wrapping_mul`]: i32::wrapping_mul"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i32, rhs: i32) {
if !!lhs.overflowing_mul(rhs).1 {
let msg =
"unsafe precondition(s) violated: i32::unchecked_mul cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_mul(self, rhs) }
}
/// Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
/// or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i32::MIN + 1).checked_div(-1), Some(2147483647));"]
#[doc = "assert_eq!(i32::MIN.checked_div(-1), None);"]
#[doc = "assert_eq!((1i32).checked_div(0), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1)))
{
None
} else { Some(unsafe { intrinsics::unchecked_div(self, rhs) }) }
}
/// Strict integer division. Computes `self / rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is when one divides `MIN / -1` on a signed type (where
/// `MIN` 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.
///
/// # 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 {
let (a, b) = self.overflowing_div(rhs);
if b { imp::overflow_panic::div() } else { a }
}
/// 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` 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.
///
/// # 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 {
let (a, b) = self.overflowing_div_euclid(rhs);
if b { imp::overflow_panic::div() } else { a }
}
/// 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` 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` 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> {
if exp == 0 { return Some(1); }
let mut base = self;
let mut acc: Self = 1;
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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc: Self = 1;
loop {
if (exp & 1) == 1 {
acc = acc.strict_mul(base);
if exp == 1 { return acc; }
}
exp /= 2;
base = base.strict_mul(base);
}
}
/// 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` 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` 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` 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` 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` 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` 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` on a signed type (where `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` 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. The behaviour 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. The behaviour 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` 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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc: Self = 1;
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 { acc = acc.wrapping_mul(base); }
exp /= 2;
base = base.wrapping_mul(base);
}
acc.wrapping_mul(base)
} else {
loop {
if (exp & 1) == 1 {
acc = acc.wrapping_mul(base);
if exp == 1 { return acc; }
}
exp /= 2;
base = base.wrapping_mul(base);
}
}
}
/// 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) {
if exp == 0 { return (1, false); }
let mut base = self;
let mut acc: Self = 1;
let mut overflown = false;
let mut r;
loop {
if (exp & 1) == 1 {
r = acc.overflowing_mul(base);
if exp == 1 { r.1 |= overflown; return r; }
acc = r.0;
overflown |= r.1;
}
exp /= 2;
r = base.overflowing_mul(base);
base = r.0;
overflown |= r.1;
}
}
/// 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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc = 1;
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 { acc = acc * base; }
exp /= 2;
base = base * base;
}
acc * base
} else {
loop {
if (exp & 1) == 1 {
acc = acc * base;
if exp == 1 { return acc; }
}
exp /= 2;
base = base * base;
}
}
}
/// 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` can produce results more efficiently for base 2, and `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.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2i32.checked_ilog2(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog2(self) -> Option<u32> {
if self <= 0 {
None
} else {
let log =
(Self::BITS - 1) -
unsafe { intrinsics::ctlz_nonzero(self) as u32 };
Some(log)
}
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// Returns `None` if the number is negative or zero.
///
/// # Example
///
/// ```
#[doc = "assert_eq!(10i32.checked_ilog10(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog10(self) -> Option<u32> {
imp::int_log10::i32(self as i32)
}
/// Computes the absolute value of `self`.
///
/// # Overflow behavior
///
/// The absolute value of
#[doc = "`i32::MIN`"]
/// cannot be represented as an
#[doc = "`i32`,"]
/// and attempting to calculate it will cause an overflow. This means
/// that code in debug mode will trigger a panic on this case and
/// optimized code will return
#[doc = "`i32::MIN`"]
/// without a panic. If you do not want this behavior, consider
/// using [`unsigned_abs`](Self::unsigned_abs) instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i32.abs(), 10);"]
#[doc = "assert_eq!((-10i32).abs(), 10);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[allow(unused_attributes)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn abs(self) -> Self {
if self.is_negative() { -self } else { self }
}
/// Computes the absolute difference between `self` and `other`.
///
/// This function always returns the correct answer without overflow or
/// panics by returning an unsigned integer.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i32.abs_diff(80), 20u32);"]
#[doc = "assert_eq!(100i32.abs_diff(110), 10u32);"]
#[doc = "assert_eq!((-100i32).abs_diff(80), 180u32);"]
#[doc = "assert_eq!((-100i32).abs_diff(-120), 20u32);"]
#[doc = "assert_eq!(i32::MIN.abs_diff(i32::MAX), u32::MAX);"]
/// ```
#[stable(feature = "int_abs_diff", since = "1.60.0")]
#[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn abs_diff(self, other: Self) -> u32 {
if self < other {
(other as u32).wrapping_sub(self as u32)
} else { (self as u32).wrapping_sub(other as u32) }
}
/// Returns a number representing sign of `self`.
///
/// - `0` if the number is zero
/// - `1` if the number is positive
/// - `-1` if the number is negative
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i32.signum(), 1);"]
#[doc = "assert_eq!(0i32.signum(), 0);"]
#[doc = "assert_eq!((-10i32).signum(), -1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_sign", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn signum(self) -> Self {
crate::intrinsics::three_way_compare(self, 0) as Self
}
/// Returns `true` if `self` is positive and `false` if the number is zero or
/// negative.
///
/// # Examples
///
/// ```
#[doc = "assert!(10i32.is_positive());"]
#[doc = "assert!(!(-10i32).is_positive());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[inline(always)]
pub const fn is_positive(self) -> bool { self > 0 }
/// Returns `true` if `self` is negative and `false` if the number is zero or
/// positive.
///
/// # Examples
///
/// ```
#[doc = "assert!((-10i32).is_negative());"]
#[doc = "assert!(!10i32.is_negative());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[inline(always)]
pub const fn is_negative(self) -> bool { self < 0 }
/// Returns the memory representation of this integer as a byte array in
/// big-endian (network) byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12345678i32.to_be_bytes();"]
#[doc = "assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
self.to_be().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// little-endian byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12345678i32.to_le_bytes();"]
#[doc = "assert_eq!(bytes, [0x78, 0x56, 0x34, 0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
self.to_le().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code
/// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
/// instead.
///
#[doc = ""]
///
/// [`to_be_bytes`]: Self::to_be_bytes
/// [`to_le_bytes`]: Self::to_le_bytes
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12345678i32.to_ne_bytes();"]
/// assert_eq!(
/// bytes,
/// if cfg!(target_endian = "big") {
#[doc = " [0x12, 0x34, 0x56, 0x78]"]
/// } else {
#[doc = " [0x78, 0x56, 0x34, 0x12]"]
/// }
/// );
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
unsafe { mem::transmute(self) }
}
/// Creates an integer value from its representation as a byte array in
/// big endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = i32::from_be_bytes([0x12, 0x34, 0x56, 0x78]);"]
#[doc = "assert_eq!(value, 0x12345678);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_be_i32(input: &mut &[u8]) -> i32 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i32>());"]
/// *input = rest;
#[doc = " i32::from_be_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_be(Self::from_ne_bytes(bytes))
}
/// Creates an integer value from its representation as a byte array in
/// little endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = i32::from_le_bytes([0x78, 0x56, 0x34, 0x12]);"]
#[doc = "assert_eq!(value, 0x12345678);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_le_i32(input: &mut &[u8]) -> i32 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i32>());"]
/// *input = rest;
#[doc = " i32::from_le_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_le(Self::from_ne_bytes(bytes))
}
/// Creates an integer value from its memory representation as a byte
/// array in native endianness.
///
/// As the target platform's native endianness is used, portable code
/// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
/// appropriate instead.
///
/// [`from_be_bytes`]: Self::from_be_bytes
/// [`from_le_bytes`]: Self::from_le_bytes
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = i32::from_ne_bytes(if cfg!(target_endian = \"big\") {"]
#[doc = " [0x12, 0x34, 0x56, 0x78]"]
/// } else {
#[doc = " [0x78, 0x56, 0x34, 0x12]"]
/// });
#[doc = "assert_eq!(value, 0x12345678);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_ne_i32(input: &mut &[u8]) -> i32 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i32>());"]
/// *input = rest;
#[doc = " i32::from_ne_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use]
#[inline]
pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
unsafe { mem::transmute(bytes) }
}
/// New code should prefer to use
#[doc = "[`i32::MIN`] instead."]
///
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MIN` associated constant on this type")]
#[rustc_diagnostic_item = "i32_legacy_fn_min_value"]
pub const fn min_value() -> Self { Self::MIN }
/// New code should prefer to use
#[doc = "[`i32::MAX`] instead."]
///
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MAX` associated constant on this type")]
#[rustc_diagnostic_item = "i32_legacy_fn_max_value"]
pub const fn max_value() -> Self { Self::MAX }
/// Clamps this number to a symmetric range centred around zero.
///
/// The method clamps the number's magnitude (absolute value) to be at most `limit`.
///
/// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
/// explicit about the intent.
///
/// # Examples
///
/// ```
/// #![feature(clamp_magnitude)]
#[doc = "assert_eq!(120i32.clamp_magnitude(100), 100);"]
#[doc = "assert_eq!(-120i32.clamp_magnitude(100), -100);"]
#[doc = "assert_eq!(80i32.clamp_magnitude(100), 80);"]
#[doc = "assert_eq!(-80i32.clamp_magnitude(100), -80);"]
/// ```
#[must_use =
"this returns the clamped value and does not modify the original"]
#[unstable(feature = "clamp_magnitude", issue = "148519")]
#[inline]
pub fn clamp_magnitude(self, limit: u32) -> Self {
if let Ok(limit) = core::convert::TryInto::<i32>::try_into(limit) {
self.clamp(-limit, limit)
} else { self }
}
/// Truncate an integer to an integer of the same size or smaller, preserving the least
/// significant bits.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i8, 120i32.truncate());"]
#[doc = "assert_eq!(-120i8, (-120i32).truncate());"]
/// assert_eq!(120i8, 376i32.truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
/// instead of truncating.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i8, 120i32.saturating_truncate());"]
#[doc = "assert_eq!(-120i8, (-120i32).saturating_truncate());"]
/// assert_eq!(127i8, 376i32.saturating_truncate());
/// assert_eq!(-128i8, (-1000i32).saturating_truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn saturating_truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_saturating_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
/// is outside the bounds of the smaller type.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(Some(120i8), 120i32.checked_truncate());"]
#[doc = "assert_eq!(Some(-120i8), (-120i32).checked_truncate());"]
/// assert_eq!(None, 376i32.checked_truncate::<i8>());
/// assert_eq!(None, (-1000i32).checked_truncate::<i8>());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn checked_truncate<Target>(self) -> Option<Target> where
Self: [const] traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_checked_truncate(self)
}
/// Widen to an integer of the same size or larger, preserving its value.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i128, 120i8.widen());"]
#[doc = "assert_eq!(-120i128, (-120i8).widen());"]
/// ```
#[must_use =
"this returns the widened value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn widen<Target>(self) -> Target where Self: [const]
traits::WidenTarget<Target> {
traits::WidenTarget::internal_widen(self)
}int_impl! {
426Self = i32,
427 ActualT = i32,
428 UnsignedT = u32,
429 BITS = 32,
430 BITS_MINUS_ONE = 31,
431 Min = -2147483648,
432 Max = 2147483647,
433 rot = 8,
434 rot_op = "0x10000b3",
435 rot_result = "0xb301",
436 swap_op = "0x12345678",
437 swapped = "0x78563412",
438 reversed = "0x1e6a2c48",
439 le_bytes = "[0x78, 0x56, 0x34, 0x12]",
440 be_bytes = "[0x12, 0x34, 0x56, 0x78]",
441 to_xe_bytes_doc = "",
442 from_xe_bytes_doc = "",
443 bound_condition = "",
444 }445/// 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 }446/// 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 }447}
448449impl i64 {
450/// 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 =
"CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"CURRENT_RUSTC_VERSION")]
#[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 =
"CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"CURRENT_RUSTC_VERSION")]
#[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`.
///
/// # 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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since =
"CURRENT_RUSTC_VERSION")]
#[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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since =
"CURRENT_RUSTC_VERSION")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn lowest_one(self) -> Option<u32> { (self as u64).lowest_one() }
/// Returns the bit pattern of `self` reinterpreted as an unsigned integer of the same size.
///
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
/// the same.
///
/// # Examples
///
/// ```
#[doc = "let n = -1i64;"]
///
#[doc = "assert_eq!(n.cast_unsigned(), u64::MAX);"]
/// ```
#[stable(feature = "integer_sign_cast", since = "1.87.0")]
#[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_unsigned(self) -> u64 { self as u64 }
/// Saturating conversion of `self` to an unsigned integer of the same size.
///
/// Negative values are clamped to `0`.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`checked_cast_unsigned`](Self::checked_cast_unsigned),
/// or [`strict_cast_unsigned`](Self::strict_cast_unsigned).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = i64::MIN;"]
///
#[doc = "assert_eq!(n.saturating_cast_unsigned(), 0u64);"]
#[doc = "assert_eq!(64i64.saturating_cast_unsigned(), 64u64);"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_cast_unsigned(self) -> u64 {
if self >= 0 { self.cast_unsigned() } else { 0 }
}
/// Checked conversion of `self` to an unsigned integer of the same size,
/// returning `None` if `self` is negative.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`saturating_cast_unsigned`](Self::saturating_cast_unsigned),
/// or [`strict_cast_unsigned`](Self::strict_cast_unsigned).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = i64::MIN;"]
///
#[doc = "assert_eq!(n.checked_cast_unsigned(), None);"]
#[doc = "assert_eq!(64i64.checked_cast_unsigned(), Some(64u64));"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn checked_cast_unsigned(self) -> Option<u64> {
if self >= 0 { Some(self.cast_unsigned()) } else { None }
}
/// Strict conversion of `self` to an unsigned integer of the same size,
/// which panics if `self` is negative.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`checked_cast_unsigned`](Self::checked_cast_unsigned),
/// or [`saturating_cast_unsigned`](Self::saturating_cast_unsigned).
///
/// # Examples
///
/// ```should_panic
/// #![feature(integer_cast_extras)]
#[doc = "let _ = i64::MIN.strict_cast_unsigned();"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_cast_unsigned(self) -> u64 {
match self.checked_cast_unsigned() {
Some(n) => n,
None => imp::overflow_panic::cast_integer(),
}
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `<<` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0xaa00000000006e1i64;"]
#[doc = "let m = 0x6e10aa;"]
///
#[doc = "assert_eq!(n.rotate_left(12), m);"]
#[doc = "assert_eq!(n.rotate_left(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn rotate_left(self, n: u32) -> Self {
(self as u64).rotate_left(n) as Self
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `>>` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x6e10aai64;"]
#[doc = "let m = 0xaa00000000006e1;"]
///
#[doc = "assert_eq!(n.rotate_right(12), m);"]
#[doc = "assert_eq!(n.rotate_right(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn rotate_right(self, n: u32) -> Self {
(self as u64).rotate_right(n) as Self
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1234567890123456i64;"]
///
/// let m = n.swap_bytes();
///
#[doc = "assert_eq!(m, 0x5634129078563412);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn swap_bytes(self) -> Self { (self as u64).swap_bytes() as Self }
/// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
/// second least-significant bit becomes second most-significant bit, etc.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1234567890123456i64;"]
/// let m = n.reverse_bits();
///
#[doc = "assert_eq!(m, 0x6a2c48091e6a2c48);"]
#[doc = "assert_eq!(0, 0i64.reverse_bits());"]
/// ```
#[stable(feature = "reverse_bits", since = "1.37.0")]
#[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn reverse_bits(self) -> Self {
(self as u64).reverse_bits() as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are swapped.
///
/// See also [from_be_bytes()](Self::from_be_bytes).
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai64;"]
///
/// if cfg!(target_endian = "big") {
#[doc = " assert_eq!(i64::from_be(n), n)"]
/// } else {
#[doc = " assert_eq!(i64::from_be(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn from_be(x: Self) -> Self { x.swap_bytes() }
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are swapped.
///
/// See also [from_le_bytes()](Self::from_le_bytes).
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai64;"]
///
/// if cfg!(target_endian = "little") {
#[doc = " assert_eq!(i64::from_le(n), n)"]
/// } else {
#[doc = " assert_eq!(i64::from_le(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn from_le(x: Self) -> Self { x }
/// Swaps bytes of `self` on little endian targets.
///
/// On big endian this is a no-op.
///
/// The returned value has the same type as `self`, and will be interpreted
/// as (a potentially different) value of a native-endian
#[doc = "`i64`."]
///
/// See [`to_be_bytes()`](Self::to_be_bytes) for a type-safe alternative.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai64;"]
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be(self) -> Self { self.swap_bytes() }
/// Swaps bytes of `self` on big endian targets.
///
/// On little endian this is a no-op.
///
/// The returned value has the same type as `self`, and will be interpreted
/// as (a potentially different) value of a native-endian
#[doc = "`i64`."]
///
/// See [`to_le_bytes()`](Self::to_le_bytes) for a type-safe alternative.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai64;"]
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le(self) -> Self { self }
/// Checked integer addition. Computes `self + rhs`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i64::MAX - 2).checked_add(1), Some(i64::MAX - 1));"]
#[doc = "assert_eq!((i64::MAX - 2).checked_add(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_add(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer addition. Computes `self + rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i64::MAX - 2).strict_add(1), i64::MAX - 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i64::MAX - 2).strict_add(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_add(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Unchecked integer addition. Computes `self + rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_add(y)` is semantically equivalent to calling
/// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_add`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self + rhs > i64::MAX` or `self + rhs < i64::MIN`,"]
/// i.e. when [`checked_add`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_add`]: i64::checked_add"]
#[doc = "[`wrapping_add`]: i64::wrapping_add"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i64, rhs: i64) {
if !!lhs.overflowing_add(rhs).1 {
let msg =
"unsafe precondition(s) violated: i64::unchecked_add cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_add(self, rhs) }
}
/// Checked addition with an unsigned integer. Computes `self + rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i64.checked_add_unsigned(2), Some(3));"]
#[doc = "assert_eq!((i64::MAX - 2).checked_add_unsigned(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add_unsigned(self, rhs: u64) -> Option<Self> {
let (a, b) = self.overflowing_add_unsigned(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict addition with an unsigned integer. Computes `self + rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i64.strict_add_unsigned(2), 3);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i64::MAX - 2).strict_add_unsigned(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add_unsigned(self, rhs: u64) -> Self {
let (a, b) = self.overflowing_add_unsigned(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Checked integer subtraction. Computes `self - rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i64::MIN + 2).checked_sub(1), Some(i64::MIN + 1));"]
#[doc = "assert_eq!((i64::MIN + 2).checked_sub(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_sub(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer subtraction. Computes `self - rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i64::MIN + 2).strict_sub(1), i64::MIN + 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i64::MIN + 2).strict_sub(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_sub(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
/// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_sub`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self - rhs > i64::MAX` or `self - rhs < i64::MIN`,"]
/// i.e. when [`checked_sub`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_sub`]: i64::checked_sub"]
#[doc = "[`wrapping_sub`]: i64::wrapping_sub"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i64, rhs: i64) {
if !!lhs.overflowing_sub(rhs).1 {
let msg =
"unsafe precondition(s) violated: i64::unchecked_sub cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_sub(self, rhs) }
}
/// Checked subtraction with an unsigned integer. Computes `self - rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i64.checked_sub_unsigned(2), Some(-1));"]
#[doc = "assert_eq!((i64::MIN + 2).checked_sub_unsigned(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub_unsigned(self, rhs: u64) -> Option<Self> {
let (a, b) = self.overflowing_sub_unsigned(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict subtraction with an unsigned integer. Computes `self - rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i64.strict_sub_unsigned(2), -1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i64::MIN + 2).strict_sub_unsigned(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub_unsigned(self, rhs: u64) -> Self {
let (a, b) = self.overflowing_sub_unsigned(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Checked integer multiplication. Computes `self * rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i64::MAX.checked_mul(1), Some(i64::MAX));"]
#[doc = "assert_eq!(i64::MAX.checked_mul(2), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer multiplication. Computes `self * rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i64::MAX.strict_mul(1), i64::MAX);"]
/// ```
///
/// The following panics because of overflow:
///
/// ``` should_panic
#[doc = "let _ = i64::MAX.strict_mul(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_mul(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_mul(rhs);
if b { imp::overflow_panic::mul() } else { a }
}
/// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
/// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_mul`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self * rhs > i64::MAX` or `self * rhs < i64::MIN`,"]
/// i.e. when [`checked_mul`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_mul`]: i64::checked_mul"]
#[doc = "[`wrapping_mul`]: i64::wrapping_mul"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i64, rhs: i64) {
if !!lhs.overflowing_mul(rhs).1 {
let msg =
"unsafe precondition(s) violated: i64::unchecked_mul cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_mul(self, rhs) }
}
/// Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
/// or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc =
"assert_eq!((i64::MIN + 1).checked_div(-1), Some(9223372036854775807));"]
#[doc = "assert_eq!(i64::MIN.checked_div(-1), None);"]
#[doc = "assert_eq!((1i64).checked_div(0), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1)))
{
None
} else { Some(unsafe { intrinsics::unchecked_div(self, rhs) }) }
}
/// Strict integer division. Computes `self / rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is when one divides `MIN / -1` on a signed type (where
/// `MIN` 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.
///
/// # 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 {
let (a, b) = self.overflowing_div(rhs);
if b { imp::overflow_panic::div() } else { a }
}
/// 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` 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.
///
/// # 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 {
let (a, b) = self.overflowing_div_euclid(rhs);
if b { imp::overflow_panic::div() } else { a }
}
/// 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` 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` 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> {
if exp == 0 { return Some(1); }
let mut base = self;
let mut acc: Self = 1;
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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc: Self = 1;
loop {
if (exp & 1) == 1 {
acc = acc.strict_mul(base);
if exp == 1 { return acc; }
}
exp /= 2;
base = base.strict_mul(base);
}
}
/// 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` 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` 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` 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` 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` 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` 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` on a signed type (where `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` 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. The behaviour 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. The behaviour 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` 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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc: Self = 1;
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 { acc = acc.wrapping_mul(base); }
exp /= 2;
base = base.wrapping_mul(base);
}
acc.wrapping_mul(base)
} else {
loop {
if (exp & 1) == 1 {
acc = acc.wrapping_mul(base);
if exp == 1 { return acc; }
}
exp /= 2;
base = base.wrapping_mul(base);
}
}
}
/// 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) {
if exp == 0 { return (1, false); }
let mut base = self;
let mut acc: Self = 1;
let mut overflown = false;
let mut r;
loop {
if (exp & 1) == 1 {
r = acc.overflowing_mul(base);
if exp == 1 { r.1 |= overflown; return r; }
acc = r.0;
overflown |= r.1;
}
exp /= 2;
r = base.overflowing_mul(base);
base = r.0;
overflown |= r.1;
}
}
/// 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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc = 1;
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 { acc = acc * base; }
exp /= 2;
base = base * base;
}
acc * base
} else {
loop {
if (exp & 1) == 1 {
acc = acc * base;
if exp == 1 { return acc; }
}
exp /= 2;
base = base * base;
}
}
}
/// 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` can produce results more efficiently for base 2, and `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.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2i64.checked_ilog2(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog2(self) -> Option<u32> {
if self <= 0 {
None
} else {
let log =
(Self::BITS - 1) -
unsafe { intrinsics::ctlz_nonzero(self) as u32 };
Some(log)
}
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// Returns `None` if the number is negative or zero.
///
/// # Example
///
/// ```
#[doc = "assert_eq!(10i64.checked_ilog10(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog10(self) -> Option<u32> {
imp::int_log10::i64(self as i64)
}
/// Computes the absolute value of `self`.
///
/// # Overflow behavior
///
/// The absolute value of
#[doc = "`i64::MIN`"]
/// cannot be represented as an
#[doc = "`i64`,"]
/// and attempting to calculate it will cause an overflow. This means
/// that code in debug mode will trigger a panic on this case and
/// optimized code will return
#[doc = "`i64::MIN`"]
/// without a panic. If you do not want this behavior, consider
/// using [`unsigned_abs`](Self::unsigned_abs) instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i64.abs(), 10);"]
#[doc = "assert_eq!((-10i64).abs(), 10);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[allow(unused_attributes)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn abs(self) -> Self {
if self.is_negative() { -self } else { self }
}
/// Computes the absolute difference between `self` and `other`.
///
/// This function always returns the correct answer without overflow or
/// panics by returning an unsigned integer.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i64.abs_diff(80), 20u64);"]
#[doc = "assert_eq!(100i64.abs_diff(110), 10u64);"]
#[doc = "assert_eq!((-100i64).abs_diff(80), 180u64);"]
#[doc = "assert_eq!((-100i64).abs_diff(-120), 20u64);"]
#[doc = "assert_eq!(i64::MIN.abs_diff(i64::MAX), u64::MAX);"]
/// ```
#[stable(feature = "int_abs_diff", since = "1.60.0")]
#[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn abs_diff(self, other: Self) -> u64 {
if self < other {
(other as u64).wrapping_sub(self as u64)
} else { (self as u64).wrapping_sub(other as u64) }
}
/// Returns a number representing sign of `self`.
///
/// - `0` if the number is zero
/// - `1` if the number is positive
/// - `-1` if the number is negative
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i64.signum(), 1);"]
#[doc = "assert_eq!(0i64.signum(), 0);"]
#[doc = "assert_eq!((-10i64).signum(), -1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_sign", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn signum(self) -> Self {
crate::intrinsics::three_way_compare(self, 0) as Self
}
/// Returns `true` if `self` is positive and `false` if the number is zero or
/// negative.
///
/// # Examples
///
/// ```
#[doc = "assert!(10i64.is_positive());"]
#[doc = "assert!(!(-10i64).is_positive());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[inline(always)]
pub const fn is_positive(self) -> bool { self > 0 }
/// Returns `true` if `self` is negative and `false` if the number is zero or
/// positive.
///
/// # Examples
///
/// ```
#[doc = "assert!((-10i64).is_negative());"]
#[doc = "assert!(!10i64.is_negative());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[inline(always)]
pub const fn is_negative(self) -> bool { self < 0 }
/// Returns the memory representation of this integer as a byte array in
/// big-endian (network) byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234567890123456i64.to_be_bytes();"]
#[doc =
"assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
self.to_be().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// little-endian byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234567890123456i64.to_le_bytes();"]
#[doc =
"assert_eq!(bytes, [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
self.to_le().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code
/// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
/// instead.
///
#[doc = ""]
///
/// [`to_be_bytes`]: Self::to_be_bytes
/// [`to_le_bytes`]: Self::to_le_bytes
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234567890123456i64.to_ne_bytes();"]
/// assert_eq!(
/// bytes,
/// if cfg!(target_endian = "big") {
#[doc = " [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]"]
/// } else {
#[doc = " [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]"]
/// }
/// );
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
unsafe { mem::transmute(self) }
}
/// Creates an integer value from its representation as a byte array in
/// big endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc =
"let value = i64::from_be_bytes([0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]);"]
#[doc = "assert_eq!(value, 0x1234567890123456);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_be_i64(input: &mut &[u8]) -> i64 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i64>());"]
/// *input = rest;
#[doc = " i64::from_be_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_be(Self::from_ne_bytes(bytes))
}
/// Creates an integer value from its representation as a byte array in
/// little endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc =
"let value = i64::from_le_bytes([0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);"]
#[doc = "assert_eq!(value, 0x1234567890123456);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_le_i64(input: &mut &[u8]) -> i64 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i64>());"]
/// *input = rest;
#[doc = " i64::from_le_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_le(Self::from_ne_bytes(bytes))
}
/// Creates an integer value from its memory representation as a byte
/// array in native endianness.
///
/// As the target platform's native endianness is used, portable code
/// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
/// appropriate instead.
///
/// [`from_be_bytes`]: Self::from_be_bytes
/// [`from_le_bytes`]: Self::from_le_bytes
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = i64::from_ne_bytes(if cfg!(target_endian = \"big\") {"]
#[doc = " [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]"]
/// } else {
#[doc = " [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]"]
/// });
#[doc = "assert_eq!(value, 0x1234567890123456);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_ne_i64(input: &mut &[u8]) -> i64 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i64>());"]
/// *input = rest;
#[doc = " i64::from_ne_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use]
#[inline]
pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
unsafe { mem::transmute(bytes) }
}
/// New code should prefer to use
#[doc = "[`i64::MIN`] instead."]
///
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MIN` associated constant on this type")]
#[rustc_diagnostic_item = "i64_legacy_fn_min_value"]
pub const fn min_value() -> Self { Self::MIN }
/// New code should prefer to use
#[doc = "[`i64::MAX`] instead."]
///
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MAX` associated constant on this type")]
#[rustc_diagnostic_item = "i64_legacy_fn_max_value"]
pub const fn max_value() -> Self { Self::MAX }
/// Clamps this number to a symmetric range centred around zero.
///
/// The method clamps the number's magnitude (absolute value) to be at most `limit`.
///
/// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
/// explicit about the intent.
///
/// # Examples
///
/// ```
/// #![feature(clamp_magnitude)]
#[doc = "assert_eq!(120i64.clamp_magnitude(100), 100);"]
#[doc = "assert_eq!(-120i64.clamp_magnitude(100), -100);"]
#[doc = "assert_eq!(80i64.clamp_magnitude(100), 80);"]
#[doc = "assert_eq!(-80i64.clamp_magnitude(100), -80);"]
/// ```
#[must_use =
"this returns the clamped value and does not modify the original"]
#[unstable(feature = "clamp_magnitude", issue = "148519")]
#[inline]
pub fn clamp_magnitude(self, limit: u64) -> Self {
if let Ok(limit) = core::convert::TryInto::<i64>::try_into(limit) {
self.clamp(-limit, limit)
} else { self }
}
/// Truncate an integer to an integer of the same size or smaller, preserving the least
/// significant bits.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i8, 120i64.truncate());"]
#[doc = "assert_eq!(-120i8, (-120i64).truncate());"]
/// assert_eq!(120i8, 376i32.truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
/// instead of truncating.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i8, 120i64.saturating_truncate());"]
#[doc = "assert_eq!(-120i8, (-120i64).saturating_truncate());"]
/// assert_eq!(127i8, 376i32.saturating_truncate());
/// assert_eq!(-128i8, (-1000i32).saturating_truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn saturating_truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_saturating_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
/// is outside the bounds of the smaller type.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(Some(120i8), 120i64.checked_truncate());"]
#[doc = "assert_eq!(Some(-120i8), (-120i64).checked_truncate());"]
/// assert_eq!(None, 376i32.checked_truncate::<i8>());
/// assert_eq!(None, (-1000i32).checked_truncate::<i8>());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn checked_truncate<Target>(self) -> Option<Target> where
Self: [const] traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_checked_truncate(self)
}
/// Widen to an integer of the same size or larger, preserving its value.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i128, 120i8.widen());"]
#[doc = "assert_eq!(-120i128, (-120i8).widen());"]
/// ```
#[must_use =
"this returns the widened value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn widen<Target>(self) -> Target where Self: [const]
traits::WidenTarget<Target> {
traits::WidenTarget::internal_widen(self)
}int_impl! {
451Self = i64,
452 ActualT = i64,
453 UnsignedT = u64,
454 BITS = 64,
455 BITS_MINUS_ONE = 63,
456 Min = -9223372036854775808,
457 Max = 9223372036854775807,
458 rot = 12,
459 rot_op = "0xaa00000000006e1",
460 rot_result = "0x6e10aa",
461 swap_op = "0x1234567890123456",
462 swapped = "0x5634129078563412",
463 reversed = "0x6a2c48091e6a2c48",
464 le_bytes = "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
465 be_bytes = "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
466 to_xe_bytes_doc = "",
467 from_xe_bytes_doc = "",
468 bound_condition = "",
469 }470/// 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 }471/// 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 }472}
473474impl i128 {
475/// 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 =
"CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"CURRENT_RUSTC_VERSION")]
#[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 =
"CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"CURRENT_RUSTC_VERSION")]
#[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`.
///
/// # 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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since =
"CURRENT_RUSTC_VERSION")]
#[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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since =
"CURRENT_RUSTC_VERSION")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn lowest_one(self) -> Option<u32> { (self as u128).lowest_one() }
/// Returns the bit pattern of `self` reinterpreted as an unsigned integer of the same size.
///
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
/// the same.
///
/// # Examples
///
/// ```
#[doc = "let n = -1i128;"]
///
#[doc = "assert_eq!(n.cast_unsigned(), u128::MAX);"]
/// ```
#[stable(feature = "integer_sign_cast", since = "1.87.0")]
#[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_unsigned(self) -> u128 { self as u128 }
/// Saturating conversion of `self` to an unsigned integer of the same size.
///
/// Negative values are clamped to `0`.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`checked_cast_unsigned`](Self::checked_cast_unsigned),
/// or [`strict_cast_unsigned`](Self::strict_cast_unsigned).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = i128::MIN;"]
///
#[doc = "assert_eq!(n.saturating_cast_unsigned(), 0u128);"]
#[doc = "assert_eq!(64i128.saturating_cast_unsigned(), 64u128);"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_cast_unsigned(self) -> u128 {
if self >= 0 { self.cast_unsigned() } else { 0 }
}
/// Checked conversion of `self` to an unsigned integer of the same size,
/// returning `None` if `self` is negative.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`saturating_cast_unsigned`](Self::saturating_cast_unsigned),
/// or [`strict_cast_unsigned`](Self::strict_cast_unsigned).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = i128::MIN;"]
///
#[doc = "assert_eq!(n.checked_cast_unsigned(), None);"]
#[doc = "assert_eq!(64i128.checked_cast_unsigned(), Some(64u128));"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn checked_cast_unsigned(self) -> Option<u128> {
if self >= 0 { Some(self.cast_unsigned()) } else { None }
}
/// Strict conversion of `self` to an unsigned integer of the same size,
/// which panics if `self` is negative.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`checked_cast_unsigned`](Self::checked_cast_unsigned),
/// or [`saturating_cast_unsigned`](Self::saturating_cast_unsigned).
///
/// # Examples
///
/// ```should_panic
/// #![feature(integer_cast_extras)]
#[doc = "let _ = i128::MIN.strict_cast_unsigned();"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_cast_unsigned(self) -> u128 {
match self.checked_cast_unsigned() {
Some(n) => n,
None => imp::overflow_panic::cast_integer(),
}
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `<<` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x13f40000000000000000000000004f76i128;"]
#[doc = "let m = 0x4f7613f4;"]
///
#[doc = "assert_eq!(n.rotate_left(16), m);"]
#[doc = "assert_eq!(n.rotate_left(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn rotate_left(self, n: u32) -> Self {
(self as u128).rotate_left(n) as Self
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `>>` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x4f7613f4i128;"]
#[doc = "let m = 0x13f40000000000000000000000004f76;"]
///
#[doc = "assert_eq!(n.rotate_right(16), m);"]
#[doc = "assert_eq!(n.rotate_right(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn rotate_right(self, n: u32) -> Self {
(self as u128).rotate_right(n) as Self
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x12345678901234567890123456789012i128;"]
///
/// let m = n.swap_bytes();
///
#[doc = "assert_eq!(m, 0x12907856341290785634129078563412);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn swap_bytes(self) -> Self { (self as u128).swap_bytes() as Self }
/// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
/// second least-significant bit becomes second most-significant bit, etc.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x12345678901234567890123456789012i128;"]
/// let m = n.reverse_bits();
///
#[doc = "assert_eq!(m, 0x48091e6a2c48091e6a2c48091e6a2c48);"]
#[doc = "assert_eq!(0, 0i128.reverse_bits());"]
/// ```
#[stable(feature = "reverse_bits", since = "1.37.0")]
#[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn reverse_bits(self) -> Self {
(self as u128).reverse_bits() as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are swapped.
///
/// See also [from_be_bytes()](Self::from_be_bytes).
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai128;"]
///
/// if cfg!(target_endian = "big") {
#[doc = " assert_eq!(i128::from_be(n), n)"]
/// } else {
#[doc = " assert_eq!(i128::from_be(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn from_be(x: Self) -> Self { x.swap_bytes() }
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are swapped.
///
/// See also [from_le_bytes()](Self::from_le_bytes).
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai128;"]
///
/// if cfg!(target_endian = "little") {
#[doc = " assert_eq!(i128::from_le(n), n)"]
/// } else {
#[doc = " assert_eq!(i128::from_le(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn from_le(x: Self) -> Self { x }
/// Swaps bytes of `self` on little endian targets.
///
/// On big endian this is a no-op.
///
/// The returned value has the same type as `self`, and will be interpreted
/// as (a potentially different) value of a native-endian
#[doc = "`i128`."]
///
/// See [`to_be_bytes()`](Self::to_be_bytes) for a type-safe alternative.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai128;"]
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be(self) -> Self { self.swap_bytes() }
/// Swaps bytes of `self` on big endian targets.
///
/// On little endian this is a no-op.
///
/// The returned value has the same type as `self`, and will be interpreted
/// as (a potentially different) value of a native-endian
#[doc = "`i128`."]
///
/// See [`to_le_bytes()`](Self::to_le_bytes) for a type-safe alternative.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ai128;"]
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le(self) -> Self { self }
/// Checked integer addition. Computes `self + rhs`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i128::MAX - 2).checked_add(1), Some(i128::MAX - 1));"]
#[doc = "assert_eq!((i128::MAX - 2).checked_add(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_add(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer addition. Computes `self + rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i128::MAX - 2).strict_add(1), i128::MAX - 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i128::MAX - 2).strict_add(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_add(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Unchecked integer addition. Computes `self + rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_add(y)` is semantically equivalent to calling
/// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_add`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self + rhs > i128::MAX` or `self + rhs < i128::MIN`,"]
/// i.e. when [`checked_add`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_add`]: i128::checked_add"]
#[doc = "[`wrapping_add`]: i128::wrapping_add"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i128, rhs: i128) {
if !!lhs.overflowing_add(rhs).1 {
let msg =
"unsafe precondition(s) violated: i128::unchecked_add cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_add(self, rhs) }
}
/// Checked addition with an unsigned integer. Computes `self + rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i128.checked_add_unsigned(2), Some(3));"]
#[doc = "assert_eq!((i128::MAX - 2).checked_add_unsigned(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add_unsigned(self, rhs: u128) -> Option<Self> {
let (a, b) = self.overflowing_add_unsigned(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict addition with an unsigned integer. Computes `self + rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i128.strict_add_unsigned(2), 3);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i128::MAX - 2).strict_add_unsigned(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add_unsigned(self, rhs: u128) -> Self {
let (a, b) = self.overflowing_add_unsigned(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Checked integer subtraction. Computes `self - rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i128::MIN + 2).checked_sub(1), Some(i128::MIN + 1));"]
#[doc = "assert_eq!((i128::MIN + 2).checked_sub(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_sub(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer subtraction. Computes `self - rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((i128::MIN + 2).strict_sub(1), i128::MIN + 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i128::MIN + 2).strict_sub(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_sub(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
/// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_sub`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self - rhs > i128::MAX` or `self - rhs < i128::MIN`,"]
/// i.e. when [`checked_sub`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_sub`]: i128::checked_sub"]
#[doc = "[`wrapping_sub`]: i128::wrapping_sub"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i128, rhs: i128) {
if !!lhs.overflowing_sub(rhs).1 {
let msg =
"unsafe precondition(s) violated: i128::unchecked_sub cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_sub(self, rhs) }
}
/// Checked subtraction with an unsigned integer. Computes `self - rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i128.checked_sub_unsigned(2), Some(-1));"]
#[doc = "assert_eq!((i128::MIN + 2).checked_sub_unsigned(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub_unsigned(self, rhs: u128) -> Option<Self> {
let (a, b) = self.overflowing_sub_unsigned(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict subtraction with an unsigned integer. Computes `self - rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1i128.strict_sub_unsigned(2), -1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (i128::MIN + 2).strict_sub_unsigned(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub_unsigned(self, rhs: u128) -> Self {
let (a, b) = self.overflowing_sub_unsigned(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Checked integer multiplication. Computes `self * rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i128::MAX.checked_mul(1), Some(i128::MAX));"]
#[doc = "assert_eq!(i128::MAX.checked_mul(2), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer multiplication. Computes `self * rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i128::MAX.strict_mul(1), i128::MAX);"]
/// ```
///
/// The following panics because of overflow:
///
/// ``` should_panic
#[doc = "let _ = i128::MAX.strict_mul(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_mul(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_mul(rhs);
if b { imp::overflow_panic::mul() } else { a }
}
/// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
/// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_mul`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self * rhs > i128::MAX` or `self * rhs < i128::MIN`,"]
/// i.e. when [`checked_mul`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_mul`]: i128::checked_mul"]
#[doc = "[`wrapping_mul`]: i128::wrapping_mul"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: i128, rhs: i128) {
if !!lhs.overflowing_mul(rhs).1 {
let msg =
"unsafe precondition(s) violated: i128::unchecked_mul cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_mul(self, rhs) }
}
/// Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
/// or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc =
"assert_eq!((i128::MIN + 1).checked_div(-1), Some(170141183460469231731687303715884105727));"]
#[doc = "assert_eq!(i128::MIN.checked_div(-1), None);"]
#[doc = "assert_eq!((1i128).checked_div(0), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1)))
{
None
} else { Some(unsafe { intrinsics::unchecked_div(self, rhs) }) }
}
/// Strict integer division. Computes `self / rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is when one divides `MIN / -1` on a signed type (where
/// `MIN` 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.
///
/// # 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 {
let (a, b) = self.overflowing_div(rhs);
if b { imp::overflow_panic::div() } else { a }
}
/// 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` 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.
///
/// # 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 {
let (a, b) = self.overflowing_div_euclid(rhs);
if b { imp::overflow_panic::div() } else { a }
}
/// 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` 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` 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> {
if exp == 0 { return Some(1); }
let mut base = self;
let mut acc: Self = 1;
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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc: Self = 1;
loop {
if (exp & 1) == 1 {
acc = acc.strict_mul(base);
if exp == 1 { return acc; }
}
exp /= 2;
base = base.strict_mul(base);
}
}
/// 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` 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` 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` 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` 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` 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` 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` on a signed type (where `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` 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. The behaviour 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. The behaviour 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` 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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc: Self = 1;
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 { acc = acc.wrapping_mul(base); }
exp /= 2;
base = base.wrapping_mul(base);
}
acc.wrapping_mul(base)
} else {
loop {
if (exp & 1) == 1 {
acc = acc.wrapping_mul(base);
if exp == 1 { return acc; }
}
exp /= 2;
base = base.wrapping_mul(base);
}
}
}
/// 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) {
if exp == 0 { return (1, false); }
let mut base = self;
let mut acc: Self = 1;
let mut overflown = false;
let mut r;
loop {
if (exp & 1) == 1 {
r = acc.overflowing_mul(base);
if exp == 1 { r.1 |= overflown; return r; }
acc = r.0;
overflown |= r.1;
}
exp /= 2;
r = base.overflowing_mul(base);
base = r.0;
overflown |= r.1;
}
}
/// 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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc = 1;
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 { acc = acc * base; }
exp /= 2;
base = base * base;
}
acc * base
} else {
loop {
if (exp & 1) == 1 {
acc = acc * base;
if exp == 1 { return acc; }
}
exp /= 2;
base = base * base;
}
}
}
/// 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` can produce results more efficiently for base 2, and `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.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2i128.checked_ilog2(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog2(self) -> Option<u32> {
if self <= 0 {
None
} else {
let log =
(Self::BITS - 1) -
unsafe { intrinsics::ctlz_nonzero(self) as u32 };
Some(log)
}
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// Returns `None` if the number is negative or zero.
///
/// # Example
///
/// ```
#[doc = "assert_eq!(10i128.checked_ilog10(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog10(self) -> Option<u32> {
imp::int_log10::i128(self as i128)
}
/// Computes the absolute value of `self`.
///
/// # Overflow behavior
///
/// The absolute value of
#[doc = "`i128::MIN`"]
/// cannot be represented as an
#[doc = "`i128`,"]
/// and attempting to calculate it will cause an overflow. This means
/// that code in debug mode will trigger a panic on this case and
/// optimized code will return
#[doc = "`i128::MIN`"]
/// without a panic. If you do not want this behavior, consider
/// using [`unsigned_abs`](Self::unsigned_abs) instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i128.abs(), 10);"]
#[doc = "assert_eq!((-10i128).abs(), 10);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[allow(unused_attributes)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn abs(self) -> Self {
if self.is_negative() { -self } else { self }
}
/// Computes the absolute difference between `self` and `other`.
///
/// This function always returns the correct answer without overflow or
/// panics by returning an unsigned integer.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100i128.abs_diff(80), 20u128);"]
#[doc = "assert_eq!(100i128.abs_diff(110), 10u128);"]
#[doc = "assert_eq!((-100i128).abs_diff(80), 180u128);"]
#[doc = "assert_eq!((-100i128).abs_diff(-120), 20u128);"]
#[doc = "assert_eq!(i128::MIN.abs_diff(i128::MAX), u128::MAX);"]
/// ```
#[stable(feature = "int_abs_diff", since = "1.60.0")]
#[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn abs_diff(self, other: Self) -> u128 {
if self < other {
(other as u128).wrapping_sub(self as u128)
} else { (self as u128).wrapping_sub(other as u128) }
}
/// Returns a number representing sign of `self`.
///
/// - `0` if the number is zero
/// - `1` if the number is positive
/// - `-1` if the number is negative
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10i128.signum(), 1);"]
#[doc = "assert_eq!(0i128.signum(), 0);"]
#[doc = "assert_eq!((-10i128).signum(), -1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_sign", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn signum(self) -> Self {
crate::intrinsics::three_way_compare(self, 0) as Self
}
/// Returns `true` if `self` is positive and `false` if the number is zero or
/// negative.
///
/// # Examples
///
/// ```
#[doc = "assert!(10i128.is_positive());"]
#[doc = "assert!(!(-10i128).is_positive());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[inline(always)]
pub const fn is_positive(self) -> bool { self > 0 }
/// Returns `true` if `self` is negative and `false` if the number is zero or
/// positive.
///
/// # Examples
///
/// ```
#[doc = "assert!((-10i128).is_negative());"]
#[doc = "assert!(!10i128.is_negative());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[inline(always)]
pub const fn is_negative(self) -> bool { self < 0 }
/// Returns the memory representation of this integer as a byte array in
/// big-endian (network) byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12345678901234567890123456789012i128.to_be_bytes();"]
#[doc =
"assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
self.to_be().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// little-endian byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12345678901234567890123456789012i128.to_le_bytes();"]
#[doc =
"assert_eq!(bytes, [0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
self.to_le().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code
/// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
/// instead.
///
#[doc = ""]
///
/// [`to_be_bytes`]: Self::to_be_bytes
/// [`to_le_bytes`]: Self::to_le_bytes
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12345678901234567890123456789012i128.to_ne_bytes();"]
/// assert_eq!(
/// bytes,
/// if cfg!(target_endian = "big") {
#[doc =
" [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]"]
/// } else {
#[doc =
" [0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]"]
/// }
/// );
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
unsafe { mem::transmute(self) }
}
/// Creates an integer value from its representation as a byte array in
/// big endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc =
"let value = i128::from_be_bytes([0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]);"]
#[doc = "assert_eq!(value, 0x12345678901234567890123456789012);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_be_i128(input: &mut &[u8]) -> i128 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i128>());"]
/// *input = rest;
#[doc = " i128::from_be_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_be(Self::from_ne_bytes(bytes))
}
/// Creates an integer value from its representation as a byte array in
/// little endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc =
"let value = i128::from_le_bytes([0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);"]
#[doc = "assert_eq!(value, 0x12345678901234567890123456789012);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_le_i128(input: &mut &[u8]) -> i128 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i128>());"]
/// *input = rest;
#[doc = " i128::from_le_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_le(Self::from_ne_bytes(bytes))
}
/// Creates an integer value from its memory representation as a byte
/// array in native endianness.
///
/// As the target platform's native endianness is used, portable code
/// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
/// appropriate instead.
///
/// [`from_be_bytes`]: Self::from_be_bytes
/// [`from_le_bytes`]: Self::from_le_bytes
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = i128::from_ne_bytes(if cfg!(target_endian = \"big\") {"]
#[doc =
" [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]"]
/// } else {
#[doc =
" [0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]"]
/// });
#[doc = "assert_eq!(value, 0x12345678901234567890123456789012);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_ne_i128(input: &mut &[u8]) -> i128 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<i128>());"]
/// *input = rest;
#[doc = " i128::from_ne_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use]
#[inline]
pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
unsafe { mem::transmute(bytes) }
}
/// New code should prefer to use
#[doc = "[`i128::MIN`] instead."]
///
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MIN` associated constant on this type")]
#[rustc_diagnostic_item = "i128_legacy_fn_min_value"]
pub const fn min_value() -> Self { Self::MIN }
/// New code should prefer to use
#[doc = "[`i128::MAX`] instead."]
///
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MAX` associated constant on this type")]
#[rustc_diagnostic_item = "i128_legacy_fn_max_value"]
pub const fn max_value() -> Self { Self::MAX }
/// Clamps this number to a symmetric range centred around zero.
///
/// The method clamps the number's magnitude (absolute value) to be at most `limit`.
///
/// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
/// explicit about the intent.
///
/// # Examples
///
/// ```
/// #![feature(clamp_magnitude)]
#[doc = "assert_eq!(120i128.clamp_magnitude(100), 100);"]
#[doc = "assert_eq!(-120i128.clamp_magnitude(100), -100);"]
#[doc = "assert_eq!(80i128.clamp_magnitude(100), 80);"]
#[doc = "assert_eq!(-80i128.clamp_magnitude(100), -80);"]
/// ```
#[must_use =
"this returns the clamped value and does not modify the original"]
#[unstable(feature = "clamp_magnitude", issue = "148519")]
#[inline]
pub fn clamp_magnitude(self, limit: u128) -> Self {
if let Ok(limit) = core::convert::TryInto::<i128>::try_into(limit) {
self.clamp(-limit, limit)
} else { self }
}
/// Truncate an integer to an integer of the same size or smaller, preserving the least
/// significant bits.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i8, 120i128.truncate());"]
#[doc = "assert_eq!(-120i8, (-120i128).truncate());"]
/// assert_eq!(120i8, 376i32.truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
/// instead of truncating.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i8, 120i128.saturating_truncate());"]
#[doc = "assert_eq!(-120i8, (-120i128).saturating_truncate());"]
/// assert_eq!(127i8, 376i32.saturating_truncate());
/// assert_eq!(-128i8, (-1000i32).saturating_truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn saturating_truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_saturating_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
/// is outside the bounds of the smaller type.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(Some(120i8), 120i128.checked_truncate());"]
#[doc = "assert_eq!(Some(-120i8), (-120i128).checked_truncate());"]
/// assert_eq!(None, 376i32.checked_truncate::<i8>());
/// assert_eq!(None, (-1000i32).checked_truncate::<i8>());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn checked_truncate<Target>(self) -> Option<Target> where
Self: [const] traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_checked_truncate(self)
}
/// Widen to an integer of the same size or larger, preserving its value.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i128, 120i8.widen());"]
#[doc = "assert_eq!(-120i128, (-120i8).widen());"]
/// ```
#[must_use =
"this returns the widened value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn widen<Target>(self) -> Target where Self: [const]
traits::WidenTarget<Target> {
traits::WidenTarget::internal_widen(self)
}int_impl! {
476Self = i128,
477 ActualT = i128,
478 UnsignedT = u128,
479 BITS = 128,
480 BITS_MINUS_ONE = 127,
481 Min = -170141183460469231731687303715884105728,
482 Max = 170141183460469231731687303715884105727,
483 rot = 16,
484 rot_op = "0x13f40000000000000000000000004f76",
485 rot_result = "0x4f7613f4",
486 swap_op = "0x12345678901234567890123456789012",
487 swapped = "0x12907856341290785634129078563412",
488 reversed = "0x48091e6a2c48091e6a2c48091e6a2c48",
489 le_bytes = "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
490 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
491 be_bytes = "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
492 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
493 to_xe_bytes_doc = "",
494 from_xe_bytes_doc = "",
495 bound_condition = "",
496 }497/// 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 }498}
499500#[doc(auto_cfg = false)]
501#[cfg(target_pointer_width = "16")]
502impl isize {
503int_impl! {
504Self = isize,
505 ActualT = i16,
506 UnsignedT = usize,
507 BITS = 16,
508 BITS_MINUS_ONE = 15,
509 Min = -32768,
510 Max = 32767,
511 rot = 4,
512 rot_op = "-0x5ffd",
513 rot_result = "0x3a",
514 swap_op = "0x1234",
515 swapped = "0x3412",
516 reversed = "0x2c48",
517 le_bytes = "[0x34, 0x12]",
518 be_bytes = "[0x12, 0x34]",
519 to_xe_bytes_doc = usize_isize_to_xe_bytes_doc!(),
520 from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(),
521 bound_condition = " on 16-bit targets",
522 }
523midpoint_impl! { isize, i32, signed }
524}
525526#[doc(auto_cfg = false)]
527#[cfg(target_pointer_width = "32")]
528impl isize {
529int_impl! {
530Self = isize,
531 ActualT = i32,
532 UnsignedT = usize,
533 BITS = 32,
534 BITS_MINUS_ONE = 31,
535 Min = -2147483648,
536 Max = 2147483647,
537 rot = 8,
538 rot_op = "0x10000b3",
539 rot_result = "0xb301",
540 swap_op = "0x12345678",
541 swapped = "0x78563412",
542 reversed = "0x1e6a2c48",
543 le_bytes = "[0x78, 0x56, 0x34, 0x12]",
544 be_bytes = "[0x12, 0x34, 0x56, 0x78]",
545 to_xe_bytes_doc = usize_isize_to_xe_bytes_doc!(),
546 from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(),
547 bound_condition = " on 32-bit targets",
548 }
549midpoint_impl! { isize, i64, signed }
550}
551552#[doc(auto_cfg = false)]
553#[cfg(target_pointer_width = "64")]
554impl isize {
555/// 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 =
"CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"CURRENT_RUSTC_VERSION")]
#[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 =
"CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"CURRENT_RUSTC_VERSION")]
#[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`.
///
/// # 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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since =
"CURRENT_RUSTC_VERSION")]
#[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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since =
"CURRENT_RUSTC_VERSION")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn lowest_one(self) -> Option<u32> { (self as usize).lowest_one() }
/// Returns the bit pattern of `self` reinterpreted as an unsigned integer of the same size.
///
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
/// the same.
///
/// # Examples
///
/// ```
#[doc = "let n = -1isize;"]
///
#[doc = "assert_eq!(n.cast_unsigned(), usize::MAX);"]
/// ```
#[stable(feature = "integer_sign_cast", since = "1.87.0")]
#[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_unsigned(self) -> usize { self as usize }
/// Saturating conversion of `self` to an unsigned integer of the same size.
///
/// Negative values are clamped to `0`.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`checked_cast_unsigned`](Self::checked_cast_unsigned),
/// or [`strict_cast_unsigned`](Self::strict_cast_unsigned).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = isize::MIN;"]
///
#[doc = "assert_eq!(n.saturating_cast_unsigned(), 0usize);"]
#[doc = "assert_eq!(64isize.saturating_cast_unsigned(), 64usize);"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_cast_unsigned(self) -> usize {
if self >= 0 { self.cast_unsigned() } else { 0 }
}
/// Checked conversion of `self` to an unsigned integer of the same size,
/// returning `None` if `self` is negative.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`saturating_cast_unsigned`](Self::saturating_cast_unsigned),
/// or [`strict_cast_unsigned`](Self::strict_cast_unsigned).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = isize::MIN;"]
///
#[doc = "assert_eq!(n.checked_cast_unsigned(), None);"]
#[doc = "assert_eq!(64isize.checked_cast_unsigned(), Some(64usize));"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn checked_cast_unsigned(self) -> Option<usize> {
if self >= 0 { Some(self.cast_unsigned()) } else { None }
}
/// Strict conversion of `self` to an unsigned integer of the same size,
/// which panics if `self` is negative.
///
/// For other kinds of unsigned integer casts, see
/// [`cast_unsigned`](Self::cast_unsigned),
/// [`checked_cast_unsigned`](Self::checked_cast_unsigned),
/// or [`saturating_cast_unsigned`](Self::saturating_cast_unsigned).
///
/// # Examples
///
/// ```should_panic
/// #![feature(integer_cast_extras)]
#[doc = "let _ = isize::MIN.strict_cast_unsigned();"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_cast_unsigned(self) -> usize {
match self.checked_cast_unsigned() {
Some(n) => n,
None => imp::overflow_panic::cast_integer(),
}
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `<<` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0xaa00000000006e1isize;"]
#[doc = "let m = 0x6e10aa;"]
///
#[doc = "assert_eq!(n.rotate_left(12), m);"]
#[doc = "assert_eq!(n.rotate_left(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn rotate_left(self, n: u32) -> Self {
(self as usize).rotate_left(n) as Self
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `>>` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x6e10aaisize;"]
#[doc = "let m = 0xaa00000000006e1;"]
///
#[doc = "assert_eq!(n.rotate_right(12), m);"]
#[doc = "assert_eq!(n.rotate_right(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn rotate_right(self, n: u32) -> Self {
(self as usize).rotate_right(n) as Self
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1234567890123456isize;"]
///
/// let m = n.swap_bytes();
///
#[doc = "assert_eq!(m, 0x5634129078563412);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn swap_bytes(self) -> Self { (self as usize).swap_bytes() as Self }
/// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
/// second least-significant bit becomes second most-significant bit, etc.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1234567890123456isize;"]
/// let m = n.reverse_bits();
///
#[doc = "assert_eq!(m, 0x6a2c48091e6a2c48);"]
#[doc = "assert_eq!(0, 0isize.reverse_bits());"]
/// ```
#[stable(feature = "reverse_bits", since = "1.37.0")]
#[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn reverse_bits(self) -> Self {
(self as usize).reverse_bits() as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are swapped.
///
/// See also [from_be_bytes()](Self::from_be_bytes).
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Aisize;"]
///
/// if cfg!(target_endian = "big") {
#[doc = " assert_eq!(isize::from_be(n), n)"]
/// } else {
#[doc = " assert_eq!(isize::from_be(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn from_be(x: Self) -> Self { x.swap_bytes() }
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are swapped.
///
/// See also [from_le_bytes()](Self::from_le_bytes).
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Aisize;"]
///
/// if cfg!(target_endian = "little") {
#[doc = " assert_eq!(isize::from_le(n), n)"]
/// } else {
#[doc = " assert_eq!(isize::from_le(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use]
#[inline]
pub const fn from_le(x: Self) -> Self { x }
/// Swaps bytes of `self` on little endian targets.
///
/// On big endian this is a no-op.
///
/// The returned value has the same type as `self`, and will be interpreted
/// as (a potentially different) value of a native-endian
#[doc = "`isize`."]
///
/// See [`to_be_bytes()`](Self::to_be_bytes) for a type-safe alternative.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Aisize;"]
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be(self) -> Self { self.swap_bytes() }
/// Swaps bytes of `self` on big endian targets.
///
/// On little endian this is a no-op.
///
/// The returned value has the same type as `self`, and will be interpreted
/// as (a potentially different) value of a native-endian
#[doc = "`isize`."]
///
/// See [`to_le_bytes()`](Self::to_le_bytes) for a type-safe alternative.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Aisize;"]
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_conversions", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le(self) -> Self { self }
/// Checked integer addition. Computes `self + rhs`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((isize::MAX - 2).checked_add(1), Some(isize::MAX - 1));"]
#[doc = "assert_eq!((isize::MAX - 2).checked_add(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_add(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer addition. Computes `self + rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((isize::MAX - 2).strict_add(1), isize::MAX - 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (isize::MAX - 2).strict_add(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_add(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Unchecked integer addition. Computes `self + rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_add(y)` is semantically equivalent to calling
/// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_add`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self + rhs > isize::MAX` or `self + rhs < isize::MIN`,"]
/// i.e. when [`checked_add`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_add`]: isize::checked_add"]
#[doc = "[`wrapping_add`]: isize::wrapping_add"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: isize, rhs: isize) {
if !!lhs.overflowing_add(rhs).1 {
let msg =
"unsafe precondition(s) violated: isize::unchecked_add cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_add(self, rhs) }
}
/// Checked addition with an unsigned integer. Computes `self + rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1isize.checked_add_unsigned(2), Some(3));"]
#[doc = "assert_eq!((isize::MAX - 2).checked_add_unsigned(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add_unsigned(self, rhs: usize) -> Option<Self> {
let (a, b) = self.overflowing_add_unsigned(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict addition with an unsigned integer. Computes `self + rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1isize.strict_add_unsigned(2), 3);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (isize::MAX - 2).strict_add_unsigned(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add_unsigned(self, rhs: usize) -> Self {
let (a, b) = self.overflowing_add_unsigned(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Checked integer subtraction. Computes `self - rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((isize::MIN + 2).checked_sub(1), Some(isize::MIN + 1));"]
#[doc = "assert_eq!((isize::MIN + 2).checked_sub(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_sub(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer subtraction. Computes `self - rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((isize::MIN + 2).strict_sub(1), isize::MIN + 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (isize::MIN + 2).strict_sub(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_sub(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
/// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_sub`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self - rhs > isize::MAX` or `self - rhs < isize::MIN`,"]
/// i.e. when [`checked_sub`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_sub`]: isize::checked_sub"]
#[doc = "[`wrapping_sub`]: isize::wrapping_sub"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: isize, rhs: isize) {
if !!lhs.overflowing_sub(rhs).1 {
let msg =
"unsafe precondition(s) violated: isize::unchecked_sub cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_sub(self, rhs) }
}
/// Checked subtraction with an unsigned integer. Computes `self - rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1isize.checked_sub_unsigned(2), Some(-1));"]
#[doc = "assert_eq!((isize::MIN + 2).checked_sub_unsigned(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub_unsigned(self, rhs: usize) -> Option<Self> {
let (a, b) = self.overflowing_sub_unsigned(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict subtraction with an unsigned integer. Computes `self - rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1isize.strict_sub_unsigned(2), -1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (isize::MIN + 2).strict_sub_unsigned(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub_unsigned(self, rhs: usize) -> Self {
let (a, b) = self.overflowing_sub_unsigned(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Checked integer multiplication. Computes `self * rhs`, returning `None` if
/// overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(isize::MAX.checked_mul(1), Some(isize::MAX));"]
#[doc = "assert_eq!(isize::MAX.checked_mul(2), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer multiplication. Computes `self * rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(isize::MAX.strict_mul(1), isize::MAX);"]
/// ```
///
/// The following panics because of overflow:
///
/// ``` should_panic
#[doc = "let _ = isize::MAX.strict_mul(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_mul(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_mul(rhs);
if b { imp::overflow_panic::mul() } else { a }
}
/// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
/// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_mul`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self * rhs > isize::MAX` or `self * rhs < isize::MIN`,"]
/// i.e. when [`checked_mul`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_mul`]: isize::checked_mul"]
#[doc = "[`wrapping_mul`]: isize::wrapping_mul"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: isize, rhs: isize) {
if !!lhs.overflowing_mul(rhs).1 {
let msg =
"unsafe precondition(s) violated: isize::unchecked_mul cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_mul(self, rhs) }
}
/// Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
/// or the division results in overflow.
///
/// # Examples
///
/// ```
#[doc =
"assert_eq!((isize::MIN + 1).checked_div(-1), Some(9223372036854775807));"]
#[doc = "assert_eq!(isize::MIN.checked_div(-1), None);"]
#[doc = "assert_eq!((1isize).checked_div(0), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0 || ((self == Self::MIN) && (rhs == -1)))
{
None
} else { Some(unsafe { intrinsics::unchecked_div(self, rhs) }) }
}
/// Strict integer division. Computes `self / rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// The only case where such an overflow can occur is when one divides `MIN / -1` on a signed type (where
/// `MIN` 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.
///
/// # 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 {
let (a, b) = self.overflowing_div(rhs);
if b { imp::overflow_panic::div() } else { a }
}
/// 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` 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.
///
/// # 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 {
let (a, b) = self.overflowing_div_euclid(rhs);
if b { imp::overflow_panic::div() } else { a }
}
/// 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` 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` 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> {
if exp == 0 { return Some(1); }
let mut base = self;
let mut acc: Self = 1;
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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc: Self = 1;
loop {
if (exp & 1) == 1 {
acc = acc.strict_mul(base);
if exp == 1 { return acc; }
}
exp /= 2;
base = base.strict_mul(base);
}
}
/// 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` 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` 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` 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` 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` 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` 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` on a signed type (where `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` 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. The behaviour 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. The behaviour 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` 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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc: Self = 1;
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 { acc = acc.wrapping_mul(base); }
exp /= 2;
base = base.wrapping_mul(base);
}
acc.wrapping_mul(base)
} else {
loop {
if (exp & 1) == 1 {
acc = acc.wrapping_mul(base);
if exp == 1 { return acc; }
}
exp /= 2;
base = base.wrapping_mul(base);
}
}
}
/// 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) {
if exp == 0 { return (1, false); }
let mut base = self;
let mut acc: Self = 1;
let mut overflown = false;
let mut r;
loop {
if (exp & 1) == 1 {
r = acc.overflowing_mul(base);
if exp == 1 { r.1 |= overflown; return r; }
acc = r.0;
overflown |= r.1;
}
exp /= 2;
r = base.overflowing_mul(base);
base = r.0;
overflown |= r.1;
}
}
/// 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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc = 1;
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 { acc = acc * base; }
exp /= 2;
base = base * base;
}
acc * base
} else {
loop {
if (exp & 1) == 1 {
acc = acc * base;
if exp == 1 { return acc; }
}
exp /= 2;
base = base * base;
}
}
}
/// 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` can produce results more efficiently for base 2, and `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.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2isize.checked_ilog2(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog2(self) -> Option<u32> {
if self <= 0 {
None
} else {
let log =
(Self::BITS - 1) -
unsafe { intrinsics::ctlz_nonzero(self) as u32 };
Some(log)
}
}
/// Returns the base 10 logarithm of the number, rounded down.
///
/// Returns `None` if the number is negative or zero.
///
/// # Example
///
/// ```
#[doc = "assert_eq!(10isize.checked_ilog10(), Some(1));"]
/// ```
#[stable(feature = "int_log", since = "1.67.0")]
#[rustc_const_stable(feature = "int_log", since = "1.67.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_ilog10(self) -> Option<u32> {
imp::int_log10::i64(self as i64)
}
/// Computes the absolute value of `self`.
///
/// # Overflow behavior
///
/// The absolute value of
#[doc = "`isize::MIN`"]
/// cannot be represented as an
#[doc = "`isize`,"]
/// and attempting to calculate it will cause an overflow. This means
/// that code in debug mode will trigger a panic on this case and
/// optimized code will return
#[doc = "`isize::MIN`"]
/// without a panic. If you do not want this behavior, consider
/// using [`unsigned_abs`](Self::unsigned_abs) instead.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10isize.abs(), 10);"]
#[doc = "assert_eq!((-10isize).abs(), 10);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[allow(unused_attributes)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn abs(self) -> Self {
if self.is_negative() { -self } else { self }
}
/// Computes the absolute difference between `self` and `other`.
///
/// This function always returns the correct answer without overflow or
/// panics by returning an unsigned integer.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100isize.abs_diff(80), 20usize);"]
#[doc = "assert_eq!(100isize.abs_diff(110), 10usize);"]
#[doc = "assert_eq!((-100isize).abs_diff(80), 180usize);"]
#[doc = "assert_eq!((-100isize).abs_diff(-120), 20usize);"]
#[doc = "assert_eq!(isize::MIN.abs_diff(isize::MAX), usize::MAX);"]
/// ```
#[stable(feature = "int_abs_diff", since = "1.60.0")]
#[rustc_const_stable(feature = "int_abs_diff", since = "1.60.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn abs_diff(self, other: Self) -> usize {
if self < other {
(other as usize).wrapping_sub(self as usize)
} else { (self as usize).wrapping_sub(other as usize) }
}
/// Returns a number representing sign of `self`.
///
/// - `0` if the number is zero
/// - `1` if the number is positive
/// - `-1` if the number is negative
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10isize.signum(), 1);"]
#[doc = "assert_eq!(0isize.signum(), 0);"]
#[doc = "assert_eq!((-10isize).signum(), -1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_sign", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn signum(self) -> Self {
crate::intrinsics::three_way_compare(self, 0) as Self
}
/// Returns `true` if `self` is positive and `false` if the number is zero or
/// negative.
///
/// # Examples
///
/// ```
#[doc = "assert!(10isize.is_positive());"]
#[doc = "assert!(!(-10isize).is_positive());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[inline(always)]
pub const fn is_positive(self) -> bool { self > 0 }
/// Returns `true` if `self` is negative and `false` if the number is zero or
/// positive.
///
/// # Examples
///
/// ```
#[doc = "assert!((-10isize).is_negative());"]
#[doc = "assert!(!10isize.is_negative());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_methods", since = "1.32.0")]
#[inline(always)]
pub const fn is_negative(self) -> bool { self < 0 }
/// Returns the memory representation of this integer as a byte array in
/// big-endian (network) byte order.
///
#[doc =
"
**Note**: This function returns an array of length 2, 4 or 8 bytes
depending on the target pointer size.
"]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234567890123456isize.to_be_bytes();"]
#[doc =
"assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
self.to_be().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// little-endian byte order.
///
#[doc =
"
**Note**: This function returns an array of length 2, 4 or 8 bytes
depending on the target pointer size.
"]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234567890123456isize.to_le_bytes();"]
#[doc =
"assert_eq!(bytes, [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
self.to_le().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code
/// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
/// instead.
///
#[doc =
"
**Note**: This function returns an array of length 2, 4 or 8 bytes
depending on the target pointer size.
"]
///
/// [`to_be_bytes`]: Self::to_be_bytes
/// [`to_le_bytes`]: Self::to_le_bytes
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234567890123456isize.to_ne_bytes();"]
/// assert_eq!(
/// bytes,
/// if cfg!(target_endian = "big") {
#[doc = " [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]"]
/// } else {
#[doc = " [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]"]
/// }
/// );
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
unsafe { mem::transmute(self) }
}
/// Creates an integer value from its representation as a byte array in
/// big endian.
///
#[doc =
"
**Note**: This function takes an array of length 2, 4 or 8 bytes
depending on the target pointer size.
"]
///
/// # Examples
///
/// ```
#[doc =
"let value = isize::from_be_bytes([0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]);"]
#[doc = "assert_eq!(value, 0x1234567890123456);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_be_isize(input: &mut &[u8]) -> isize {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<isize>());"]
/// *input = rest;
#[doc = " isize::from_be_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_be(Self::from_ne_bytes(bytes))
}
/// Creates an integer value from its representation as a byte array in
/// little endian.
///
#[doc =
"
**Note**: This function takes an array of length 2, 4 or 8 bytes
depending on the target pointer size.
"]
///
/// # Examples
///
/// ```
#[doc =
"let value = isize::from_le_bytes([0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);"]
#[doc = "assert_eq!(value, 0x1234567890123456);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_le_isize(input: &mut &[u8]) -> isize {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<isize>());"]
/// *input = rest;
#[doc = " isize::from_le_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_le(Self::from_ne_bytes(bytes))
}
/// Creates an integer value from its memory representation as a byte
/// array in native endianness.
///
/// As the target platform's native endianness is used, portable code
/// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
/// appropriate instead.
///
/// [`from_be_bytes`]: Self::from_be_bytes
/// [`from_le_bytes`]: Self::from_le_bytes
///
#[doc =
"
**Note**: This function takes an array of length 2, 4 or 8 bytes
depending on the target pointer size.
"]
///
/// # Examples
///
/// ```
#[doc = "let value = isize::from_ne_bytes(if cfg!(target_endian = \"big\") {"]
#[doc = " [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]"]
/// } else {
#[doc = " [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]"]
/// });
#[doc = "assert_eq!(value, 0x1234567890123456);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_ne_isize(input: &mut &[u8]) -> isize {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<isize>());"]
/// *input = rest;
#[doc = " isize::from_ne_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use]
#[inline]
pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
unsafe { mem::transmute(bytes) }
}
/// New code should prefer to use
#[doc = "[`isize::MIN`] instead."]
///
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_min_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MIN` associated constant on this type")]
#[rustc_diagnostic_item = "isize_legacy_fn_min_value"]
pub const fn min_value() -> Self { Self::MIN }
/// New code should prefer to use
#[doc = "[`isize::MAX`] instead."]
///
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[inline(always)]
#[rustc_promotable]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MAX` associated constant on this type")]
#[rustc_diagnostic_item = "isize_legacy_fn_max_value"]
pub const fn max_value() -> Self { Self::MAX }
/// Clamps this number to a symmetric range centred around zero.
///
/// The method clamps the number's magnitude (absolute value) to be at most `limit`.
///
/// This is functionally equivalent to `self.clamp(-limit, limit)`, but is more
/// explicit about the intent.
///
/// # Examples
///
/// ```
/// #![feature(clamp_magnitude)]
#[doc = "assert_eq!(120isize.clamp_magnitude(100), 100);"]
#[doc = "assert_eq!(-120isize.clamp_magnitude(100), -100);"]
#[doc = "assert_eq!(80isize.clamp_magnitude(100), 80);"]
#[doc = "assert_eq!(-80isize.clamp_magnitude(100), -80);"]
/// ```
#[must_use =
"this returns the clamped value and does not modify the original"]
#[unstable(feature = "clamp_magnitude", issue = "148519")]
#[inline]
pub fn clamp_magnitude(self, limit: usize) -> Self {
if let Ok(limit) = core::convert::TryInto::<isize>::try_into(limit) {
self.clamp(-limit, limit)
} else { self }
}
/// Truncate an integer to an integer of the same size or smaller, preserving the least
/// significant bits.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i8, 120isize.truncate());"]
#[doc = "assert_eq!(-120i8, (-120isize).truncate());"]
/// assert_eq!(120i8, 376i32.truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
/// instead of truncating.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i8, 120isize.saturating_truncate());"]
#[doc = "assert_eq!(-120i8, (-120isize).saturating_truncate());"]
/// assert_eq!(127i8, 376i32.saturating_truncate());
/// assert_eq!(-128i8, (-1000i32).saturating_truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn saturating_truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_saturating_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
/// is outside the bounds of the smaller type.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(Some(120i8), 120isize.checked_truncate());"]
#[doc = "assert_eq!(Some(-120i8), (-120isize).checked_truncate());"]
/// assert_eq!(None, 376i32.checked_truncate::<i8>());
/// assert_eq!(None, (-1000i32).checked_truncate::<i8>());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn checked_truncate<Target>(self) -> Option<Target> where
Self: [const] traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_checked_truncate(self)
}
/// Widen to an integer of the same size or larger, preserving its value.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120i128, 120i8.widen());"]
#[doc = "assert_eq!(-120i128, (-120i8).widen());"]
/// ```
#[must_use =
"this returns the widened value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn widen<Target>(self) -> Target where Self: [const]
traits::WidenTarget<Target> {
traits::WidenTarget::internal_widen(self)
}int_impl! {
556Self = isize,
557 ActualT = i64,
558 UnsignedT = usize,
559 BITS = 64,
560 BITS_MINUS_ONE = 63,
561 Min = -9223372036854775808,
562 Max = 9223372036854775807,
563 rot = 12,
564 rot_op = "0xaa00000000006e1",
565 rot_result = "0x6e10aa",
566 swap_op = "0x1234567890123456",
567 swapped = "0x5634129078563412",
568 reversed = "0x6a2c48091e6a2c48",
569 le_bytes = "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
570 be_bytes = "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
571 to_xe_bytes_doc = usize_isize_to_xe_bytes_doc!(),
572 from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(),
573 bound_condition = " on 64-bit targets",
574 }575/// 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 }576}
577578/// If the bit selected by this mask is set, ascii is lower case.
579const ASCII_CASE_MASK: u8 = 0b0010_0000;
580581impl u8 {
582/// 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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "uint_bit_width", since =
"CURRENT_RUSTC_VERSION")]
#[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 =
"CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"CURRENT_RUSTC_VERSION")]
#[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 =
"CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"CURRENT_RUSTC_VERSION")]
#[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`.
///
/// # 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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since =
"CURRENT_RUSTC_VERSION")]
#[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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since =
"CURRENT_RUSTC_VERSION")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn lowest_one(self) -> Option<u32> {
match NonZero::new(self) {
Some(v) => Some(v.lowest_one()),
None => None,
}
}
/// Returns the bit pattern of `self` reinterpreted as a signed integer of the same size.
///
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
/// the same.
///
/// # Examples
///
/// ```
#[doc = "let n = u8::MAX;"]
///
#[doc = "assert_eq!(n.cast_signed(), -1i8);"]
/// ```
#[stable(feature = "integer_sign_cast", since = "1.87.0")]
#[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_signed(self) -> i8 { self as i8 }
/// Saturating conversion of `self` to a signed integer of the same size.
///
/// The signed integer's maximum value is returned if `self` is larger
/// than the maximum positive value representable by the signed integer.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`checked_cast_signed`](Self::checked_cast_signed),
/// or [`strict_cast_signed`](Self::strict_cast_signed).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = u8::MAX;"]
///
#[doc = "assert_eq!(n.saturating_cast_signed(), i8::MAX);"]
#[doc = "assert_eq!(64u8.saturating_cast_signed(), 64i8);"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_cast_signed(self) -> i8 {
if self <= <i8>::MAX.cast_unsigned() {
self.cast_signed()
} else { <i8>::MAX }
}
/// Checked conversion of `self` to a signed integer of the same size,
/// returning `None` if `self` is larger than the signed integer's
/// maximum value.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`saturating_cast_signed`](Self::saturating_cast_signed),
/// or [`strict_cast_signed`](Self::strict_cast_signed).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = u8::MAX;"]
///
#[doc = "assert_eq!(n.checked_cast_signed(), None);"]
#[doc = "assert_eq!(64u8.checked_cast_signed(), Some(64i8));"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn checked_cast_signed(self) -> Option<i8> {
if self <= <i8>::MAX.cast_unsigned() {
Some(self.cast_signed())
} else { None }
}
/// Strict conversion of `self` to a signed integer of the same size,
/// which panics if `self` is larger than the signed integer's maximum
/// value.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`checked_cast_signed`](Self::checked_cast_signed),
/// or [`saturating_cast_signed`](Self::saturating_cast_signed).
///
/// # Examples
///
/// ```should_panic
/// #![feature(integer_cast_extras)]
#[doc = "let _ = u8::MAX.strict_cast_signed();"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_cast_signed(self) -> i8 {
match self.checked_cast_signed() {
Some(n) => n,
None => imp::overflow_panic::cast_integer(),
}
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `<<` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x82u8;"]
#[doc = "let m = 0xa;"]
///
#[doc = "assert_eq!(n.rotate_left(2), m);"]
#[doc = "assert_eq!(n.rotate_left(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
pub const fn rotate_left(self, n: u32) -> Self {
return intrinsics::rotate_left(self, n);
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `>>` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0xau8;"]
#[doc = "let m = 0x82;"]
///
#[doc = "assert_eq!(n.rotate_right(2), m);"]
#[doc = "assert_eq!(n.rotate_right(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
pub const fn rotate_right(self, n: u32) -> Self {
return intrinsics::rotate_right(self, n);
}
/// Performs a left funnel shift (concatenates `self` with `rhs`, with `self`
/// making up the most significant half, then shifts the combined value left
/// by `n`, and most significant half is extracted to produce the result).
///
/// Please note this isn't the same operation as the `<<` shifting operator or
/// [`rotate_left`](Self::rotate_left), although `a.funnel_shl(a, n)` is *equivalent*
/// to `a.rotate_left(n)`.
///
/// # Panics
///
/// If `n` is greater than or equal to the number of bits in `self`
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(funnel_shifts)]
#[doc = "let a = 0x82u8;"]
#[doc = "let b = 0x36u8;"]
#[doc = "let m = 0x8;"]
///
#[doc = "assert_eq!(a.funnel_shl(b, 2), m);"]
/// ```
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn funnel_shl(self, rhs: Self, n: u32) -> Self {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift left with overflow"));
}
};
unsafe { self.unchecked_funnel_shl(rhs, n) }
}
/// Performs a right funnel shift (concatenates `self` and `rhs`, with `self`
/// making up the most significant half, then shifts the combined value right
/// by `n`, and least significant half is extracted to produce the result).
///
/// Please note this isn't the same operation as the `>>` shifting operator or
/// [`rotate_right`](Self::rotate_right), although `a.funnel_shr(a, n)` is *equivalent*
/// to `a.rotate_right(n)`.
///
/// # Panics
///
/// If `n` is greater than or equal to the number of bits in `self`
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(funnel_shifts)]
#[doc = "let a = 0x82u8;"]
#[doc = "let b = 0x36u8;"]
#[doc = "let m = 0x8d;"]
///
#[doc = "assert_eq!(a.funnel_shr(b, 2), m);"]
/// ```
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn funnel_shr(self, rhs: Self, n: u32) -> Self {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift right with overflow"));
}
};
unsafe { self.unchecked_funnel_shr(rhs, n) }
}
/// Unchecked funnel shift left.
///
/// # Safety
///
/// This results in undefined behavior if `n` is greater than or equal to
#[doc = "`u8::BITS`,"]
/// i.e. when [`funnel_shl`](Self::funnel_shl) would panic.
///
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_funnel_shl(self, low: Self, n: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(n: u32) {
if !(n < <u8>::BITS) {
let msg =
"unsafe precondition(s) violated: u8::unchecked_funnel_shl cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(n); }
};
unsafe { intrinsics::unchecked_funnel_shl(self, low, n) }
}
/// Unchecked funnel shift right.
///
/// # Safety
///
/// This results in undefined behavior if `n` is greater than or equal to
#[doc = "`u8::BITS`,"]
/// i.e. when [`funnel_shr`](Self::funnel_shr) would panic.
///
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_funnel_shr(self, low: Self, n: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(n: u32) {
if !(n < <u8>::BITS) {
let msg =
"unsafe precondition(s) violated: u8::unchecked_funnel_shr cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(n); }
};
unsafe { intrinsics::unchecked_funnel_shr(self, low, n) }
}
/// Performs a carry-less multiplication, returning the lower bits.
///
/// This operation is similar to long multiplication in base 2, except that exclusive or is
/// used instead of addition. The implementation is equivalent to:
///
/// ```no_run
#[doc = "pub fn carryless_mul(lhs: u8, rhs: u8) -> u8{"]
/// let mut retval = 0;
#[doc = " for i in 0..u8::BITS {"]
/// if (rhs >> i) & 1 != 0 {
/// // long multiplication would use +=
/// retval ^= lhs << i;
/// }
/// }
/// retval
/// }
/// ```
///
/// The actual implementation is more efficient, and on some platforms lowers directly to a
/// dedicated instruction.
///
/// # Uses
///
/// Carryless multiplication can be used to turn a bitmask of quote characters into a
/// bit mask of characters surrounded by quotes:
///
/// ```no_run
/// r#"abc xxx "foobar" zzz "a"!"#; // input string
/// 0b0000000010000001000001010; // quote_mask
/// 0b0000000001111110000000100; // quote_mask.carryless_mul(!0) & !quote_mask
/// ```
///
/// Another use is in cryptography, where carryless multiplication allows for efficient
/// implementations of polynomial multiplication in `GF(2)[X]`, the polynomial ring
/// over `GF(2)`.
///
/// # Examples
///
/// ```
/// #![feature(uint_carryless_mul)]
///
#[doc = "let a = 0x12u8;"]
#[doc = "let b = 0x34u8;"]
///
#[doc = "assert_eq!(a.carryless_mul(b), 0x28);"]
/// ```
#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
#[doc(alias = "clmul")]
#[unstable(feature = "uint_carryless_mul", issue = "152080")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn carryless_mul(self, rhs: Self) -> Self {
intrinsics::carryless_mul(self, rhs)
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x12u8;"]
/// let m = n.swap_bytes();
///
#[doc = "assert_eq!(m, 0x12);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn swap_bytes(self) -> Self {
intrinsics::bswap(self as u8) as Self
}
/// Returns an integer with the bit locations specified by `mask` packed
/// contiguously into the least significant bits of the result.
/// ```
/// #![feature(uint_gather_scatter_bits)]
#[doc = "let n: u8 = 0b1011_1100;"]
///
/// assert_eq!(n.extract_bits(0b0010_0100), 0b0000_0011);
/// assert_eq!(n.extract_bits(0xF0), 0b0000_1011);
/// ```
#[doc(alias = "pext")]
#[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn extract_bits(self, mask: Self) -> Self {
imp::int_bits::u8::extract_impl(self as u8, mask as u8) as u8
}
/// Returns an integer with the least significant bits of `self`
/// distributed to the bit locations specified by `mask`.
/// ```
/// #![feature(uint_gather_scatter_bits)]
#[doc = "let n: u8 = 0b1010_1101;"]
///
/// assert_eq!(n.deposit_bits(0b0101_0101), 0b0101_0001);
/// assert_eq!(n.deposit_bits(0xF0), 0b1101_0000);
/// ```
#[doc(alias = "pdep")]
#[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn deposit_bits(self, mask: Self) -> Self {
imp::int_bits::u8::deposit_impl(self as u8, mask as u8) as u8
}
/// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
/// second least-significant bit becomes second most-significant bit, etc.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x12u8;"]
/// let m = n.reverse_bits();
///
#[doc = "assert_eq!(m, 0x48);"]
#[doc = "assert_eq!(0, 0u8.reverse_bits());"]
/// ```
#[stable(feature = "reverse_bits", since = "1.37.0")]
#[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn reverse_bits(self) -> Self {
intrinsics::bitreverse(self as u8) as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au8;"]
///
/// if cfg!(target_endian = "big") {
#[doc = " assert_eq!(u8::from_be(n), n)"]
/// } else {
#[doc = " assert_eq!(u8::from_be(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use]
#[inline(always)]
pub const fn from_be(x: Self) -> Self { x.swap_bytes() }
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au8;"]
///
/// if cfg!(target_endian = "little") {
#[doc = " assert_eq!(u8::from_le(n), n)"]
/// } else {
#[doc = " assert_eq!(u8::from_le(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use]
#[inline(always)]
pub const fn from_le(x: Self) -> Self { x }
/// Converts `self` to big endian from the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au8;"]
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn to_be(self) -> Self { self.swap_bytes() }
/// Converts `self` to little endian from the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au8;"]
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn to_le(self) -> Self { self }
/// Checked integer addition. Computes `self + rhs`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((u8::MAX - 2).checked_add(1), Some(u8::MAX - 1));"]
#[doc = "assert_eq!((u8::MAX - 2).checked_add(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(intrinsics::add_with_overflow(self, rhs).1) {
None
} else { Some(unsafe { intrinsics::unchecked_add(self, rhs) }) }
}
/// Strict integer addition. Computes `self + rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((u8::MAX - 2).strict_add(1), u8::MAX - 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (u8::MAX - 2).strict_add(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_add(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Unchecked integer addition. Computes `self + rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_add(y)` is semantically equivalent to calling
/// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_add`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self + rhs > u8::MAX`,"]
/// i.e. when [`checked_add`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_add`]: u8::checked_add"]
#[doc = "[`wrapping_add`]: u8::wrapping_add"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u8, rhs: u8) {
if !!lhs.overflowing_add(rhs).1 {
let msg =
"unsafe precondition(s) violated: u8::unchecked_add cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_add(self, rhs) }
}
/// Checked addition with a signed integer. Computes `self + rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u8.checked_add_signed(2), Some(3));"]
#[doc = "assert_eq!(1u8.checked_add_signed(-2), None);"]
#[doc = "assert_eq!((u8::MAX - 2).checked_add_signed(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add_signed(self, rhs: i8) -> Option<Self> {
let (a, b) = self.overflowing_add_signed(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict addition with a signed integer. Computes `self + rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u8.strict_add_signed(2), 3);"]
/// ```
///
/// The following panic because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1u8.strict_add_signed(-2);"]
/// ```
///
/// ```should_panic
#[doc = "let _ = (u8::MAX - 2).strict_add_signed(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add_signed(self, rhs: i8) -> Self {
let (a, b) = self.overflowing_add_signed(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Checked integer subtraction. Computes `self - rhs`, returning
/// `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u8.checked_sub(1), Some(0));"]
#[doc = "assert_eq!(0u8.checked_sub(1), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
if self < rhs {
None
} else { Some(unsafe { intrinsics::unchecked_sub(self, rhs) }) }
}
/// Strict integer subtraction. Computes `self - rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u8.strict_sub(1), 0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0u8.strict_sub(1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_sub(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
/// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_sub`].
///
/// If you find yourself writing code like this:
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if foo >= bar {
/// // SAFETY: just checked it will not overflow
/// let diff = unsafe { foo.unchecked_sub(bar) };
/// // ... use diff ...
/// }
/// ```
///
/// Consider changing it to
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if let Some(diff) = foo.checked_sub(bar) {
/// // ... use diff ...
/// }
/// ```
///
/// As that does exactly the same thing -- including telling the optimizer
/// that the subtraction cannot overflow -- but avoids needing `unsafe`.
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self - rhs < u8::MIN`,"]
/// i.e. when [`checked_sub`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_sub`]: u8::checked_sub"]
#[doc = "[`wrapping_sub`]: u8::wrapping_sub"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u8, rhs: u8) {
if !!lhs.overflowing_sub(rhs).1 {
let msg =
"unsafe precondition(s) violated: u8::unchecked_sub cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_sub(self, rhs) }
}
/// Checked subtraction with a signed integer. Computes `self - rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u8.checked_sub_signed(2), None);"]
#[doc = "assert_eq!(1u8.checked_sub_signed(-2), Some(3));"]
#[doc = "assert_eq!((u8::MAX - 2).checked_sub_signed(-4), None);"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub_signed(self, rhs: i8) -> Option<Self> {
let (res, overflow) = self.overflowing_sub_signed(rhs);
if !overflow { Some(res) } else { None }
}
/// Strict subtraction with a signed integer. Computes `self - rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3u8.strict_sub_signed(2), 1);"]
/// ```
///
/// The following panic because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1u8.strict_sub_signed(2);"]
/// ```
///
/// ```should_panic
#[doc = "let _ = (u8::MAX).strict_sub_signed(-1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub_signed(self, rhs: i8) -> Self {
let (a, b) = self.overflowing_sub_signed(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
#[doc =
"Checked integer subtraction. Computes `self - rhs` and checks if the result fits into an [`i8`], returning `None` if overflow occurred."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10u8.checked_signed_diff(2), Some(8));"]
#[doc = "assert_eq!(2u8.checked_signed_diff(10), Some(-8));"]
#[doc = "assert_eq!(u8::MAX.checked_signed_diff(i8::MAX as u8), None);"]
#[doc =
"assert_eq!((i8::MAX as u8).checked_signed_diff(u8::MAX), Some(i8::MIN));"]
#[doc = "assert_eq!((i8::MAX as u8 + 1).checked_signed_diff(0), None);"]
#[doc = "assert_eq!(u8::MAX.checked_signed_diff(u8::MAX), Some(0));"]
/// ```
#[stable(feature = "unsigned_signed_diff", since = "1.91.0")]
#[rustc_const_stable(feature = "unsigned_signed_diff", since = "1.91.0")]
#[inline]
pub const fn checked_signed_diff(self, rhs: Self) -> Option<i8> {
let res = self.wrapping_sub(rhs) as i8;
let overflow = (self >= rhs) == (res < 0);
if !overflow { Some(res) } else { None }
}
/// Checked integer multiplication. Computes `self * rhs`, returning
/// `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u8.checked_mul(1), Some(5));"]
#[doc = "assert_eq!(u8::MAX.checked_mul(2), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer multiplication. Computes `self * rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u8.strict_mul(1), 5);"]
/// ```
///
/// The following panics because of overflow:
///
/// ``` should_panic
#[doc = "let _ = u8::MAX.strict_mul(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_mul(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_mul(rhs);
if b { imp::overflow_panic::mul() } else { a }
}
/// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
/// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_mul`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self * rhs > u8::MAX`,"]
/// i.e. when [`checked_mul`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_mul`]: u8::checked_mul"]
#[doc = "[`wrapping_mul`]: u8::wrapping_mul"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u8, rhs: u8) {
if !!lhs.overflowing_mul(rhs).1 {
let msg =
"unsafe precondition(s) violated: u8::unchecked_mul cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_mul(self, rhs) }
}
/// Checked integer division. Computes `self / rhs`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128u8.checked_div(2), Some(64));"]
#[doc = "assert_eq!(1u8.checked_div(0), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(unsafe { intrinsics::unchecked_div(self, rhs) }) }
}
/// Strict integer division. Computes `self / rhs`.
///
/// Strict division on unsigned types is just normal division. There's no
/// way overflow could ever happen. This function exists so that all
/// operations are accounted for in the strict operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u8.strict_div(10), 10);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1u8).strict_div(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_div(self, rhs: Self) -> Self { self / rhs }
/// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128u8.checked_div_euclid(2), Some(64));"]
#[doc = "assert_eq!(1u8.checked_div_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(self.div_euclid(rhs)) }
}
/// Strict Euclidean division. Computes `self.div_euclid(rhs)`.
///
/// Strict division on unsigned types is just normal division. There's no
/// way overflow could ever happen. This function exists so that all
/// operations are accounted for in the strict operations. Since, for the
/// positive integers, all common definitions of division are equal, this
/// is exactly equal to `self.strict_div(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u8.strict_div_euclid(10), 10);"]
/// ```
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1u8).strict_div_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Checked integer division without remainder. Computes `self / rhs`,
/// returning `None` if `rhs == 0` or if `self % rhs != 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64u8.checked_div_exact(2), Some(32));"]
#[doc = "assert_eq!(64u8.checked_div_exact(32), Some(2));"]
#[doc = "assert_eq!(64u8.checked_div_exact(0), None);"]
#[doc = "assert_eq!(65u8.checked_div_exact(2), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_exact(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else {
unsafe {
if intrinsics::unlikely(intrinsics::unchecked_rem(self, rhs) != 0)
{
None
} else { Some(intrinsics::exact_div(self, rhs)) }
}
}
}
/// Integer division without remainder. Computes `self / rhs`, returning `None` if `self % rhs != 0`.
///
/// # Panics
///
/// This function will panic if `rhs == 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64u8.div_exact(2), Some(32));"]
#[doc = "assert_eq!(64u8.div_exact(32), Some(2));"]
#[doc = "assert_eq!(65u8.div_exact(2), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn div_exact(self, rhs: Self) -> Option<Self> {
if self % rhs != 0 { None } else { Some(self / rhs) }
}
/// Unchecked integer division without remainder. Computes `self / rhs`.
///
/// # Safety
///
/// This results in undefined behavior when `rhs == 0` or `self % rhs != 0`,
/// i.e. when [`checked_div_exact`](Self::checked_div_exact) would return `None`.
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_div_exact(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u8, rhs: u8) {
if !(rhs > 0 && lhs % rhs == 0) {
let msg =
"unsafe precondition(s) violated: u8::unchecked_div_exact divide by zero or leave a remainder\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::exact_div(self, rhs) }
}
/// Checked integer remainder. Computes `self % rhs`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u8.checked_rem(2), Some(1));"]
#[doc = "assert_eq!(5u8.checked_rem(0), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(unsafe { intrinsics::unchecked_rem(self, rhs) }) }
}
/// Strict integer remainder. Computes `self % rhs`.
///
/// Strict remainder calculation on unsigned types is just the regular
/// remainder calculation. There's no way overflow could ever happen.
/// This function exists so that all operations are accounted for in the
/// strict operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u8.strict_rem(10), 0);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5u8.strict_rem(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_rem(self, rhs: Self) -> Self { self % rhs }
/// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u8.checked_rem_euclid(2), Some(1));"]
#[doc = "assert_eq!(5u8.checked_rem_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(self.rem_euclid(rhs)) }
}
/// Strict Euclidean modulo. Computes `self.rem_euclid(rhs)`.
///
/// Strict modulo calculation on unsigned types is just the regular
/// remainder calculation. There's no way overflow could ever happen.
/// This function exists so that all operations are accounted for in the
/// strict operations. Since, for the positive integers, all common
/// definitions of division are equal, this is exactly equal to
/// `self.strict_rem(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u8.strict_rem_euclid(10), 0);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5u8.strict_rem_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Same value as `self | other`, but UB if any bit position is set in both inputs.
///
/// This is a situational micro-optimization for places where you'd rather
/// use addition on some platforms and bitwise or on other platforms, based
/// on exactly which instructions combine better with whatever else you're
/// doing. Note that there's no reason to bother using this for places
/// where it's clear from the operations involved that they can't overlap.
/// For example, if you're combining `u16`s into a `u32` with
/// `((a as u32) << 16) | (b as u32)`, that's fine, as the backend will
/// know those sides of the `|` are disjoint without needing help.
///
/// # Examples
///
/// ```
/// #![feature(disjoint_bitor)]
///
/// // SAFETY: `1` and `4` have no bits in common.
/// unsafe {
#[doc = " assert_eq!(1_u8.unchecked_disjoint_bitor(4), 5);"]
/// }
/// ```
///
/// # Safety
///
/// Requires that `(self & other) == 0`, otherwise it's immediate UB.
///
/// Equivalently, requires that `(self | other) == (self + other)`.
#[unstable(feature = "disjoint_bitor", issue = "135758")]
#[rustc_const_unstable(feature = "disjoint_bitor", issue = "135758")]
#[inline]
pub const unsafe fn unchecked_disjoint_bitor(self, other: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u8, rhs: u8) {
if !((lhs & rhs) == 0) {
let msg =
"unsafe precondition(s) violated: u8::unchecked_disjoint_bitor cannot have overlapping bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, other);
}
};
unsafe { intrinsics::disjoint_bitor(self, other) }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// This method might not be optimized owing to implementation details;
/// `ilog2` can produce results more efficiently for base 2, and `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));"]
/// ```
#[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 == 2 {
return self.checked_ilog2();
} else 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.
///
/// # 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> {
if exp == 0 { return Some(1); }
let mut base = self;
let mut acc: Self = 1;
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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc: Self = 1;
loop {
if (exp & 1) == 1 {
acc = acc.strict_mul(base);
if exp == 1 { return acc; }
}
exp /= 2;
base = base.strict_mul(base);
}
}
/// 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. The behaviour 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. The behaviour 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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc: Self = 1;
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 { acc = acc.wrapping_mul(base); }
exp /= 2;
base = base.wrapping_mul(base);
}
acc.wrapping_mul(base)
} else {
loop {
if (exp & 1) == 1 {
acc = acc.wrapping_mul(base);
if exp == 1 { return acc; }
}
exp /= 2;
base = base.wrapping_mul(base);
}
}
}
/// 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) {
if exp == 0 { return (1, false); }
let mut base = self;
let mut acc: Self = 1;
let mut overflown = false;
let mut r;
loop {
if (exp & 1) == 1 {
r = acc.overflowing_mul(base);
if exp == 1 { r.1 |= overflown; return r; }
acc = r.0;
overflown |= r.1;
}
exp /= 2;
r = base.overflowing_mul(base);
base = r.0;
overflown |= r.1;
}
}
/// 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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc = 1;
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 { acc = acc * base; }
exp /= 2;
base = base * base;
}
acc * base
} else {
loop {
if (exp & 1) == 1 {
acc = acc * base;
if exp == 1 { return acc; }
}
exp /= 2;
base = base * base;
}
}
}
/// Returns the square root of the number, rounded down.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10u8.isqrt(), 3);"]
/// ```
#[stable(feature = "isqrt", since = "1.84.0")]
#[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn isqrt(self) -> Self {
let result = imp::int_sqrt::u8(self as u8) as Self;
unsafe {
const MAX_RESULT: u8 = imp::int_sqrt::u8(<u8>::MAX) as u8;
crate::hint::assert_unchecked(result <= MAX_RESULT)
}
if self >= 1 { unsafe { crate::hint::assert_unchecked(result >= 1) } }
unsafe {
crate::hint::assert_unchecked(result.unchecked_mul(result) <= self);
crate::hint::assert_unchecked(result <= self);
}
result
}
/// Performs Euclidean division.
///
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self / rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7u8.div_euclid(4), 1); // or any other integer type"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Calculates the least remainder of `self` when divided by
/// `rhs`.
///
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self % rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7u8.rem_euclid(4), 3); // or any other integer type"]
/// ```
#[doc(alias = "modulo", alias = "mod")]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
///
/// This is the same as performing `self / rhs` for all unsigned integers.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "assert_eq!(7_u8.div_floor(4), 1);"]
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn div_floor(self, rhs: Self) -> Self { self / rhs }
/// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7_u8.div_ceil(4), 2);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_ceil(self, rhs: Self) -> Self {
let d = self / rhs;
let r = self % rhs;
if r > 0 { d + 1 } else { d }
}
/// Calculates the smallest value greater than or equal to `self` that
/// is a multiple of `rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// On overflow, this function will panic if overflow checks are enabled (default in debug
/// mode) and wrap if overflow checks are disabled (default in release mode).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(16_u8.next_multiple_of(8), 16);"]
#[doc = "assert_eq!(23_u8.next_multiple_of(8), 24);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_multiple_of(self, rhs: Self) -> Self {
match self % rhs { 0 => self, r => self + (rhs - r), }
}
/// Calculates the smallest value greater than or equal to `self` that
/// is a multiple of `rhs`. Returns `None` if `rhs` is zero or the
/// operation would result in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(16_u8.checked_next_multiple_of(8), Some(16));"]
#[doc = "assert_eq!(23_u8.checked_next_multiple_of(8), Some(24));"]
#[doc = "assert_eq!(1_u8.checked_next_multiple_of(0), None);"]
#[doc = "assert_eq!(u8::MAX.checked_next_multiple_of(2), None);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
match match self.checked_rem(rhs) { Some(x) => x, None => return None, } {
0 => Some(self),
r => self.checked_add(rhs - r),
}
}
/// Returns `true` if `self` is an integer multiple of `rhs`, and false otherwise.
///
/// This function is equivalent to `self % rhs == 0`, except that it will not panic
/// for `rhs == 0`. Instead, `0.is_multiple_of(0) == true`, and for any non-zero `n`,
/// `n.is_multiple_of(0) == false`.
///
/// # Examples
///
/// ```
#[doc = "assert!(6_u8.is_multiple_of(2));"]
#[doc = "assert!(!5_u8.is_multiple_of(2));"]
///
#[doc = "assert!(0_u8.is_multiple_of(0));"]
#[doc = "assert!(!6_u8.is_multiple_of(0));"]
/// ```
#[stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
#[rustc_const_stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
#[must_use]
#[inline]
pub const fn is_multiple_of(self, rhs: Self) -> bool {
match rhs { 0 => self == 0, _ => self % rhs == 0, }
}
/// Returns `true` if and only if `self == 2^k` for some unsigned integer `k`.
///
/// # Examples
///
/// ```
#[doc = "assert!(16u8.is_power_of_two());"]
#[doc = "assert!(!10u8.is_power_of_two());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
#[inline(always)]
pub const fn is_power_of_two(self) -> bool { self.count_ones() == 1 }
#[inline]
const fn one_less_than_next_power_of_two(self) -> Self {
if self <= 1 { return 0; }
let p = self - 1;
let z = unsafe { intrinsics::ctlz_nonzero(p) };
<u8>::MAX >> z
}
/// Returns the smallest power of two greater than or equal to `self`.
///
/// When return value overflows (i.e., `self > (1 << (N-1))` for type
/// `uN`), it panics in debug mode and the return value is wrapped to 0 in
/// release mode (the only situation in which this method can return 0).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u8.next_power_of_two(), 2);"]
#[doc = "assert_eq!(3u8.next_power_of_two(), 4);"]
#[doc = "assert_eq!(0u8.next_power_of_two(), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_power_of_two(self) -> Self {
self.one_less_than_next_power_of_two() + 1
}
/// Returns the smallest power of two greater than or equal to `self`. If
/// the next power of two is greater than the type's maximum value,
/// `None` is returned, otherwise the power of two is wrapped in `Some`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u8.checked_next_power_of_two(), Some(2));"]
#[doc = "assert_eq!(3u8.checked_next_power_of_two(), Some(4));"]
#[doc = "assert_eq!(u8::MAX.checked_next_power_of_two(), None);"]
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn checked_next_power_of_two(self) -> Option<Self> {
self.one_less_than_next_power_of_two().checked_add(1)
}
/// Returns the smallest power of two greater than or equal to `n`. If
/// the next power of two is greater than the type's maximum value,
/// the return value is wrapped to `0`.
///
/// # Examples
///
/// ```
/// #![feature(wrapping_next_power_of_two)]
///
#[doc = "assert_eq!(2u8.wrapping_next_power_of_two(), 2);"]
#[doc = "assert_eq!(3u8.wrapping_next_power_of_two(), 4);"]
#[doc = "assert_eq!(u8::MAX.wrapping_next_power_of_two(), 0);"]
/// ```
#[inline]
#[unstable(feature = "wrapping_next_power_of_two", issue = "32463", reason =
"needs decision on wrapping behavior")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn wrapping_next_power_of_two(self) -> Self {
self.one_less_than_next_power_of_two().wrapping_add(1)
}
/// Returns the memory representation of this integer as a byte array in
/// big-endian (network) byte order.
///
#[doc =
"
**Note**: This function is meaningless on `u8`. Byte order does not exist as a
concept for byte-sized integers. This function is only provided in symmetry
with larger integer types.
"]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12u8.to_be_bytes();"]
#[doc = "assert_eq!(bytes, [0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
self.to_be().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// little-endian byte order.
///
#[doc =
"
**Note**: This function is meaningless on `u8`. Byte order does not exist as a
concept for byte-sized integers. This function is only provided in symmetry
with larger integer types.
"]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12u8.to_le_bytes();"]
#[doc = "assert_eq!(bytes, [0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
self.to_le().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code
/// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
/// instead.
///
#[doc =
"
**Note**: This function is meaningless on `u8`. Byte order does not exist as a
concept for byte-sized integers. This function is only provided in symmetry
with larger integer types.
"]
///
/// [`to_be_bytes`]: Self::to_be_bytes
/// [`to_le_bytes`]: Self::to_le_bytes
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12u8.to_ne_bytes();"]
/// assert_eq!(
/// bytes,
/// if cfg!(target_endian = "big") {
#[doc = " [0x12]"]
/// } else {
#[doc = " [0x12]"]
/// }
/// );
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[allow(unnecessary_transmutes)]
#[inline]
pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
unsafe { mem::transmute(self) }
}
/// Creates a native endian integer value from its representation
/// as a byte array in big endian.
///
#[doc =
"
**Note**: This function is meaningless on `u8`. Byte order does not exist as a
concept for byte-sized integers. This function is only provided in symmetry
with larger integer types.
"]
///
/// # Examples
///
/// ```
#[doc = "let value = u8::from_be_bytes([0x12]);"]
#[doc = "assert_eq!(value, 0x12);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_be_u8(input: &mut &[u8]) -> u8 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u8>());"]
/// *input = rest;
#[doc = " u8::from_be_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_be(Self::from_ne_bytes(bytes))
}
/// Creates a native endian integer value from its representation
/// as a byte array in little endian.
///
#[doc =
"
**Note**: This function is meaningless on `u8`. Byte order does not exist as a
concept for byte-sized integers. This function is only provided in symmetry
with larger integer types.
"]
///
/// # Examples
///
/// ```
#[doc = "let value = u8::from_le_bytes([0x12]);"]
#[doc = "assert_eq!(value, 0x12);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_le_u8(input: &mut &[u8]) -> u8 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u8>());"]
/// *input = rest;
#[doc = " u8::from_le_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_le(Self::from_ne_bytes(bytes))
}
/// Creates a native endian integer value from its memory representation
/// as a byte array in native endianness.
///
/// As the target platform's native endianness is used, portable code
/// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
/// appropriate instead.
///
/// [`from_be_bytes`]: Self::from_be_bytes
/// [`from_le_bytes`]: Self::from_le_bytes
///
#[doc =
"
**Note**: This function is meaningless on `u8`. Byte order does not exist as a
concept for byte-sized integers. This function is only provided in symmetry
with larger integer types.
"]
///
/// # Examples
///
/// ```
#[doc = "let value = u8::from_ne_bytes(if cfg!(target_endian = \"big\") {"]
#[doc = " [0x12]"]
/// } else {
#[doc = " [0x12]"]
/// });
#[doc = "assert_eq!(value, 0x12);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_ne_u8(input: &mut &[u8]) -> u8 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u8>());"]
/// *input = rest;
#[doc = " u8::from_ne_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use]
#[inline]
pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
unsafe { mem::transmute(bytes) }
}
/// New code should prefer to use
#[doc = "[`u8::MIN`] instead."]
///
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_promotable]
#[inline(always)]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MIN` associated constant on this type")]
#[rustc_diagnostic_item = "u8_legacy_fn_min_value"]
pub const fn min_value() -> Self { Self::MIN }
/// New code should prefer to use
#[doc = "[`u8::MAX`] instead."]
///
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_promotable]
#[inline(always)]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MAX` associated constant on this type")]
#[rustc_diagnostic_item = "u8_legacy_fn_max_value"]
pub const fn max_value() -> Self { Self::MAX }
/// Truncate an integer to an integer of the same size or smaller, preserving the least
/// significant bits.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u8, 120u8.truncate());"]
/// assert_eq!(120u8, 376u32.truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
/// instead of truncating.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u8, 120u8.saturating_truncate());"]
/// assert_eq!(255u8, 376u32.saturating_truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn saturating_truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_saturating_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
/// is outside the bounds of the smaller type.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(Some(120u8), 120u8.checked_truncate());"]
/// assert_eq!(None, 376u32.checked_truncate::<u8>());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn checked_truncate<Target>(self) -> Option<Target> where
Self: [const] traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_checked_truncate(self)
}
/// Widen to an integer of the same size or larger, preserving its value.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u128, 120u8.widen());"]
/// ```
#[must_use =
"this returns the widened value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn widen<Target>(self) -> Target where Self: [const]
traits::WidenTarget<Target> {
traits::WidenTarget::internal_widen(self)
}uint_impl! {
583Self = u8,
584 ActualT = u8,
585 SignedT = i8,
586 BITS = 8,
587 BITS_MINUS_ONE = 7,
588 MAX = 255,
589 rot = 2,
590 rot_op = "0x82",
591 rot_result = "0xa",
592 fsh_op = "0x36",
593 fshl_result = "0x8",
594 fshr_result = "0x8d",
595 clmul_lhs = "0x12",
596 clmul_rhs = "0x34",
597 clmul_result = "0x28",
598 swap_op = "0x12",
599 swapped = "0x12",
600 reversed = "0x48",
601 le_bytes = "[0x12]",
602 be_bytes = "[0x12]",
603 to_xe_bytes_doc = u8_xe_bytes_doc!(),
604 from_xe_bytes_doc = u8_xe_bytes_doc!(),
605 bound_condition = "",
606 }607/// 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 }608/// 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 }609/// 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 }610/// 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 }611612/// Checks if the value is within the ASCII range.
613 ///
614 /// # Examples
615 ///
616 /// ```
617 /// let ascii = 97u8;
618 /// let non_ascii = 150u8;
619 ///
620 /// assert!(ascii.is_ascii());
621 /// assert!(!non_ascii.is_ascii());
622 /// ```
623#[must_use]
624 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
625 #[rustc_const_stable(feature = "const_u8_is_ascii", since = "1.43.0")]
626 #[inline]
627pub const fn is_ascii(&self) -> bool {
628*self <= 127
629}
630631/// If the value of this byte is within the ASCII range, returns it as an
632 /// [ASCII character](ascii::Char). Otherwise, returns `None`.
633#[must_use]
634 #[unstable(feature = "ascii_char", issue = "110998")]
635 #[inline]
636pub const fn as_ascii(&self) -> Option<ascii::Char> {
637 ascii::Char::from_u8(*self)
638 }
639640/// Converts this byte to an [ASCII character](ascii::Char), without
641 /// checking whether or not it's valid.
642 ///
643 /// # Safety
644 ///
645 /// This byte must be valid ASCII, or else this is UB.
646#[must_use]
647 #[unstable(feature = "ascii_char", issue = "110998")]
648 #[inline]
649pub const unsafe fn as_ascii_unchecked(&self) -> ascii::Char {
650{
#[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!(
651 check_library_ub,
652"as_ascii_unchecked requires that the byte is valid ASCII",
653 (it: &u8 = self) => it.is_ascii()
654 );
655656// SAFETY: the caller promised that this byte is ASCII.
657unsafe { ascii::Char::from_u8_unchecked(*self) }
658 }
659660/// Makes a copy of the value in its ASCII upper case equivalent.
661 ///
662 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
663 /// but non-ASCII letters are unchanged.
664 ///
665 /// To uppercase the value in-place, use [`make_ascii_uppercase`].
666 ///
667 /// # Examples
668 ///
669 /// ```
670 /// let lowercase_a = 97u8;
671 ///
672 /// assert_eq!(65, lowercase_a.to_ascii_uppercase());
673 /// ```
674 ///
675 /// [`make_ascii_uppercase`]: Self::make_ascii_uppercase
676#[must_use = "to uppercase the value in-place, use `make_ascii_uppercase()`"]
677 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
678 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
679 #[inline]
680pub const fn to_ascii_uppercase(&self) -> u8 {
681// Toggle the 6th bit if this is a lowercase letter
682*self ^ ((self.is_ascii_lowercase() as u8) * ASCII_CASE_MASK)
683 }
684685/// Makes a copy of the value in its ASCII lower case equivalent.
686 ///
687 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
688 /// but non-ASCII letters are unchanged.
689 ///
690 /// To lowercase the value in-place, use [`make_ascii_lowercase`].
691 ///
692 /// # Examples
693 ///
694 /// ```
695 /// let uppercase_a = 65u8;
696 ///
697 /// assert_eq!(97, uppercase_a.to_ascii_lowercase());
698 /// ```
699 ///
700 /// [`make_ascii_lowercase`]: Self::make_ascii_lowercase
701#[must_use = "to lowercase the value in-place, use `make_ascii_lowercase()`"]
702 #[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
703 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
704 #[inline]
705pub const fn to_ascii_lowercase(&self) -> u8 {
706// Set the 6th bit if this is an uppercase letter
707*self | (self.is_ascii_uppercase() as u8 * ASCII_CASE_MASK)
708 }
709710/// Assumes self is ascii
711#[inline]
712pub(crate) const fn ascii_change_case_unchecked(&self) -> u8 {
713*self ^ ASCII_CASE_MASK714 }
715716/// Checks that two values are an ASCII case-insensitive match.
717 ///
718 /// This is equivalent to `to_ascii_lowercase(a) == to_ascii_lowercase(b)`.
719 ///
720 /// # Examples
721 ///
722 /// ```
723 /// let lowercase_a = 97u8;
724 /// let uppercase_a = 65u8;
725 ///
726 /// assert!(lowercase_a.eq_ignore_ascii_case(&uppercase_a));
727 /// ```
728#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
729 #[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
730 #[inline]
731pub const fn eq_ignore_ascii_case(&self, other: &u8) -> bool {
732self.to_ascii_lowercase() == other.to_ascii_lowercase()
733 }
734735/// Converts this value to its ASCII upper case equivalent in-place.
736 ///
737 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z',
738 /// but non-ASCII letters are unchanged.
739 ///
740 /// To return a new uppercased value without modifying the existing one, use
741 /// [`to_ascii_uppercase`].
742 ///
743 /// # Examples
744 ///
745 /// ```
746 /// let mut byte = b'a';
747 ///
748 /// byte.make_ascii_uppercase();
749 ///
750 /// assert_eq!(b'A', byte);
751 /// ```
752 ///
753 /// [`to_ascii_uppercase`]: Self::to_ascii_uppercase
754#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
755 #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
756 #[inline]
757pub const fn make_ascii_uppercase(&mut self) {
758*self = self.to_ascii_uppercase();
759 }
760761/// Converts this value to its ASCII lower case equivalent in-place.
762 ///
763 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z',
764 /// but non-ASCII letters are unchanged.
765 ///
766 /// To return a new lowercased value without modifying the existing one, use
767 /// [`to_ascii_lowercase`].
768 ///
769 /// # Examples
770 ///
771 /// ```
772 /// let mut byte = b'A';
773 ///
774 /// byte.make_ascii_lowercase();
775 ///
776 /// assert_eq!(b'a', byte);
777 /// ```
778 ///
779 /// [`to_ascii_lowercase`]: Self::to_ascii_lowercase
780#[stable(feature = "ascii_methods_on_intrinsics", since = "1.23.0")]
781 #[rustc_const_stable(feature = "const_make_ascii", since = "1.84.0")]
782 #[inline]
783pub const fn make_ascii_lowercase(&mut self) {
784*self = self.to_ascii_lowercase();
785 }
786787/// Checks if the value is an ASCII alphabetic character:
788 ///
789 /// - U+0041 'A' ..= U+005A 'Z', or
790 /// - U+0061 'a' ..= U+007A 'z'.
791 ///
792 /// # Examples
793 ///
794 /// ```
795 /// let uppercase_a = b'A';
796 /// let uppercase_g = b'G';
797 /// let a = b'a';
798 /// let g = b'g';
799 /// let zero = b'0';
800 /// let percent = b'%';
801 /// let space = b' ';
802 /// let lf = b'\n';
803 /// let esc = b'\x1b';
804 ///
805 /// assert!(uppercase_a.is_ascii_alphabetic());
806 /// assert!(uppercase_g.is_ascii_alphabetic());
807 /// assert!(a.is_ascii_alphabetic());
808 /// assert!(g.is_ascii_alphabetic());
809 /// assert!(!zero.is_ascii_alphabetic());
810 /// assert!(!percent.is_ascii_alphabetic());
811 /// assert!(!space.is_ascii_alphabetic());
812 /// assert!(!lf.is_ascii_alphabetic());
813 /// assert!(!esc.is_ascii_alphabetic());
814 /// ```
815#[must_use]
816 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
817 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
818 #[inline]
819pub const fn is_ascii_alphabetic(&self) -> bool {
820#[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')821 }
822823/// Checks if the value is an ASCII uppercase character:
824 /// U+0041 'A' ..= U+005A 'Z'.
825 ///
826 /// # Examples
827 ///
828 /// ```
829 /// let uppercase_a = b'A';
830 /// let uppercase_g = b'G';
831 /// let a = b'a';
832 /// let g = b'g';
833 /// let zero = b'0';
834 /// let percent = b'%';
835 /// let space = b' ';
836 /// let lf = b'\n';
837 /// let esc = b'\x1b';
838 ///
839 /// assert!(uppercase_a.is_ascii_uppercase());
840 /// assert!(uppercase_g.is_ascii_uppercase());
841 /// assert!(!a.is_ascii_uppercase());
842 /// assert!(!g.is_ascii_uppercase());
843 /// assert!(!zero.is_ascii_uppercase());
844 /// assert!(!percent.is_ascii_uppercase());
845 /// assert!(!space.is_ascii_uppercase());
846 /// assert!(!lf.is_ascii_uppercase());
847 /// assert!(!esc.is_ascii_uppercase());
848 /// ```
849#[must_use]
850 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
851 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
852 #[inline]
853pub const fn is_ascii_uppercase(&self) -> bool {
854#[allow(non_exhaustive_omitted_patterns)] match *self {
b'A'..=b'Z' => true,
_ => false,
}matches!(*self, b'A'..=b'Z')855 }
856857/// Checks if the value is an ASCII lowercase character:
858 /// U+0061 'a' ..= U+007A 'z'.
859 ///
860 /// # Examples
861 ///
862 /// ```
863 /// let uppercase_a = b'A';
864 /// let uppercase_g = b'G';
865 /// let a = b'a';
866 /// let g = b'g';
867 /// let zero = b'0';
868 /// let percent = b'%';
869 /// let space = b' ';
870 /// let lf = b'\n';
871 /// let esc = b'\x1b';
872 ///
873 /// assert!(!uppercase_a.is_ascii_lowercase());
874 /// assert!(!uppercase_g.is_ascii_lowercase());
875 /// assert!(a.is_ascii_lowercase());
876 /// assert!(g.is_ascii_lowercase());
877 /// assert!(!zero.is_ascii_lowercase());
878 /// assert!(!percent.is_ascii_lowercase());
879 /// assert!(!space.is_ascii_lowercase());
880 /// assert!(!lf.is_ascii_lowercase());
881 /// assert!(!esc.is_ascii_lowercase());
882 /// ```
883#[must_use]
884 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
885 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
886 #[inline]
887pub const fn is_ascii_lowercase(&self) -> bool {
888#[allow(non_exhaustive_omitted_patterns)] match *self {
b'a'..=b'z' => true,
_ => false,
}matches!(*self, b'a'..=b'z')889 }
890891/// Checks if the value is an ASCII alphanumeric character:
892 ///
893 /// - U+0041 'A' ..= U+005A 'Z', or
894 /// - U+0061 'a' ..= U+007A 'z', or
895 /// - U+0030 '0' ..= U+0039 '9'.
896 ///
897 /// # Examples
898 ///
899 /// ```
900 /// let uppercase_a = b'A';
901 /// let uppercase_g = b'G';
902 /// let a = b'a';
903 /// let g = b'g';
904 /// let zero = b'0';
905 /// let percent = b'%';
906 /// let space = b' ';
907 /// let lf = b'\n';
908 /// let esc = b'\x1b';
909 ///
910 /// assert!(uppercase_a.is_ascii_alphanumeric());
911 /// assert!(uppercase_g.is_ascii_alphanumeric());
912 /// assert!(a.is_ascii_alphanumeric());
913 /// assert!(g.is_ascii_alphanumeric());
914 /// assert!(zero.is_ascii_alphanumeric());
915 /// assert!(!percent.is_ascii_alphanumeric());
916 /// assert!(!space.is_ascii_alphanumeric());
917 /// assert!(!lf.is_ascii_alphanumeric());
918 /// assert!(!esc.is_ascii_alphanumeric());
919 /// ```
920#[must_use]
921 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
922 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
923 #[inline]
924pub const fn is_ascii_alphanumeric(&self) -> bool {
925#[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')926 }
927928/// Checks if the value is an ASCII decimal digit:
929 /// U+0030 '0' ..= U+0039 '9'.
930 ///
931 /// # Examples
932 ///
933 /// ```
934 /// let uppercase_a = b'A';
935 /// let uppercase_g = b'G';
936 /// let a = b'a';
937 /// let g = b'g';
938 /// let zero = b'0';
939 /// let percent = b'%';
940 /// let space = b' ';
941 /// let lf = b'\n';
942 /// let esc = b'\x1b';
943 ///
944 /// assert!(!uppercase_a.is_ascii_digit());
945 /// assert!(!uppercase_g.is_ascii_digit());
946 /// assert!(!a.is_ascii_digit());
947 /// assert!(!g.is_ascii_digit());
948 /// assert!(zero.is_ascii_digit());
949 /// assert!(!percent.is_ascii_digit());
950 /// assert!(!space.is_ascii_digit());
951 /// assert!(!lf.is_ascii_digit());
952 /// assert!(!esc.is_ascii_digit());
953 /// ```
954#[must_use]
955 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
956 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
957 #[inline]
958pub const fn is_ascii_digit(&self) -> bool {
959#[allow(non_exhaustive_omitted_patterns)] match *self {
b'0'..=b'9' => true,
_ => false,
}matches!(*self, b'0'..=b'9')960 }
961962/// Checks if the value is an ASCII octal digit:
963 /// U+0030 '0' ..= U+0037 '7'.
964 ///
965 /// # Examples
966 ///
967 /// ```
968 /// #![feature(is_ascii_octdigit)]
969 ///
970 /// let uppercase_a = b'A';
971 /// let a = b'a';
972 /// let zero = b'0';
973 /// let seven = b'7';
974 /// let nine = b'9';
975 /// let percent = b'%';
976 /// let lf = b'\n';
977 ///
978 /// assert!(!uppercase_a.is_ascii_octdigit());
979 /// assert!(!a.is_ascii_octdigit());
980 /// assert!(zero.is_ascii_octdigit());
981 /// assert!(seven.is_ascii_octdigit());
982 /// assert!(!nine.is_ascii_octdigit());
983 /// assert!(!percent.is_ascii_octdigit());
984 /// assert!(!lf.is_ascii_octdigit());
985 /// ```
986#[must_use]
987 #[unstable(feature = "is_ascii_octdigit", issue = "101288")]
988 #[inline]
989pub const fn is_ascii_octdigit(&self) -> bool {
990#[allow(non_exhaustive_omitted_patterns)] match *self {
b'0'..=b'7' => true,
_ => false,
}matches!(*self, b'0'..=b'7')991 }
992993/// Checks if the value is an ASCII hexadecimal digit:
994 ///
995 /// - U+0030 '0' ..= U+0039 '9', or
996 /// - U+0041 'A' ..= U+0046 'F', or
997 /// - U+0061 'a' ..= U+0066 'f'.
998 ///
999 /// # Examples
1000 ///
1001 /// ```
1002 /// let uppercase_a = b'A';
1003 /// let uppercase_g = b'G';
1004 /// let a = b'a';
1005 /// let g = b'g';
1006 /// let zero = b'0';
1007 /// let percent = b'%';
1008 /// let space = b' ';
1009 /// let lf = b'\n';
1010 /// let esc = b'\x1b';
1011 ///
1012 /// assert!(uppercase_a.is_ascii_hexdigit());
1013 /// assert!(!uppercase_g.is_ascii_hexdigit());
1014 /// assert!(a.is_ascii_hexdigit());
1015 /// assert!(!g.is_ascii_hexdigit());
1016 /// assert!(zero.is_ascii_hexdigit());
1017 /// assert!(!percent.is_ascii_hexdigit());
1018 /// assert!(!space.is_ascii_hexdigit());
1019 /// assert!(!lf.is_ascii_hexdigit());
1020 /// assert!(!esc.is_ascii_hexdigit());
1021 /// ```
1022#[must_use]
1023 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1024 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1025 #[inline]
1026pub const fn is_ascii_hexdigit(&self) -> bool {
1027#[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')1028 }
10291030/// Checks if the value is an ASCII punctuation or symbol character
1031 /// (i.e. not alphanumeric, whitespace, or control):
1032 ///
1033 /// - U+0021 ..= U+002F `! " # $ % & ' ( ) * + , - . /`, or
1034 /// - U+003A ..= U+0040 `: ; < = > ? @`, or
1035 /// - U+005B ..= U+0060 `` [ \ ] ^ _ ` ``, or
1036 /// - U+007B ..= U+007E `{ | } ~`
1037 ///
1038 /// # Examples
1039 ///
1040 /// ```
1041 /// let uppercase_a = b'A';
1042 /// let uppercase_g = b'G';
1043 /// let a = b'a';
1044 /// let g = b'g';
1045 /// let zero = b'0';
1046 /// let percent = b'%';
1047 /// let space = b' ';
1048 /// let lf = b'\n';
1049 /// let esc = b'\x1b';
1050 ///
1051 /// assert!(!uppercase_a.is_ascii_punctuation());
1052 /// assert!(!uppercase_g.is_ascii_punctuation());
1053 /// assert!(!a.is_ascii_punctuation());
1054 /// assert!(!g.is_ascii_punctuation());
1055 /// assert!(!zero.is_ascii_punctuation());
1056 /// assert!(percent.is_ascii_punctuation());
1057 /// assert!(!space.is_ascii_punctuation());
1058 /// assert!(!lf.is_ascii_punctuation());
1059 /// assert!(!esc.is_ascii_punctuation());
1060 /// ```
1061#[must_use]
1062 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1063 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1064 #[inline]
1065pub const fn is_ascii_punctuation(&self) -> bool {
1066#[allow(non_exhaustive_omitted_patterns)] match *self {
b'!'..=b'/' => true,
_ => false,
}matches!(*self, b'!'..=b'/')1067 | #[allow(non_exhaustive_omitted_patterns)] match *self {
b':'..=b'@' => true,
_ => false,
}matches!(*self, b':'..=b'@')1068 | #[allow(non_exhaustive_omitted_patterns)] match *self {
b'['..=b'`' => true,
_ => false,
}matches!(*self, b'['..=b'`')1069 | #[allow(non_exhaustive_omitted_patterns)] match *self {
b'{'..=b'~' => true,
_ => false,
}matches!(*self, b'{'..=b'~')1070 }
10711072/// Checks if the value is an ASCII graphic character
1073 /// (i.e. not whitespace or control):
1074 /// U+0021 '!' ..= U+007E '~'.
1075 ///
1076 /// # Examples
1077 ///
1078 /// ```
1079 /// let uppercase_a = b'A';
1080 /// let uppercase_g = b'G';
1081 /// let a = b'a';
1082 /// let g = b'g';
1083 /// let zero = b'0';
1084 /// let percent = b'%';
1085 /// let space = b' ';
1086 /// let lf = b'\n';
1087 /// let esc = b'\x1b';
1088 ///
1089 /// assert!(uppercase_a.is_ascii_graphic());
1090 /// assert!(uppercase_g.is_ascii_graphic());
1091 /// assert!(a.is_ascii_graphic());
1092 /// assert!(g.is_ascii_graphic());
1093 /// assert!(zero.is_ascii_graphic());
1094 /// assert!(percent.is_ascii_graphic());
1095 /// assert!(!space.is_ascii_graphic());
1096 /// assert!(!lf.is_ascii_graphic());
1097 /// assert!(!esc.is_ascii_graphic());
1098 /// ```
1099#[must_use]
1100 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1101 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1102 #[inline]
1103pub const fn is_ascii_graphic(&self) -> bool {
1104#[allow(non_exhaustive_omitted_patterns)] match *self {
b'!'..=b'~' => true,
_ => false,
}matches!(*self, b'!'..=b'~')1105 }
11061107/// Checks if the value is an ASCII whitespace character:
1108 /// U+0020 SPACE, U+0009 HORIZONTAL TAB, U+000A LINE FEED,
1109 /// U+000C FORM FEED, or U+000D CARRIAGE RETURN.
1110 ///
1111 /// **Warning:** Because the list above excludes U+000B VERTICAL TAB,
1112 /// `b.is_ascii_whitespace()` is **not** equivalent to `char::from(b).is_whitespace()`.
1113 ///
1114 /// Rust uses the WhatWG Infra Standard's [definition of ASCII
1115 /// whitespace][infra-aw]. There are several other definitions in
1116 /// wide use. For instance, [the POSIX locale][pct] includes
1117 /// U+000B VERTICAL TAB as well as all the above characters,
1118 /// but—from the very same specification—[the default rule for
1119 /// "field splitting" in the Bourne shell][bfs] considers *only*
1120 /// SPACE, HORIZONTAL TAB, and LINE FEED as whitespace.
1121 ///
1122 /// If you are writing a program that will process an existing
1123 /// file format, check what that format's definition of whitespace is
1124 /// before using this function.
1125 ///
1126 /// [infra-aw]: https://infra.spec.whatwg.org/#ascii-whitespace
1127 /// [pct]: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap07.html#tag_07_03_01
1128 /// [bfs]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_05
1129 ///
1130 /// # Examples
1131 ///
1132 /// ```
1133 /// let uppercase_a = b'A';
1134 /// let uppercase_g = b'G';
1135 /// let a = b'a';
1136 /// let g = b'g';
1137 /// let zero = b'0';
1138 /// let percent = b'%';
1139 /// let space = b' ';
1140 /// let lf = b'\n';
1141 /// let esc = b'\x1b';
1142 ///
1143 /// assert!(!uppercase_a.is_ascii_whitespace());
1144 /// assert!(!uppercase_g.is_ascii_whitespace());
1145 /// assert!(!a.is_ascii_whitespace());
1146 /// assert!(!g.is_ascii_whitespace());
1147 /// assert!(!zero.is_ascii_whitespace());
1148 /// assert!(!percent.is_ascii_whitespace());
1149 /// assert!(space.is_ascii_whitespace());
1150 /// assert!(lf.is_ascii_whitespace());
1151 /// assert!(!esc.is_ascii_whitespace());
1152 /// ```
1153#[must_use]
1154 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1155 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1156 #[inline]
1157pub const fn is_ascii_whitespace(&self) -> bool {
1158#[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' ')1159 }
11601161/// Checks if the value is an ASCII control character:
1162 /// U+0000 NUL ..= U+001F UNIT SEPARATOR, or U+007F DELETE.
1163 /// Note that most ASCII whitespace characters are control
1164 /// characters, but SPACE is not.
1165 ///
1166 /// # Examples
1167 ///
1168 /// ```
1169 /// let uppercase_a = b'A';
1170 /// let uppercase_g = b'G';
1171 /// let a = b'a';
1172 /// let g = b'g';
1173 /// let zero = b'0';
1174 /// let percent = b'%';
1175 /// let space = b' ';
1176 /// let lf = b'\n';
1177 /// let esc = b'\x1b';
1178 ///
1179 /// assert!(!uppercase_a.is_ascii_control());
1180 /// assert!(!uppercase_g.is_ascii_control());
1181 /// assert!(!a.is_ascii_control());
1182 /// assert!(!g.is_ascii_control());
1183 /// assert!(!zero.is_ascii_control());
1184 /// assert!(!percent.is_ascii_control());
1185 /// assert!(!space.is_ascii_control());
1186 /// assert!(lf.is_ascii_control());
1187 /// assert!(esc.is_ascii_control());
1188 /// ```
1189#[must_use]
1190 #[stable(feature = "ascii_ctype_on_intrinsics", since = "1.24.0")]
1191 #[rustc_const_stable(feature = "const_ascii_ctype_on_intrinsics", since = "1.47.0")]
1192 #[inline]
1193pub const fn is_ascii_control(&self) -> bool {
1194#[allow(non_exhaustive_omitted_patterns)] match *self {
b'\0'..=b'\x1F' | b'\x7F' => true,
_ => false,
}matches!(*self, b'\0'..=b'\x1F' | b'\x7F')1195 }
11961197/// Returns an iterator that produces an escaped version of a `u8`,
1198 /// treating it as an ASCII character.
1199 ///
1200 /// The behavior is identical to [`ascii::escape_default`].
1201 ///
1202 /// # Examples
1203 ///
1204 /// ```
1205 /// assert_eq!("0", b'0'.escape_ascii().to_string());
1206 /// assert_eq!("\\t", b'\t'.escape_ascii().to_string());
1207 /// assert_eq!("\\r", b'\r'.escape_ascii().to_string());
1208 /// assert_eq!("\\n", b'\n'.escape_ascii().to_string());
1209 /// assert_eq!("\\'", b'\''.escape_ascii().to_string());
1210 /// assert_eq!("\\\"", b'"'.escape_ascii().to_string());
1211 /// assert_eq!("\\\\", b'\\'.escape_ascii().to_string());
1212 /// assert_eq!("\\x9d", b'\x9d'.escape_ascii().to_string());
1213 /// ```
1214#[must_use = "this returns the escaped byte as an iterator, \
1215 without modifying the original"]
1216 #[stable(feature = "inherent_ascii_escape", since = "1.60.0")]
1217 #[inline]
1218pub fn escape_ascii(self) -> ascii::EscapeDefault {
1219 ascii::escape_default(self)
1220 }
12211222#[inline]
1223pub(crate) const fn is_utf8_char_boundary(self) -> bool {
1224// This is bit magic equivalent to: b < 128 || b >= 192
1225(selfas i8) >= -0x40
1226}
1227}
12281229impl u16 {
1230/// 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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "uint_bit_width", since =
"CURRENT_RUSTC_VERSION")]
#[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 =
"CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"CURRENT_RUSTC_VERSION")]
#[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 =
"CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"CURRENT_RUSTC_VERSION")]
#[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`.
///
/// # 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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since =
"CURRENT_RUSTC_VERSION")]
#[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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since =
"CURRENT_RUSTC_VERSION")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn lowest_one(self) -> Option<u32> {
match NonZero::new(self) {
Some(v) => Some(v.lowest_one()),
None => None,
}
}
/// Returns the bit pattern of `self` reinterpreted as a signed integer of the same size.
///
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
/// the same.
///
/// # Examples
///
/// ```
#[doc = "let n = u16::MAX;"]
///
#[doc = "assert_eq!(n.cast_signed(), -1i16);"]
/// ```
#[stable(feature = "integer_sign_cast", since = "1.87.0")]
#[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_signed(self) -> i16 { self as i16 }
/// Saturating conversion of `self` to a signed integer of the same size.
///
/// The signed integer's maximum value is returned if `self` is larger
/// than the maximum positive value representable by the signed integer.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`checked_cast_signed`](Self::checked_cast_signed),
/// or [`strict_cast_signed`](Self::strict_cast_signed).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = u16::MAX;"]
///
#[doc = "assert_eq!(n.saturating_cast_signed(), i16::MAX);"]
#[doc = "assert_eq!(64u16.saturating_cast_signed(), 64i16);"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_cast_signed(self) -> i16 {
if self <= <i16>::MAX.cast_unsigned() {
self.cast_signed()
} else { <i16>::MAX }
}
/// Checked conversion of `self` to a signed integer of the same size,
/// returning `None` if `self` is larger than the signed integer's
/// maximum value.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`saturating_cast_signed`](Self::saturating_cast_signed),
/// or [`strict_cast_signed`](Self::strict_cast_signed).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = u16::MAX;"]
///
#[doc = "assert_eq!(n.checked_cast_signed(), None);"]
#[doc = "assert_eq!(64u16.checked_cast_signed(), Some(64i16));"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn checked_cast_signed(self) -> Option<i16> {
if self <= <i16>::MAX.cast_unsigned() {
Some(self.cast_signed())
} else { None }
}
/// Strict conversion of `self` to a signed integer of the same size,
/// which panics if `self` is larger than the signed integer's maximum
/// value.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`checked_cast_signed`](Self::checked_cast_signed),
/// or [`saturating_cast_signed`](Self::saturating_cast_signed).
///
/// # Examples
///
/// ```should_panic
/// #![feature(integer_cast_extras)]
#[doc = "let _ = u16::MAX.strict_cast_signed();"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_cast_signed(self) -> i16 {
match self.checked_cast_signed() {
Some(n) => n,
None => imp::overflow_panic::cast_integer(),
}
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `<<` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0xa003u16;"]
#[doc = "let m = 0x3a;"]
///
#[doc = "assert_eq!(n.rotate_left(4), m);"]
#[doc = "assert_eq!(n.rotate_left(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
pub const fn rotate_left(self, n: u32) -> Self {
return intrinsics::rotate_left(self, n);
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `>>` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x3au16;"]
#[doc = "let m = 0xa003;"]
///
#[doc = "assert_eq!(n.rotate_right(4), m);"]
#[doc = "assert_eq!(n.rotate_right(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
pub const fn rotate_right(self, n: u32) -> Self {
return intrinsics::rotate_right(self, n);
}
/// Performs a left funnel shift (concatenates `self` with `rhs`, with `self`
/// making up the most significant half, then shifts the combined value left
/// by `n`, and most significant half is extracted to produce the result).
///
/// Please note this isn't the same operation as the `<<` shifting operator or
/// [`rotate_left`](Self::rotate_left), although `a.funnel_shl(a, n)` is *equivalent*
/// to `a.rotate_left(n)`.
///
/// # Panics
///
/// If `n` is greater than or equal to the number of bits in `self`
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(funnel_shifts)]
#[doc = "let a = 0xa003u16;"]
#[doc = "let b = 0x2deu16;"]
#[doc = "let m = 0x30;"]
///
#[doc = "assert_eq!(a.funnel_shl(b, 4), m);"]
/// ```
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn funnel_shl(self, rhs: Self, n: u32) -> Self {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift left with overflow"));
}
};
unsafe { self.unchecked_funnel_shl(rhs, n) }
}
/// Performs a right funnel shift (concatenates `self` and `rhs`, with `self`
/// making up the most significant half, then shifts the combined value right
/// by `n`, and least significant half is extracted to produce the result).
///
/// Please note this isn't the same operation as the `>>` shifting operator or
/// [`rotate_right`](Self::rotate_right), although `a.funnel_shr(a, n)` is *equivalent*
/// to `a.rotate_right(n)`.
///
/// # Panics
///
/// If `n` is greater than or equal to the number of bits in `self`
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(funnel_shifts)]
#[doc = "let a = 0xa003u16;"]
#[doc = "let b = 0x2deu16;"]
#[doc = "let m = 0x302d;"]
///
#[doc = "assert_eq!(a.funnel_shr(b, 4), m);"]
/// ```
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn funnel_shr(self, rhs: Self, n: u32) -> Self {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift right with overflow"));
}
};
unsafe { self.unchecked_funnel_shr(rhs, n) }
}
/// Unchecked funnel shift left.
///
/// # Safety
///
/// This results in undefined behavior if `n` is greater than or equal to
#[doc = "`u16::BITS`,"]
/// i.e. when [`funnel_shl`](Self::funnel_shl) would panic.
///
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_funnel_shl(self, low: Self, n: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(n: u32) {
if !(n < <u16>::BITS) {
let msg =
"unsafe precondition(s) violated: u16::unchecked_funnel_shl cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(n); }
};
unsafe { intrinsics::unchecked_funnel_shl(self, low, n) }
}
/// Unchecked funnel shift right.
///
/// # Safety
///
/// This results in undefined behavior if `n` is greater than or equal to
#[doc = "`u16::BITS`,"]
/// i.e. when [`funnel_shr`](Self::funnel_shr) would panic.
///
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_funnel_shr(self, low: Self, n: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(n: u32) {
if !(n < <u16>::BITS) {
let msg =
"unsafe precondition(s) violated: u16::unchecked_funnel_shr cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(n); }
};
unsafe { intrinsics::unchecked_funnel_shr(self, low, n) }
}
/// Performs a carry-less multiplication, returning the lower bits.
///
/// This operation is similar to long multiplication in base 2, except that exclusive or is
/// used instead of addition. The implementation is equivalent to:
///
/// ```no_run
#[doc = "pub fn carryless_mul(lhs: u16, rhs: u16) -> u16{"]
/// let mut retval = 0;
#[doc = " for i in 0..u16::BITS {"]
/// if (rhs >> i) & 1 != 0 {
/// // long multiplication would use +=
/// retval ^= lhs << i;
/// }
/// }
/// retval
/// }
/// ```
///
/// The actual implementation is more efficient, and on some platforms lowers directly to a
/// dedicated instruction.
///
/// # Uses
///
/// Carryless multiplication can be used to turn a bitmask of quote characters into a
/// bit mask of characters surrounded by quotes:
///
/// ```no_run
/// r#"abc xxx "foobar" zzz "a"!"#; // input string
/// 0b0000000010000001000001010; // quote_mask
/// 0b0000000001111110000000100; // quote_mask.carryless_mul(!0) & !quote_mask
/// ```
///
/// Another use is in cryptography, where carryless multiplication allows for efficient
/// implementations of polynomial multiplication in `GF(2)[X]`, the polynomial ring
/// over `GF(2)`.
///
/// # Examples
///
/// ```
/// #![feature(uint_carryless_mul)]
///
#[doc = "let a = 0x9012u16;"]
#[doc = "let b = 0xcd34u16;"]
///
#[doc = "assert_eq!(a.carryless_mul(b), 0x928);"]
/// ```
#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
#[doc(alias = "clmul")]
#[unstable(feature = "uint_carryless_mul", issue = "152080")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn carryless_mul(self, rhs: Self) -> Self {
intrinsics::carryless_mul(self, rhs)
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1234u16;"]
/// let m = n.swap_bytes();
///
#[doc = "assert_eq!(m, 0x3412);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn swap_bytes(self) -> Self {
intrinsics::bswap(self as u16) as Self
}
/// Returns an integer with the bit locations specified by `mask` packed
/// contiguously into the least significant bits of the result.
/// ```
/// #![feature(uint_gather_scatter_bits)]
#[doc = "let n: u16 = 0b1011_1100;"]
///
/// assert_eq!(n.extract_bits(0b0010_0100), 0b0000_0011);
/// assert_eq!(n.extract_bits(0xF0), 0b0000_1011);
/// ```
#[doc(alias = "pext")]
#[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn extract_bits(self, mask: Self) -> Self {
imp::int_bits::u16::extract_impl(self as u16, mask as u16) as u16
}
/// Returns an integer with the least significant bits of `self`
/// distributed to the bit locations specified by `mask`.
/// ```
/// #![feature(uint_gather_scatter_bits)]
#[doc = "let n: u16 = 0b1010_1101;"]
///
/// assert_eq!(n.deposit_bits(0b0101_0101), 0b0101_0001);
/// assert_eq!(n.deposit_bits(0xF0), 0b1101_0000);
/// ```
#[doc(alias = "pdep")]
#[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn deposit_bits(self, mask: Self) -> Self {
imp::int_bits::u16::deposit_impl(self as u16, mask as u16) as u16
}
/// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
/// second least-significant bit becomes second most-significant bit, etc.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1234u16;"]
/// let m = n.reverse_bits();
///
#[doc = "assert_eq!(m, 0x2c48);"]
#[doc = "assert_eq!(0, 0u16.reverse_bits());"]
/// ```
#[stable(feature = "reverse_bits", since = "1.37.0")]
#[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn reverse_bits(self) -> Self {
intrinsics::bitreverse(self as u16) as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au16;"]
///
/// if cfg!(target_endian = "big") {
#[doc = " assert_eq!(u16::from_be(n), n)"]
/// } else {
#[doc = " assert_eq!(u16::from_be(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use]
#[inline(always)]
pub const fn from_be(x: Self) -> Self { x.swap_bytes() }
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au16;"]
///
/// if cfg!(target_endian = "little") {
#[doc = " assert_eq!(u16::from_le(n), n)"]
/// } else {
#[doc = " assert_eq!(u16::from_le(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use]
#[inline(always)]
pub const fn from_le(x: Self) -> Self { x }
/// Converts `self` to big endian from the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au16;"]
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn to_be(self) -> Self { self.swap_bytes() }
/// Converts `self` to little endian from the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au16;"]
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn to_le(self) -> Self { self }
/// Checked integer addition. Computes `self + rhs`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((u16::MAX - 2).checked_add(1), Some(u16::MAX - 1));"]
#[doc = "assert_eq!((u16::MAX - 2).checked_add(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(intrinsics::add_with_overflow(self, rhs).1) {
None
} else { Some(unsafe { intrinsics::unchecked_add(self, rhs) }) }
}
/// Strict integer addition. Computes `self + rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((u16::MAX - 2).strict_add(1), u16::MAX - 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (u16::MAX - 2).strict_add(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_add(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Unchecked integer addition. Computes `self + rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_add(y)` is semantically equivalent to calling
/// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_add`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self + rhs > u16::MAX`,"]
/// i.e. when [`checked_add`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_add`]: u16::checked_add"]
#[doc = "[`wrapping_add`]: u16::wrapping_add"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u16, rhs: u16) {
if !!lhs.overflowing_add(rhs).1 {
let msg =
"unsafe precondition(s) violated: u16::unchecked_add cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_add(self, rhs) }
}
/// Checked addition with a signed integer. Computes `self + rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u16.checked_add_signed(2), Some(3));"]
#[doc = "assert_eq!(1u16.checked_add_signed(-2), None);"]
#[doc = "assert_eq!((u16::MAX - 2).checked_add_signed(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add_signed(self, rhs: i16) -> Option<Self> {
let (a, b) = self.overflowing_add_signed(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict addition with a signed integer. Computes `self + rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u16.strict_add_signed(2), 3);"]
/// ```
///
/// The following panic because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1u16.strict_add_signed(-2);"]
/// ```
///
/// ```should_panic
#[doc = "let _ = (u16::MAX - 2).strict_add_signed(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add_signed(self, rhs: i16) -> Self {
let (a, b) = self.overflowing_add_signed(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Checked integer subtraction. Computes `self - rhs`, returning
/// `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u16.checked_sub(1), Some(0));"]
#[doc = "assert_eq!(0u16.checked_sub(1), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
if self < rhs {
None
} else { Some(unsafe { intrinsics::unchecked_sub(self, rhs) }) }
}
/// Strict integer subtraction. Computes `self - rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u16.strict_sub(1), 0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0u16.strict_sub(1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_sub(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
/// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_sub`].
///
/// If you find yourself writing code like this:
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if foo >= bar {
/// // SAFETY: just checked it will not overflow
/// let diff = unsafe { foo.unchecked_sub(bar) };
/// // ... use diff ...
/// }
/// ```
///
/// Consider changing it to
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if let Some(diff) = foo.checked_sub(bar) {
/// // ... use diff ...
/// }
/// ```
///
/// As that does exactly the same thing -- including telling the optimizer
/// that the subtraction cannot overflow -- but avoids needing `unsafe`.
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self - rhs < u16::MIN`,"]
/// i.e. when [`checked_sub`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_sub`]: u16::checked_sub"]
#[doc = "[`wrapping_sub`]: u16::wrapping_sub"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u16, rhs: u16) {
if !!lhs.overflowing_sub(rhs).1 {
let msg =
"unsafe precondition(s) violated: u16::unchecked_sub cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_sub(self, rhs) }
}
/// Checked subtraction with a signed integer. Computes `self - rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u16.checked_sub_signed(2), None);"]
#[doc = "assert_eq!(1u16.checked_sub_signed(-2), Some(3));"]
#[doc = "assert_eq!((u16::MAX - 2).checked_sub_signed(-4), None);"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub_signed(self, rhs: i16) -> Option<Self> {
let (res, overflow) = self.overflowing_sub_signed(rhs);
if !overflow { Some(res) } else { None }
}
/// Strict subtraction with a signed integer. Computes `self - rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3u16.strict_sub_signed(2), 1);"]
/// ```
///
/// The following panic because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1u16.strict_sub_signed(2);"]
/// ```
///
/// ```should_panic
#[doc = "let _ = (u16::MAX).strict_sub_signed(-1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub_signed(self, rhs: i16) -> Self {
let (a, b) = self.overflowing_sub_signed(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
#[doc =
"Checked integer subtraction. Computes `self - rhs` and checks if the result fits into an [`i16`], returning `None` if overflow occurred."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10u16.checked_signed_diff(2), Some(8));"]
#[doc = "assert_eq!(2u16.checked_signed_diff(10), Some(-8));"]
#[doc = "assert_eq!(u16::MAX.checked_signed_diff(i16::MAX as u16), None);"]
#[doc =
"assert_eq!((i16::MAX as u16).checked_signed_diff(u16::MAX), Some(i16::MIN));"]
#[doc = "assert_eq!((i16::MAX as u16 + 1).checked_signed_diff(0), None);"]
#[doc = "assert_eq!(u16::MAX.checked_signed_diff(u16::MAX), Some(0));"]
/// ```
#[stable(feature = "unsigned_signed_diff", since = "1.91.0")]
#[rustc_const_stable(feature = "unsigned_signed_diff", since = "1.91.0")]
#[inline]
pub const fn checked_signed_diff(self, rhs: Self) -> Option<i16> {
let res = self.wrapping_sub(rhs) as i16;
let overflow = (self >= rhs) == (res < 0);
if !overflow { Some(res) } else { None }
}
/// Checked integer multiplication. Computes `self * rhs`, returning
/// `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u16.checked_mul(1), Some(5));"]
#[doc = "assert_eq!(u16::MAX.checked_mul(2), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer multiplication. Computes `self * rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u16.strict_mul(1), 5);"]
/// ```
///
/// The following panics because of overflow:
///
/// ``` should_panic
#[doc = "let _ = u16::MAX.strict_mul(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_mul(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_mul(rhs);
if b { imp::overflow_panic::mul() } else { a }
}
/// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
/// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_mul`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self * rhs > u16::MAX`,"]
/// i.e. when [`checked_mul`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_mul`]: u16::checked_mul"]
#[doc = "[`wrapping_mul`]: u16::wrapping_mul"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u16, rhs: u16) {
if !!lhs.overflowing_mul(rhs).1 {
let msg =
"unsafe precondition(s) violated: u16::unchecked_mul cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_mul(self, rhs) }
}
/// Checked integer division. Computes `self / rhs`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128u16.checked_div(2), Some(64));"]
#[doc = "assert_eq!(1u16.checked_div(0), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(unsafe { intrinsics::unchecked_div(self, rhs) }) }
}
/// Strict integer division. Computes `self / rhs`.
///
/// Strict division on unsigned types is just normal division. There's no
/// way overflow could ever happen. This function exists so that all
/// operations are accounted for in the strict operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u16.strict_div(10), 10);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1u16).strict_div(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_div(self, rhs: Self) -> Self { self / rhs }
/// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128u16.checked_div_euclid(2), Some(64));"]
#[doc = "assert_eq!(1u16.checked_div_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(self.div_euclid(rhs)) }
}
/// Strict Euclidean division. Computes `self.div_euclid(rhs)`.
///
/// Strict division on unsigned types is just normal division. There's no
/// way overflow could ever happen. This function exists so that all
/// operations are accounted for in the strict operations. Since, for the
/// positive integers, all common definitions of division are equal, this
/// is exactly equal to `self.strict_div(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u16.strict_div_euclid(10), 10);"]
/// ```
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1u16).strict_div_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Checked integer division without remainder. Computes `self / rhs`,
/// returning `None` if `rhs == 0` or if `self % rhs != 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64u16.checked_div_exact(2), Some(32));"]
#[doc = "assert_eq!(64u16.checked_div_exact(32), Some(2));"]
#[doc = "assert_eq!(64u16.checked_div_exact(0), None);"]
#[doc = "assert_eq!(65u16.checked_div_exact(2), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_exact(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else {
unsafe {
if intrinsics::unlikely(intrinsics::unchecked_rem(self, rhs) != 0)
{
None
} else { Some(intrinsics::exact_div(self, rhs)) }
}
}
}
/// Integer division without remainder. Computes `self / rhs`, returning `None` if `self % rhs != 0`.
///
/// # Panics
///
/// This function will panic if `rhs == 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64u16.div_exact(2), Some(32));"]
#[doc = "assert_eq!(64u16.div_exact(32), Some(2));"]
#[doc = "assert_eq!(65u16.div_exact(2), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn div_exact(self, rhs: Self) -> Option<Self> {
if self % rhs != 0 { None } else { Some(self / rhs) }
}
/// Unchecked integer division without remainder. Computes `self / rhs`.
///
/// # Safety
///
/// This results in undefined behavior when `rhs == 0` or `self % rhs != 0`,
/// i.e. when [`checked_div_exact`](Self::checked_div_exact) would return `None`.
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_div_exact(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u16, rhs: u16) {
if !(rhs > 0 && lhs % rhs == 0) {
let msg =
"unsafe precondition(s) violated: u16::unchecked_div_exact divide by zero or leave a remainder\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::exact_div(self, rhs) }
}
/// Checked integer remainder. Computes `self % rhs`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u16.checked_rem(2), Some(1));"]
#[doc = "assert_eq!(5u16.checked_rem(0), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(unsafe { intrinsics::unchecked_rem(self, rhs) }) }
}
/// Strict integer remainder. Computes `self % rhs`.
///
/// Strict remainder calculation on unsigned types is just the regular
/// remainder calculation. There's no way overflow could ever happen.
/// This function exists so that all operations are accounted for in the
/// strict operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u16.strict_rem(10), 0);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5u16.strict_rem(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_rem(self, rhs: Self) -> Self { self % rhs }
/// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u16.checked_rem_euclid(2), Some(1));"]
#[doc = "assert_eq!(5u16.checked_rem_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(self.rem_euclid(rhs)) }
}
/// Strict Euclidean modulo. Computes `self.rem_euclid(rhs)`.
///
/// Strict modulo calculation on unsigned types is just the regular
/// remainder calculation. There's no way overflow could ever happen.
/// This function exists so that all operations are accounted for in the
/// strict operations. Since, for the positive integers, all common
/// definitions of division are equal, this is exactly equal to
/// `self.strict_rem(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u16.strict_rem_euclid(10), 0);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5u16.strict_rem_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Same value as `self | other`, but UB if any bit position is set in both inputs.
///
/// This is a situational micro-optimization for places where you'd rather
/// use addition on some platforms and bitwise or on other platforms, based
/// on exactly which instructions combine better with whatever else you're
/// doing. Note that there's no reason to bother using this for places
/// where it's clear from the operations involved that they can't overlap.
/// For example, if you're combining `u16`s into a `u32` with
/// `((a as u32) << 16) | (b as u32)`, that's fine, as the backend will
/// know those sides of the `|` are disjoint without needing help.
///
/// # Examples
///
/// ```
/// #![feature(disjoint_bitor)]
///
/// // SAFETY: `1` and `4` have no bits in common.
/// unsafe {
#[doc = " assert_eq!(1_u16.unchecked_disjoint_bitor(4), 5);"]
/// }
/// ```
///
/// # Safety
///
/// Requires that `(self & other) == 0`, otherwise it's immediate UB.
///
/// Equivalently, requires that `(self | other) == (self + other)`.
#[unstable(feature = "disjoint_bitor", issue = "135758")]
#[rustc_const_unstable(feature = "disjoint_bitor", issue = "135758")]
#[inline]
pub const unsafe fn unchecked_disjoint_bitor(self, other: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u16, rhs: u16) {
if !((lhs & rhs) == 0) {
let msg =
"unsafe precondition(s) violated: u16::unchecked_disjoint_bitor cannot have overlapping bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, other);
}
};
unsafe { intrinsics::disjoint_bitor(self, other) }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// This method might not be optimized owing to implementation details;
/// `ilog2` can produce results more efficiently for base 2, and `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));"]
/// ```
#[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 == 2 {
return self.checked_ilog2();
} else 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.
///
/// # 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> {
if exp == 0 { return Some(1); }
let mut base = self;
let mut acc: Self = 1;
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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc: Self = 1;
loop {
if (exp & 1) == 1 {
acc = acc.strict_mul(base);
if exp == 1 { return acc; }
}
exp /= 2;
base = base.strict_mul(base);
}
}
/// 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. The behaviour 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. The behaviour 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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc: Self = 1;
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 { acc = acc.wrapping_mul(base); }
exp /= 2;
base = base.wrapping_mul(base);
}
acc.wrapping_mul(base)
} else {
loop {
if (exp & 1) == 1 {
acc = acc.wrapping_mul(base);
if exp == 1 { return acc; }
}
exp /= 2;
base = base.wrapping_mul(base);
}
}
}
/// 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) {
if exp == 0 { return (1, false); }
let mut base = self;
let mut acc: Self = 1;
let mut overflown = false;
let mut r;
loop {
if (exp & 1) == 1 {
r = acc.overflowing_mul(base);
if exp == 1 { r.1 |= overflown; return r; }
acc = r.0;
overflown |= r.1;
}
exp /= 2;
r = base.overflowing_mul(base);
base = r.0;
overflown |= r.1;
}
}
/// 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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc = 1;
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 { acc = acc * base; }
exp /= 2;
base = base * base;
}
acc * base
} else {
loop {
if (exp & 1) == 1 {
acc = acc * base;
if exp == 1 { return acc; }
}
exp /= 2;
base = base * base;
}
}
}
/// Returns the square root of the number, rounded down.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10u16.isqrt(), 3);"]
/// ```
#[stable(feature = "isqrt", since = "1.84.0")]
#[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn isqrt(self) -> Self {
let result = imp::int_sqrt::u16(self as u16) as Self;
unsafe {
const MAX_RESULT: u16 = imp::int_sqrt::u16(<u16>::MAX) as u16;
crate::hint::assert_unchecked(result <= MAX_RESULT)
}
if self >= 1 { unsafe { crate::hint::assert_unchecked(result >= 1) } }
unsafe {
crate::hint::assert_unchecked(result.unchecked_mul(result) <= self);
crate::hint::assert_unchecked(result <= self);
}
result
}
/// Performs Euclidean division.
///
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self / rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7u16.div_euclid(4), 1); // or any other integer type"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Calculates the least remainder of `self` when divided by
/// `rhs`.
///
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self % rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7u16.rem_euclid(4), 3); // or any other integer type"]
/// ```
#[doc(alias = "modulo", alias = "mod")]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
///
/// This is the same as performing `self / rhs` for all unsigned integers.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "assert_eq!(7_u16.div_floor(4), 1);"]
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn div_floor(self, rhs: Self) -> Self { self / rhs }
/// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7_u16.div_ceil(4), 2);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_ceil(self, rhs: Self) -> Self {
let d = self / rhs;
let r = self % rhs;
if r > 0 { d + 1 } else { d }
}
/// Calculates the smallest value greater than or equal to `self` that
/// is a multiple of `rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// On overflow, this function will panic if overflow checks are enabled (default in debug
/// mode) and wrap if overflow checks are disabled (default in release mode).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(16_u16.next_multiple_of(8), 16);"]
#[doc = "assert_eq!(23_u16.next_multiple_of(8), 24);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_multiple_of(self, rhs: Self) -> Self {
match self % rhs { 0 => self, r => self + (rhs - r), }
}
/// Calculates the smallest value greater than or equal to `self` that
/// is a multiple of `rhs`. Returns `None` if `rhs` is zero or the
/// operation would result in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(16_u16.checked_next_multiple_of(8), Some(16));"]
#[doc = "assert_eq!(23_u16.checked_next_multiple_of(8), Some(24));"]
#[doc = "assert_eq!(1_u16.checked_next_multiple_of(0), None);"]
#[doc = "assert_eq!(u16::MAX.checked_next_multiple_of(2), None);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
match match self.checked_rem(rhs) { Some(x) => x, None => return None, } {
0 => Some(self),
r => self.checked_add(rhs - r),
}
}
/// Returns `true` if `self` is an integer multiple of `rhs`, and false otherwise.
///
/// This function is equivalent to `self % rhs == 0`, except that it will not panic
/// for `rhs == 0`. Instead, `0.is_multiple_of(0) == true`, and for any non-zero `n`,
/// `n.is_multiple_of(0) == false`.
///
/// # Examples
///
/// ```
#[doc = "assert!(6_u16.is_multiple_of(2));"]
#[doc = "assert!(!5_u16.is_multiple_of(2));"]
///
#[doc = "assert!(0_u16.is_multiple_of(0));"]
#[doc = "assert!(!6_u16.is_multiple_of(0));"]
/// ```
#[stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
#[rustc_const_stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
#[must_use]
#[inline]
pub const fn is_multiple_of(self, rhs: Self) -> bool {
match rhs { 0 => self == 0, _ => self % rhs == 0, }
}
/// Returns `true` if and only if `self == 2^k` for some unsigned integer `k`.
///
/// # Examples
///
/// ```
#[doc = "assert!(16u16.is_power_of_two());"]
#[doc = "assert!(!10u16.is_power_of_two());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
#[inline(always)]
pub const fn is_power_of_two(self) -> bool { self.count_ones() == 1 }
#[inline]
const fn one_less_than_next_power_of_two(self) -> Self {
if self <= 1 { return 0; }
let p = self - 1;
let z = unsafe { intrinsics::ctlz_nonzero(p) };
<u16>::MAX >> z
}
/// Returns the smallest power of two greater than or equal to `self`.
///
/// When return value overflows (i.e., `self > (1 << (N-1))` for type
/// `uN`), it panics in debug mode and the return value is wrapped to 0 in
/// release mode (the only situation in which this method can return 0).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u16.next_power_of_two(), 2);"]
#[doc = "assert_eq!(3u16.next_power_of_two(), 4);"]
#[doc = "assert_eq!(0u16.next_power_of_two(), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_power_of_two(self) -> Self {
self.one_less_than_next_power_of_two() + 1
}
/// Returns the smallest power of two greater than or equal to `self`. If
/// the next power of two is greater than the type's maximum value,
/// `None` is returned, otherwise the power of two is wrapped in `Some`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u16.checked_next_power_of_two(), Some(2));"]
#[doc = "assert_eq!(3u16.checked_next_power_of_two(), Some(4));"]
#[doc = "assert_eq!(u16::MAX.checked_next_power_of_two(), None);"]
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn checked_next_power_of_two(self) -> Option<Self> {
self.one_less_than_next_power_of_two().checked_add(1)
}
/// Returns the smallest power of two greater than or equal to `n`. If
/// the next power of two is greater than the type's maximum value,
/// the return value is wrapped to `0`.
///
/// # Examples
///
/// ```
/// #![feature(wrapping_next_power_of_two)]
///
#[doc = "assert_eq!(2u16.wrapping_next_power_of_two(), 2);"]
#[doc = "assert_eq!(3u16.wrapping_next_power_of_two(), 4);"]
#[doc = "assert_eq!(u16::MAX.wrapping_next_power_of_two(), 0);"]
/// ```
#[inline]
#[unstable(feature = "wrapping_next_power_of_two", issue = "32463", reason =
"needs decision on wrapping behavior")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn wrapping_next_power_of_two(self) -> Self {
self.one_less_than_next_power_of_two().wrapping_add(1)
}
/// Returns the memory representation of this integer as a byte array in
/// big-endian (network) byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234u16.to_be_bytes();"]
#[doc = "assert_eq!(bytes, [0x12, 0x34]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
self.to_be().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// little-endian byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234u16.to_le_bytes();"]
#[doc = "assert_eq!(bytes, [0x34, 0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
self.to_le().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code
/// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
/// instead.
///
#[doc = ""]
///
/// [`to_be_bytes`]: Self::to_be_bytes
/// [`to_le_bytes`]: Self::to_le_bytes
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234u16.to_ne_bytes();"]
/// assert_eq!(
/// bytes,
/// if cfg!(target_endian = "big") {
#[doc = " [0x12, 0x34]"]
/// } else {
#[doc = " [0x34, 0x12]"]
/// }
/// );
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[allow(unnecessary_transmutes)]
#[inline]
pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
unsafe { mem::transmute(self) }
}
/// Creates a native endian integer value from its representation
/// as a byte array in big endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = u16::from_be_bytes([0x12, 0x34]);"]
#[doc = "assert_eq!(value, 0x1234);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_be_u16(input: &mut &[u8]) -> u16 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u16>());"]
/// *input = rest;
#[doc = " u16::from_be_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_be(Self::from_ne_bytes(bytes))
}
/// Creates a native endian integer value from its representation
/// as a byte array in little endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = u16::from_le_bytes([0x34, 0x12]);"]
#[doc = "assert_eq!(value, 0x1234);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_le_u16(input: &mut &[u8]) -> u16 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u16>());"]
/// *input = rest;
#[doc = " u16::from_le_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_le(Self::from_ne_bytes(bytes))
}
/// Creates a native endian integer value from its memory representation
/// as a byte array in native endianness.
///
/// As the target platform's native endianness is used, portable code
/// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
/// appropriate instead.
///
/// [`from_be_bytes`]: Self::from_be_bytes
/// [`from_le_bytes`]: Self::from_le_bytes
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = u16::from_ne_bytes(if cfg!(target_endian = \"big\") {"]
#[doc = " [0x12, 0x34]"]
/// } else {
#[doc = " [0x34, 0x12]"]
/// });
#[doc = "assert_eq!(value, 0x1234);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_ne_u16(input: &mut &[u8]) -> u16 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u16>());"]
/// *input = rest;
#[doc = " u16::from_ne_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use]
#[inline]
pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
unsafe { mem::transmute(bytes) }
}
/// New code should prefer to use
#[doc = "[`u16::MIN`] instead."]
///
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_promotable]
#[inline(always)]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MIN` associated constant on this type")]
#[rustc_diagnostic_item = "u16_legacy_fn_min_value"]
pub const fn min_value() -> Self { Self::MIN }
/// New code should prefer to use
#[doc = "[`u16::MAX`] instead."]
///
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_promotable]
#[inline(always)]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MAX` associated constant on this type")]
#[rustc_diagnostic_item = "u16_legacy_fn_max_value"]
pub const fn max_value() -> Self { Self::MAX }
/// Truncate an integer to an integer of the same size or smaller, preserving the least
/// significant bits.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u8, 120u16.truncate());"]
/// assert_eq!(120u8, 376u32.truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
/// instead of truncating.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u8, 120u16.saturating_truncate());"]
/// assert_eq!(255u8, 376u32.saturating_truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn saturating_truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_saturating_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
/// is outside the bounds of the smaller type.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(Some(120u8), 120u16.checked_truncate());"]
/// assert_eq!(None, 376u32.checked_truncate::<u8>());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn checked_truncate<Target>(self) -> Option<Target> where
Self: [const] traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_checked_truncate(self)
}
/// Widen to an integer of the same size or larger, preserving its value.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u128, 120u8.widen());"]
/// ```
#[must_use =
"this returns the widened value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn widen<Target>(self) -> Target where Self: [const]
traits::WidenTarget<Target> {
traits::WidenTarget::internal_widen(self)
}uint_impl! {
1231Self = u16,
1232 ActualT = u16,
1233 SignedT = i16,
1234 BITS = 16,
1235 BITS_MINUS_ONE = 15,
1236 MAX = 65535,
1237 rot = 4,
1238 rot_op = "0xa003",
1239 rot_result = "0x3a",
1240 fsh_op = "0x2de",
1241 fshl_result = "0x30",
1242 fshr_result = "0x302d",
1243 clmul_lhs = "0x9012",
1244 clmul_rhs = "0xcd34",
1245 clmul_result = "0x928",
1246 swap_op = "0x1234",
1247 swapped = "0x3412",
1248 reversed = "0x2c48",
1249 le_bytes = "[0x34, 0x12]",
1250 be_bytes = "[0x12, 0x34]",
1251 to_xe_bytes_doc = "",
1252 from_xe_bytes_doc = "",
1253 bound_condition = "",
1254 }1255/// 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 }1256/// 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 }1257/// 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 }1258/// 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 }12591260/// Checks if the value is a Unicode surrogate code point, which are disallowed values for [`char`].
1261 ///
1262 /// # Examples
1263 ///
1264 /// ```
1265 /// #![feature(utf16_extra)]
1266 ///
1267 /// let low_non_surrogate = 0xA000u16;
1268 /// let low_surrogate = 0xD800u16;
1269 /// let high_surrogate = 0xDC00u16;
1270 /// let high_non_surrogate = 0xE000u16;
1271 ///
1272 /// assert!(!low_non_surrogate.is_utf16_surrogate());
1273 /// assert!(low_surrogate.is_utf16_surrogate());
1274 /// assert!(high_surrogate.is_utf16_surrogate());
1275 /// assert!(!high_non_surrogate.is_utf16_surrogate());
1276 /// ```
1277#[must_use]
1278 #[unstable(feature = "utf16_extra", issue = "94919")]
1279 #[inline]
1280pub const fn is_utf16_surrogate(self) -> bool {
1281#[allow(non_exhaustive_omitted_patterns)] match self {
0xD800..=0xDFFF => true,
_ => false,
}matches!(self, 0xD800..=0xDFFF)1282 }
1283}
12841285impl u32 {
1286/// 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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "uint_bit_width", since =
"CURRENT_RUSTC_VERSION")]
#[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 =
"CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"CURRENT_RUSTC_VERSION")]
#[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 =
"CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"CURRENT_RUSTC_VERSION")]
#[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`.
///
/// # 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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since =
"CURRENT_RUSTC_VERSION")]
#[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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since =
"CURRENT_RUSTC_VERSION")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn lowest_one(self) -> Option<u32> {
match NonZero::new(self) {
Some(v) => Some(v.lowest_one()),
None => None,
}
}
/// Returns the bit pattern of `self` reinterpreted as a signed integer of the same size.
///
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
/// the same.
///
/// # Examples
///
/// ```
#[doc = "let n = u32::MAX;"]
///
#[doc = "assert_eq!(n.cast_signed(), -1i32);"]
/// ```
#[stable(feature = "integer_sign_cast", since = "1.87.0")]
#[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_signed(self) -> i32 { self as i32 }
/// Saturating conversion of `self` to a signed integer of the same size.
///
/// The signed integer's maximum value is returned if `self` is larger
/// than the maximum positive value representable by the signed integer.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`checked_cast_signed`](Self::checked_cast_signed),
/// or [`strict_cast_signed`](Self::strict_cast_signed).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = u32::MAX;"]
///
#[doc = "assert_eq!(n.saturating_cast_signed(), i32::MAX);"]
#[doc = "assert_eq!(64u32.saturating_cast_signed(), 64i32);"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_cast_signed(self) -> i32 {
if self <= <i32>::MAX.cast_unsigned() {
self.cast_signed()
} else { <i32>::MAX }
}
/// Checked conversion of `self` to a signed integer of the same size,
/// returning `None` if `self` is larger than the signed integer's
/// maximum value.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`saturating_cast_signed`](Self::saturating_cast_signed),
/// or [`strict_cast_signed`](Self::strict_cast_signed).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = u32::MAX;"]
///
#[doc = "assert_eq!(n.checked_cast_signed(), None);"]
#[doc = "assert_eq!(64u32.checked_cast_signed(), Some(64i32));"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn checked_cast_signed(self) -> Option<i32> {
if self <= <i32>::MAX.cast_unsigned() {
Some(self.cast_signed())
} else { None }
}
/// Strict conversion of `self` to a signed integer of the same size,
/// which panics if `self` is larger than the signed integer's maximum
/// value.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`checked_cast_signed`](Self::checked_cast_signed),
/// or [`saturating_cast_signed`](Self::saturating_cast_signed).
///
/// # Examples
///
/// ```should_panic
/// #![feature(integer_cast_extras)]
#[doc = "let _ = u32::MAX.strict_cast_signed();"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_cast_signed(self) -> i32 {
match self.checked_cast_signed() {
Some(n) => n,
None => imp::overflow_panic::cast_integer(),
}
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `<<` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x10000b3u32;"]
#[doc = "let m = 0xb301;"]
///
#[doc = "assert_eq!(n.rotate_left(8), m);"]
#[doc = "assert_eq!(n.rotate_left(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
pub const fn rotate_left(self, n: u32) -> Self {
return intrinsics::rotate_left(self, n);
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `>>` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0xb301u32;"]
#[doc = "let m = 0x10000b3;"]
///
#[doc = "assert_eq!(n.rotate_right(8), m);"]
#[doc = "assert_eq!(n.rotate_right(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
pub const fn rotate_right(self, n: u32) -> Self {
return intrinsics::rotate_right(self, n);
}
/// Performs a left funnel shift (concatenates `self` with `rhs`, with `self`
/// making up the most significant half, then shifts the combined value left
/// by `n`, and most significant half is extracted to produce the result).
///
/// Please note this isn't the same operation as the `<<` shifting operator or
/// [`rotate_left`](Self::rotate_left), although `a.funnel_shl(a, n)` is *equivalent*
/// to `a.rotate_left(n)`.
///
/// # Panics
///
/// If `n` is greater than or equal to the number of bits in `self`
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(funnel_shifts)]
#[doc = "let a = 0x10000b3u32;"]
#[doc = "let b = 0x2fe78e45u32;"]
#[doc = "let m = 0xb32f;"]
///
#[doc = "assert_eq!(a.funnel_shl(b, 8), m);"]
/// ```
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn funnel_shl(self, rhs: Self, n: u32) -> Self {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift left with overflow"));
}
};
unsafe { self.unchecked_funnel_shl(rhs, n) }
}
/// Performs a right funnel shift (concatenates `self` and `rhs`, with `self`
/// making up the most significant half, then shifts the combined value right
/// by `n`, and least significant half is extracted to produce the result).
///
/// Please note this isn't the same operation as the `>>` shifting operator or
/// [`rotate_right`](Self::rotate_right), although `a.funnel_shr(a, n)` is *equivalent*
/// to `a.rotate_right(n)`.
///
/// # Panics
///
/// If `n` is greater than or equal to the number of bits in `self`
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(funnel_shifts)]
#[doc = "let a = 0x10000b3u32;"]
#[doc = "let b = 0x2fe78e45u32;"]
#[doc = "let m = 0xb32fe78e;"]
///
#[doc = "assert_eq!(a.funnel_shr(b, 8), m);"]
/// ```
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn funnel_shr(self, rhs: Self, n: u32) -> Self {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift right with overflow"));
}
};
unsafe { self.unchecked_funnel_shr(rhs, n) }
}
/// Unchecked funnel shift left.
///
/// # Safety
///
/// This results in undefined behavior if `n` is greater than or equal to
#[doc = "`u32::BITS`,"]
/// i.e. when [`funnel_shl`](Self::funnel_shl) would panic.
///
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_funnel_shl(self, low: Self, n: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(n: u32) {
if !(n < <u32>::BITS) {
let msg =
"unsafe precondition(s) violated: u32::unchecked_funnel_shl cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(n); }
};
unsafe { intrinsics::unchecked_funnel_shl(self, low, n) }
}
/// Unchecked funnel shift right.
///
/// # Safety
///
/// This results in undefined behavior if `n` is greater than or equal to
#[doc = "`u32::BITS`,"]
/// i.e. when [`funnel_shr`](Self::funnel_shr) would panic.
///
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_funnel_shr(self, low: Self, n: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(n: u32) {
if !(n < <u32>::BITS) {
let msg =
"unsafe precondition(s) violated: u32::unchecked_funnel_shr cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(n); }
};
unsafe { intrinsics::unchecked_funnel_shr(self, low, n) }
}
/// Performs a carry-less multiplication, returning the lower bits.
///
/// This operation is similar to long multiplication in base 2, except that exclusive or is
/// used instead of addition. The implementation is equivalent to:
///
/// ```no_run
#[doc = "pub fn carryless_mul(lhs: u32, rhs: u32) -> u32{"]
/// let mut retval = 0;
#[doc = " for i in 0..u32::BITS {"]
/// if (rhs >> i) & 1 != 0 {
/// // long multiplication would use +=
/// retval ^= lhs << i;
/// }
/// }
/// retval
/// }
/// ```
///
/// The actual implementation is more efficient, and on some platforms lowers directly to a
/// dedicated instruction.
///
/// # Uses
///
/// Carryless multiplication can be used to turn a bitmask of quote characters into a
/// bit mask of characters surrounded by quotes:
///
/// ```no_run
/// r#"abc xxx "foobar" zzz "a"!"#; // input string
/// 0b0000000010000001000001010; // quote_mask
/// 0b0000000001111110000000100; // quote_mask.carryless_mul(!0) & !quote_mask
/// ```
///
/// Another use is in cryptography, where carryless multiplication allows for efficient
/// implementations of polynomial multiplication in `GF(2)[X]`, the polynomial ring
/// over `GF(2)`.
///
/// # Examples
///
/// ```
/// #![feature(uint_carryless_mul)]
///
#[doc = "let a = 0x56789012u32;"]
#[doc = "let b = 0xf52ecd34u32;"]
///
#[doc = "assert_eq!(a.carryless_mul(b), 0x9b980928);"]
/// ```
#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
#[doc(alias = "clmul")]
#[unstable(feature = "uint_carryless_mul", issue = "152080")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn carryless_mul(self, rhs: Self) -> Self {
intrinsics::carryless_mul(self, rhs)
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x12345678u32;"]
/// let m = n.swap_bytes();
///
#[doc = "assert_eq!(m, 0x78563412);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn swap_bytes(self) -> Self {
intrinsics::bswap(self as u32) as Self
}
/// Returns an integer with the bit locations specified by `mask` packed
/// contiguously into the least significant bits of the result.
/// ```
/// #![feature(uint_gather_scatter_bits)]
#[doc = "let n: u32 = 0b1011_1100;"]
///
/// assert_eq!(n.extract_bits(0b0010_0100), 0b0000_0011);
/// assert_eq!(n.extract_bits(0xF0), 0b0000_1011);
/// ```
#[doc(alias = "pext")]
#[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn extract_bits(self, mask: Self) -> Self {
imp::int_bits::u32::extract_impl(self as u32, mask as u32) as u32
}
/// Returns an integer with the least significant bits of `self`
/// distributed to the bit locations specified by `mask`.
/// ```
/// #![feature(uint_gather_scatter_bits)]
#[doc = "let n: u32 = 0b1010_1101;"]
///
/// assert_eq!(n.deposit_bits(0b0101_0101), 0b0101_0001);
/// assert_eq!(n.deposit_bits(0xF0), 0b1101_0000);
/// ```
#[doc(alias = "pdep")]
#[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn deposit_bits(self, mask: Self) -> Self {
imp::int_bits::u32::deposit_impl(self as u32, mask as u32) as u32
}
/// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
/// second least-significant bit becomes second most-significant bit, etc.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x12345678u32;"]
/// let m = n.reverse_bits();
///
#[doc = "assert_eq!(m, 0x1e6a2c48);"]
#[doc = "assert_eq!(0, 0u32.reverse_bits());"]
/// ```
#[stable(feature = "reverse_bits", since = "1.37.0")]
#[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn reverse_bits(self) -> Self {
intrinsics::bitreverse(self as u32) as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au32;"]
///
/// if cfg!(target_endian = "big") {
#[doc = " assert_eq!(u32::from_be(n), n)"]
/// } else {
#[doc = " assert_eq!(u32::from_be(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use]
#[inline(always)]
pub const fn from_be(x: Self) -> Self { x.swap_bytes() }
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au32;"]
///
/// if cfg!(target_endian = "little") {
#[doc = " assert_eq!(u32::from_le(n), n)"]
/// } else {
#[doc = " assert_eq!(u32::from_le(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use]
#[inline(always)]
pub const fn from_le(x: Self) -> Self { x }
/// Converts `self` to big endian from the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au32;"]
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn to_be(self) -> Self { self.swap_bytes() }
/// Converts `self` to little endian from the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au32;"]
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn to_le(self) -> Self { self }
/// Checked integer addition. Computes `self + rhs`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((u32::MAX - 2).checked_add(1), Some(u32::MAX - 1));"]
#[doc = "assert_eq!((u32::MAX - 2).checked_add(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(intrinsics::add_with_overflow(self, rhs).1) {
None
} else { Some(unsafe { intrinsics::unchecked_add(self, rhs) }) }
}
/// Strict integer addition. Computes `self + rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((u32::MAX - 2).strict_add(1), u32::MAX - 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (u32::MAX - 2).strict_add(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_add(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Unchecked integer addition. Computes `self + rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_add(y)` is semantically equivalent to calling
/// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_add`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self + rhs > u32::MAX`,"]
/// i.e. when [`checked_add`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_add`]: u32::checked_add"]
#[doc = "[`wrapping_add`]: u32::wrapping_add"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u32, rhs: u32) {
if !!lhs.overflowing_add(rhs).1 {
let msg =
"unsafe precondition(s) violated: u32::unchecked_add cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_add(self, rhs) }
}
/// Checked addition with a signed integer. Computes `self + rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u32.checked_add_signed(2), Some(3));"]
#[doc = "assert_eq!(1u32.checked_add_signed(-2), None);"]
#[doc = "assert_eq!((u32::MAX - 2).checked_add_signed(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add_signed(self, rhs: i32) -> Option<Self> {
let (a, b) = self.overflowing_add_signed(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict addition with a signed integer. Computes `self + rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u32.strict_add_signed(2), 3);"]
/// ```
///
/// The following panic because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1u32.strict_add_signed(-2);"]
/// ```
///
/// ```should_panic
#[doc = "let _ = (u32::MAX - 2).strict_add_signed(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add_signed(self, rhs: i32) -> Self {
let (a, b) = self.overflowing_add_signed(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Checked integer subtraction. Computes `self - rhs`, returning
/// `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u32.checked_sub(1), Some(0));"]
#[doc = "assert_eq!(0u32.checked_sub(1), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
if self < rhs {
None
} else { Some(unsafe { intrinsics::unchecked_sub(self, rhs) }) }
}
/// Strict integer subtraction. Computes `self - rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u32.strict_sub(1), 0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0u32.strict_sub(1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_sub(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
/// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_sub`].
///
/// If you find yourself writing code like this:
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if foo >= bar {
/// // SAFETY: just checked it will not overflow
/// let diff = unsafe { foo.unchecked_sub(bar) };
/// // ... use diff ...
/// }
/// ```
///
/// Consider changing it to
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if let Some(diff) = foo.checked_sub(bar) {
/// // ... use diff ...
/// }
/// ```
///
/// As that does exactly the same thing -- including telling the optimizer
/// that the subtraction cannot overflow -- but avoids needing `unsafe`.
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self - rhs < u32::MIN`,"]
/// i.e. when [`checked_sub`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_sub`]: u32::checked_sub"]
#[doc = "[`wrapping_sub`]: u32::wrapping_sub"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u32, rhs: u32) {
if !!lhs.overflowing_sub(rhs).1 {
let msg =
"unsafe precondition(s) violated: u32::unchecked_sub cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_sub(self, rhs) }
}
/// Checked subtraction with a signed integer. Computes `self - rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u32.checked_sub_signed(2), None);"]
#[doc = "assert_eq!(1u32.checked_sub_signed(-2), Some(3));"]
#[doc = "assert_eq!((u32::MAX - 2).checked_sub_signed(-4), None);"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub_signed(self, rhs: i32) -> Option<Self> {
let (res, overflow) = self.overflowing_sub_signed(rhs);
if !overflow { Some(res) } else { None }
}
/// Strict subtraction with a signed integer. Computes `self - rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3u32.strict_sub_signed(2), 1);"]
/// ```
///
/// The following panic because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1u32.strict_sub_signed(2);"]
/// ```
///
/// ```should_panic
#[doc = "let _ = (u32::MAX).strict_sub_signed(-1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub_signed(self, rhs: i32) -> Self {
let (a, b) = self.overflowing_sub_signed(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
#[doc =
"Checked integer subtraction. Computes `self - rhs` and checks if the result fits into an [`i32`], returning `None` if overflow occurred."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10u32.checked_signed_diff(2), Some(8));"]
#[doc = "assert_eq!(2u32.checked_signed_diff(10), Some(-8));"]
#[doc = "assert_eq!(u32::MAX.checked_signed_diff(i32::MAX as u32), None);"]
#[doc =
"assert_eq!((i32::MAX as u32).checked_signed_diff(u32::MAX), Some(i32::MIN));"]
#[doc = "assert_eq!((i32::MAX as u32 + 1).checked_signed_diff(0), None);"]
#[doc = "assert_eq!(u32::MAX.checked_signed_diff(u32::MAX), Some(0));"]
/// ```
#[stable(feature = "unsigned_signed_diff", since = "1.91.0")]
#[rustc_const_stable(feature = "unsigned_signed_diff", since = "1.91.0")]
#[inline]
pub const fn checked_signed_diff(self, rhs: Self) -> Option<i32> {
let res = self.wrapping_sub(rhs) as i32;
let overflow = (self >= rhs) == (res < 0);
if !overflow { Some(res) } else { None }
}
/// Checked integer multiplication. Computes `self * rhs`, returning
/// `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u32.checked_mul(1), Some(5));"]
#[doc = "assert_eq!(u32::MAX.checked_mul(2), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer multiplication. Computes `self * rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u32.strict_mul(1), 5);"]
/// ```
///
/// The following panics because of overflow:
///
/// ``` should_panic
#[doc = "let _ = u32::MAX.strict_mul(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_mul(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_mul(rhs);
if b { imp::overflow_panic::mul() } else { a }
}
/// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
/// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_mul`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self * rhs > u32::MAX`,"]
/// i.e. when [`checked_mul`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_mul`]: u32::checked_mul"]
#[doc = "[`wrapping_mul`]: u32::wrapping_mul"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u32, rhs: u32) {
if !!lhs.overflowing_mul(rhs).1 {
let msg =
"unsafe precondition(s) violated: u32::unchecked_mul cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_mul(self, rhs) }
}
/// Checked integer division. Computes `self / rhs`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128u32.checked_div(2), Some(64));"]
#[doc = "assert_eq!(1u32.checked_div(0), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(unsafe { intrinsics::unchecked_div(self, rhs) }) }
}
/// Strict integer division. Computes `self / rhs`.
///
/// Strict division on unsigned types is just normal division. There's no
/// way overflow could ever happen. This function exists so that all
/// operations are accounted for in the strict operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u32.strict_div(10), 10);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1u32).strict_div(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_div(self, rhs: Self) -> Self { self / rhs }
/// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128u32.checked_div_euclid(2), Some(64));"]
#[doc = "assert_eq!(1u32.checked_div_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(self.div_euclid(rhs)) }
}
/// Strict Euclidean division. Computes `self.div_euclid(rhs)`.
///
/// Strict division on unsigned types is just normal division. There's no
/// way overflow could ever happen. This function exists so that all
/// operations are accounted for in the strict operations. Since, for the
/// positive integers, all common definitions of division are equal, this
/// is exactly equal to `self.strict_div(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u32.strict_div_euclid(10), 10);"]
/// ```
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1u32).strict_div_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Checked integer division without remainder. Computes `self / rhs`,
/// returning `None` if `rhs == 0` or if `self % rhs != 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64u32.checked_div_exact(2), Some(32));"]
#[doc = "assert_eq!(64u32.checked_div_exact(32), Some(2));"]
#[doc = "assert_eq!(64u32.checked_div_exact(0), None);"]
#[doc = "assert_eq!(65u32.checked_div_exact(2), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_exact(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else {
unsafe {
if intrinsics::unlikely(intrinsics::unchecked_rem(self, rhs) != 0)
{
None
} else { Some(intrinsics::exact_div(self, rhs)) }
}
}
}
/// Integer division without remainder. Computes `self / rhs`, returning `None` if `self % rhs != 0`.
///
/// # Panics
///
/// This function will panic if `rhs == 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64u32.div_exact(2), Some(32));"]
#[doc = "assert_eq!(64u32.div_exact(32), Some(2));"]
#[doc = "assert_eq!(65u32.div_exact(2), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn div_exact(self, rhs: Self) -> Option<Self> {
if self % rhs != 0 { None } else { Some(self / rhs) }
}
/// Unchecked integer division without remainder. Computes `self / rhs`.
///
/// # Safety
///
/// This results in undefined behavior when `rhs == 0` or `self % rhs != 0`,
/// i.e. when [`checked_div_exact`](Self::checked_div_exact) would return `None`.
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_div_exact(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u32, rhs: u32) {
if !(rhs > 0 && lhs % rhs == 0) {
let msg =
"unsafe precondition(s) violated: u32::unchecked_div_exact divide by zero or leave a remainder\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::exact_div(self, rhs) }
}
/// Checked integer remainder. Computes `self % rhs`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u32.checked_rem(2), Some(1));"]
#[doc = "assert_eq!(5u32.checked_rem(0), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(unsafe { intrinsics::unchecked_rem(self, rhs) }) }
}
/// Strict integer remainder. Computes `self % rhs`.
///
/// Strict remainder calculation on unsigned types is just the regular
/// remainder calculation. There's no way overflow could ever happen.
/// This function exists so that all operations are accounted for in the
/// strict operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u32.strict_rem(10), 0);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5u32.strict_rem(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_rem(self, rhs: Self) -> Self { self % rhs }
/// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u32.checked_rem_euclid(2), Some(1));"]
#[doc = "assert_eq!(5u32.checked_rem_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(self.rem_euclid(rhs)) }
}
/// Strict Euclidean modulo. Computes `self.rem_euclid(rhs)`.
///
/// Strict modulo calculation on unsigned types is just the regular
/// remainder calculation. There's no way overflow could ever happen.
/// This function exists so that all operations are accounted for in the
/// strict operations. Since, for the positive integers, all common
/// definitions of division are equal, this is exactly equal to
/// `self.strict_rem(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u32.strict_rem_euclid(10), 0);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5u32.strict_rem_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Same value as `self | other`, but UB if any bit position is set in both inputs.
///
/// This is a situational micro-optimization for places where you'd rather
/// use addition on some platforms and bitwise or on other platforms, based
/// on exactly which instructions combine better with whatever else you're
/// doing. Note that there's no reason to bother using this for places
/// where it's clear from the operations involved that they can't overlap.
/// For example, if you're combining `u16`s into a `u32` with
/// `((a as u32) << 16) | (b as u32)`, that's fine, as the backend will
/// know those sides of the `|` are disjoint without needing help.
///
/// # Examples
///
/// ```
/// #![feature(disjoint_bitor)]
///
/// // SAFETY: `1` and `4` have no bits in common.
/// unsafe {
#[doc = " assert_eq!(1_u32.unchecked_disjoint_bitor(4), 5);"]
/// }
/// ```
///
/// # Safety
///
/// Requires that `(self & other) == 0`, otherwise it's immediate UB.
///
/// Equivalently, requires that `(self | other) == (self + other)`.
#[unstable(feature = "disjoint_bitor", issue = "135758")]
#[rustc_const_unstable(feature = "disjoint_bitor", issue = "135758")]
#[inline]
pub const unsafe fn unchecked_disjoint_bitor(self, other: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u32, rhs: u32) {
if !((lhs & rhs) == 0) {
let msg =
"unsafe precondition(s) violated: u32::unchecked_disjoint_bitor cannot have overlapping bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, other);
}
};
unsafe { intrinsics::disjoint_bitor(self, other) }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// This method might not be optimized owing to implementation details;
/// `ilog2` can produce results more efficiently for base 2, and `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));"]
/// ```
#[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 == 2 {
return self.checked_ilog2();
} else 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.
///
/// # 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> {
if exp == 0 { return Some(1); }
let mut base = self;
let mut acc: Self = 1;
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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc: Self = 1;
loop {
if (exp & 1) == 1 {
acc = acc.strict_mul(base);
if exp == 1 { return acc; }
}
exp /= 2;
base = base.strict_mul(base);
}
}
/// 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. The behaviour 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. The behaviour 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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc: Self = 1;
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 { acc = acc.wrapping_mul(base); }
exp /= 2;
base = base.wrapping_mul(base);
}
acc.wrapping_mul(base)
} else {
loop {
if (exp & 1) == 1 {
acc = acc.wrapping_mul(base);
if exp == 1 { return acc; }
}
exp /= 2;
base = base.wrapping_mul(base);
}
}
}
/// 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) {
if exp == 0 { return (1, false); }
let mut base = self;
let mut acc: Self = 1;
let mut overflown = false;
let mut r;
loop {
if (exp & 1) == 1 {
r = acc.overflowing_mul(base);
if exp == 1 { r.1 |= overflown; return r; }
acc = r.0;
overflown |= r.1;
}
exp /= 2;
r = base.overflowing_mul(base);
base = r.0;
overflown |= r.1;
}
}
/// 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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc = 1;
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 { acc = acc * base; }
exp /= 2;
base = base * base;
}
acc * base
} else {
loop {
if (exp & 1) == 1 {
acc = acc * base;
if exp == 1 { return acc; }
}
exp /= 2;
base = base * base;
}
}
}
/// Returns the square root of the number, rounded down.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10u32.isqrt(), 3);"]
/// ```
#[stable(feature = "isqrt", since = "1.84.0")]
#[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn isqrt(self) -> Self {
let result = imp::int_sqrt::u32(self as u32) as Self;
unsafe {
const MAX_RESULT: u32 = imp::int_sqrt::u32(<u32>::MAX) as u32;
crate::hint::assert_unchecked(result <= MAX_RESULT)
}
if self >= 1 { unsafe { crate::hint::assert_unchecked(result >= 1) } }
unsafe {
crate::hint::assert_unchecked(result.unchecked_mul(result) <= self);
crate::hint::assert_unchecked(result <= self);
}
result
}
/// Performs Euclidean division.
///
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self / rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7u32.div_euclid(4), 1); // or any other integer type"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Calculates the least remainder of `self` when divided by
/// `rhs`.
///
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self % rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7u32.rem_euclid(4), 3); // or any other integer type"]
/// ```
#[doc(alias = "modulo", alias = "mod")]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
///
/// This is the same as performing `self / rhs` for all unsigned integers.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "assert_eq!(7_u32.div_floor(4), 1);"]
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn div_floor(self, rhs: Self) -> Self { self / rhs }
/// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7_u32.div_ceil(4), 2);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_ceil(self, rhs: Self) -> Self {
let d = self / rhs;
let r = self % rhs;
if r > 0 { d + 1 } else { d }
}
/// Calculates the smallest value greater than or equal to `self` that
/// is a multiple of `rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// On overflow, this function will panic if overflow checks are enabled (default in debug
/// mode) and wrap if overflow checks are disabled (default in release mode).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(16_u32.next_multiple_of(8), 16);"]
#[doc = "assert_eq!(23_u32.next_multiple_of(8), 24);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_multiple_of(self, rhs: Self) -> Self {
match self % rhs { 0 => self, r => self + (rhs - r), }
}
/// Calculates the smallest value greater than or equal to `self` that
/// is a multiple of `rhs`. Returns `None` if `rhs` is zero or the
/// operation would result in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(16_u32.checked_next_multiple_of(8), Some(16));"]
#[doc = "assert_eq!(23_u32.checked_next_multiple_of(8), Some(24));"]
#[doc = "assert_eq!(1_u32.checked_next_multiple_of(0), None);"]
#[doc = "assert_eq!(u32::MAX.checked_next_multiple_of(2), None);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
match match self.checked_rem(rhs) { Some(x) => x, None => return None, } {
0 => Some(self),
r => self.checked_add(rhs - r),
}
}
/// Returns `true` if `self` is an integer multiple of `rhs`, and false otherwise.
///
/// This function is equivalent to `self % rhs == 0`, except that it will not panic
/// for `rhs == 0`. Instead, `0.is_multiple_of(0) == true`, and for any non-zero `n`,
/// `n.is_multiple_of(0) == false`.
///
/// # Examples
///
/// ```
#[doc = "assert!(6_u32.is_multiple_of(2));"]
#[doc = "assert!(!5_u32.is_multiple_of(2));"]
///
#[doc = "assert!(0_u32.is_multiple_of(0));"]
#[doc = "assert!(!6_u32.is_multiple_of(0));"]
/// ```
#[stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
#[rustc_const_stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
#[must_use]
#[inline]
pub const fn is_multiple_of(self, rhs: Self) -> bool {
match rhs { 0 => self == 0, _ => self % rhs == 0, }
}
/// Returns `true` if and only if `self == 2^k` for some unsigned integer `k`.
///
/// # Examples
///
/// ```
#[doc = "assert!(16u32.is_power_of_two());"]
#[doc = "assert!(!10u32.is_power_of_two());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
#[inline(always)]
pub const fn is_power_of_two(self) -> bool { self.count_ones() == 1 }
#[inline]
const fn one_less_than_next_power_of_two(self) -> Self {
if self <= 1 { return 0; }
let p = self - 1;
let z = unsafe { intrinsics::ctlz_nonzero(p) };
<u32>::MAX >> z
}
/// Returns the smallest power of two greater than or equal to `self`.
///
/// When return value overflows (i.e., `self > (1 << (N-1))` for type
/// `uN`), it panics in debug mode and the return value is wrapped to 0 in
/// release mode (the only situation in which this method can return 0).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u32.next_power_of_two(), 2);"]
#[doc = "assert_eq!(3u32.next_power_of_two(), 4);"]
#[doc = "assert_eq!(0u32.next_power_of_two(), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_power_of_two(self) -> Self {
self.one_less_than_next_power_of_two() + 1
}
/// Returns the smallest power of two greater than or equal to `self`. If
/// the next power of two is greater than the type's maximum value,
/// `None` is returned, otherwise the power of two is wrapped in `Some`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u32.checked_next_power_of_two(), Some(2));"]
#[doc = "assert_eq!(3u32.checked_next_power_of_two(), Some(4));"]
#[doc = "assert_eq!(u32::MAX.checked_next_power_of_two(), None);"]
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn checked_next_power_of_two(self) -> Option<Self> {
self.one_less_than_next_power_of_two().checked_add(1)
}
/// Returns the smallest power of two greater than or equal to `n`. If
/// the next power of two is greater than the type's maximum value,
/// the return value is wrapped to `0`.
///
/// # Examples
///
/// ```
/// #![feature(wrapping_next_power_of_two)]
///
#[doc = "assert_eq!(2u32.wrapping_next_power_of_two(), 2);"]
#[doc = "assert_eq!(3u32.wrapping_next_power_of_two(), 4);"]
#[doc = "assert_eq!(u32::MAX.wrapping_next_power_of_two(), 0);"]
/// ```
#[inline]
#[unstable(feature = "wrapping_next_power_of_two", issue = "32463", reason =
"needs decision on wrapping behavior")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn wrapping_next_power_of_two(self) -> Self {
self.one_less_than_next_power_of_two().wrapping_add(1)
}
/// Returns the memory representation of this integer as a byte array in
/// big-endian (network) byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12345678u32.to_be_bytes();"]
#[doc = "assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
self.to_be().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// little-endian byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12345678u32.to_le_bytes();"]
#[doc = "assert_eq!(bytes, [0x78, 0x56, 0x34, 0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
self.to_le().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code
/// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
/// instead.
///
#[doc = ""]
///
/// [`to_be_bytes`]: Self::to_be_bytes
/// [`to_le_bytes`]: Self::to_le_bytes
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12345678u32.to_ne_bytes();"]
/// assert_eq!(
/// bytes,
/// if cfg!(target_endian = "big") {
#[doc = " [0x12, 0x34, 0x56, 0x78]"]
/// } else {
#[doc = " [0x78, 0x56, 0x34, 0x12]"]
/// }
/// );
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[allow(unnecessary_transmutes)]
#[inline]
pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
unsafe { mem::transmute(self) }
}
/// Creates a native endian integer value from its representation
/// as a byte array in big endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = u32::from_be_bytes([0x12, 0x34, 0x56, 0x78]);"]
#[doc = "assert_eq!(value, 0x12345678);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_be_u32(input: &mut &[u8]) -> u32 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u32>());"]
/// *input = rest;
#[doc = " u32::from_be_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_be(Self::from_ne_bytes(bytes))
}
/// Creates a native endian integer value from its representation
/// as a byte array in little endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = u32::from_le_bytes([0x78, 0x56, 0x34, 0x12]);"]
#[doc = "assert_eq!(value, 0x12345678);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_le_u32(input: &mut &[u8]) -> u32 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u32>());"]
/// *input = rest;
#[doc = " u32::from_le_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_le(Self::from_ne_bytes(bytes))
}
/// Creates a native endian integer value from its memory representation
/// as a byte array in native endianness.
///
/// As the target platform's native endianness is used, portable code
/// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
/// appropriate instead.
///
/// [`from_be_bytes`]: Self::from_be_bytes
/// [`from_le_bytes`]: Self::from_le_bytes
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = u32::from_ne_bytes(if cfg!(target_endian = \"big\") {"]
#[doc = " [0x12, 0x34, 0x56, 0x78]"]
/// } else {
#[doc = " [0x78, 0x56, 0x34, 0x12]"]
/// });
#[doc = "assert_eq!(value, 0x12345678);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_ne_u32(input: &mut &[u8]) -> u32 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u32>());"]
/// *input = rest;
#[doc = " u32::from_ne_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use]
#[inline]
pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
unsafe { mem::transmute(bytes) }
}
/// New code should prefer to use
#[doc = "[`u32::MIN`] instead."]
///
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_promotable]
#[inline(always)]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MIN` associated constant on this type")]
#[rustc_diagnostic_item = "u32_legacy_fn_min_value"]
pub const fn min_value() -> Self { Self::MIN }
/// New code should prefer to use
#[doc = "[`u32::MAX`] instead."]
///
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_promotable]
#[inline(always)]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MAX` associated constant on this type")]
#[rustc_diagnostic_item = "u32_legacy_fn_max_value"]
pub const fn max_value() -> Self { Self::MAX }
/// Truncate an integer to an integer of the same size or smaller, preserving the least
/// significant bits.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u8, 120u32.truncate());"]
/// assert_eq!(120u8, 376u32.truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
/// instead of truncating.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u8, 120u32.saturating_truncate());"]
/// assert_eq!(255u8, 376u32.saturating_truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn saturating_truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_saturating_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
/// is outside the bounds of the smaller type.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(Some(120u8), 120u32.checked_truncate());"]
/// assert_eq!(None, 376u32.checked_truncate::<u8>());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn checked_truncate<Target>(self) -> Option<Target> where
Self: [const] traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_checked_truncate(self)
}
/// Widen to an integer of the same size or larger, preserving its value.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u128, 120u8.widen());"]
/// ```
#[must_use =
"this returns the widened value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn widen<Target>(self) -> Target where Self: [const]
traits::WidenTarget<Target> {
traits::WidenTarget::internal_widen(self)
}uint_impl! {
1287Self = u32,
1288 ActualT = u32,
1289 SignedT = i32,
1290 BITS = 32,
1291 BITS_MINUS_ONE = 31,
1292 MAX = 4294967295,
1293 rot = 8,
1294 rot_op = "0x10000b3",
1295 rot_result = "0xb301",
1296 fsh_op = "0x2fe78e45",
1297 fshl_result = "0xb32f",
1298 fshr_result = "0xb32fe78e",
1299 clmul_lhs = "0x56789012",
1300 clmul_rhs = "0xf52ecd34",
1301 clmul_result = "0x9b980928",
1302 swap_op = "0x12345678",
1303 swapped = "0x78563412",
1304 reversed = "0x1e6a2c48",
1305 le_bytes = "[0x78, 0x56, 0x34, 0x12]",
1306 be_bytes = "[0x12, 0x34, 0x56, 0x78]",
1307 to_xe_bytes_doc = "",
1308 from_xe_bytes_doc = "",
1309 bound_condition = "",
1310 }1311/// 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 }1312/// 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 }1313/// 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 }1314/// 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 }1315}
13161317impl u64 {
1318/// 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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "uint_bit_width", since =
"CURRENT_RUSTC_VERSION")]
#[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 =
"CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"CURRENT_RUSTC_VERSION")]
#[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 =
"CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"CURRENT_RUSTC_VERSION")]
#[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`.
///
/// # 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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since =
"CURRENT_RUSTC_VERSION")]
#[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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since =
"CURRENT_RUSTC_VERSION")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn lowest_one(self) -> Option<u32> {
match NonZero::new(self) {
Some(v) => Some(v.lowest_one()),
None => None,
}
}
/// Returns the bit pattern of `self` reinterpreted as a signed integer of the same size.
///
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
/// the same.
///
/// # Examples
///
/// ```
#[doc = "let n = u64::MAX;"]
///
#[doc = "assert_eq!(n.cast_signed(), -1i64);"]
/// ```
#[stable(feature = "integer_sign_cast", since = "1.87.0")]
#[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_signed(self) -> i64 { self as i64 }
/// Saturating conversion of `self` to a signed integer of the same size.
///
/// The signed integer's maximum value is returned if `self` is larger
/// than the maximum positive value representable by the signed integer.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`checked_cast_signed`](Self::checked_cast_signed),
/// or [`strict_cast_signed`](Self::strict_cast_signed).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = u64::MAX;"]
///
#[doc = "assert_eq!(n.saturating_cast_signed(), i64::MAX);"]
#[doc = "assert_eq!(64u64.saturating_cast_signed(), 64i64);"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_cast_signed(self) -> i64 {
if self <= <i64>::MAX.cast_unsigned() {
self.cast_signed()
} else { <i64>::MAX }
}
/// Checked conversion of `self` to a signed integer of the same size,
/// returning `None` if `self` is larger than the signed integer's
/// maximum value.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`saturating_cast_signed`](Self::saturating_cast_signed),
/// or [`strict_cast_signed`](Self::strict_cast_signed).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = u64::MAX;"]
///
#[doc = "assert_eq!(n.checked_cast_signed(), None);"]
#[doc = "assert_eq!(64u64.checked_cast_signed(), Some(64i64));"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn checked_cast_signed(self) -> Option<i64> {
if self <= <i64>::MAX.cast_unsigned() {
Some(self.cast_signed())
} else { None }
}
/// Strict conversion of `self` to a signed integer of the same size,
/// which panics if `self` is larger than the signed integer's maximum
/// value.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`checked_cast_signed`](Self::checked_cast_signed),
/// or [`saturating_cast_signed`](Self::saturating_cast_signed).
///
/// # Examples
///
/// ```should_panic
/// #![feature(integer_cast_extras)]
#[doc = "let _ = u64::MAX.strict_cast_signed();"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_cast_signed(self) -> i64 {
match self.checked_cast_signed() {
Some(n) => n,
None => imp::overflow_panic::cast_integer(),
}
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `<<` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0xaa00000000006e1u64;"]
#[doc = "let m = 0x6e10aa;"]
///
#[doc = "assert_eq!(n.rotate_left(12), m);"]
#[doc = "assert_eq!(n.rotate_left(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
pub const fn rotate_left(self, n: u32) -> Self {
return intrinsics::rotate_left(self, n);
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `>>` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x6e10aau64;"]
#[doc = "let m = 0xaa00000000006e1;"]
///
#[doc = "assert_eq!(n.rotate_right(12), m);"]
#[doc = "assert_eq!(n.rotate_right(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
pub const fn rotate_right(self, n: u32) -> Self {
return intrinsics::rotate_right(self, n);
}
/// Performs a left funnel shift (concatenates `self` with `rhs`, with `self`
/// making up the most significant half, then shifts the combined value left
/// by `n`, and most significant half is extracted to produce the result).
///
/// Please note this isn't the same operation as the `<<` shifting operator or
/// [`rotate_left`](Self::rotate_left), although `a.funnel_shl(a, n)` is *equivalent*
/// to `a.rotate_left(n)`.
///
/// # Panics
///
/// If `n` is greater than or equal to the number of bits in `self`
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(funnel_shifts)]
#[doc = "let a = 0xaa00000000006e1u64;"]
#[doc = "let b = 0x2fe78e45983acd98u64;"]
#[doc = "let m = 0x6e12fe;"]
///
#[doc = "assert_eq!(a.funnel_shl(b, 12), m);"]
/// ```
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn funnel_shl(self, rhs: Self, n: u32) -> Self {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift left with overflow"));
}
};
unsafe { self.unchecked_funnel_shl(rhs, n) }
}
/// Performs a right funnel shift (concatenates `self` and `rhs`, with `self`
/// making up the most significant half, then shifts the combined value right
/// by `n`, and least significant half is extracted to produce the result).
///
/// Please note this isn't the same operation as the `>>` shifting operator or
/// [`rotate_right`](Self::rotate_right), although `a.funnel_shr(a, n)` is *equivalent*
/// to `a.rotate_right(n)`.
///
/// # Panics
///
/// If `n` is greater than or equal to the number of bits in `self`
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(funnel_shifts)]
#[doc = "let a = 0xaa00000000006e1u64;"]
#[doc = "let b = 0x2fe78e45983acd98u64;"]
#[doc = "let m = 0x6e12fe78e45983ac;"]
///
#[doc = "assert_eq!(a.funnel_shr(b, 12), m);"]
/// ```
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn funnel_shr(self, rhs: Self, n: u32) -> Self {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift right with overflow"));
}
};
unsafe { self.unchecked_funnel_shr(rhs, n) }
}
/// Unchecked funnel shift left.
///
/// # Safety
///
/// This results in undefined behavior if `n` is greater than or equal to
#[doc = "`u64::BITS`,"]
/// i.e. when [`funnel_shl`](Self::funnel_shl) would panic.
///
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_funnel_shl(self, low: Self, n: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(n: u32) {
if !(n < <u64>::BITS) {
let msg =
"unsafe precondition(s) violated: u64::unchecked_funnel_shl cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(n); }
};
unsafe { intrinsics::unchecked_funnel_shl(self, low, n) }
}
/// Unchecked funnel shift right.
///
/// # Safety
///
/// This results in undefined behavior if `n` is greater than or equal to
#[doc = "`u64::BITS`,"]
/// i.e. when [`funnel_shr`](Self::funnel_shr) would panic.
///
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_funnel_shr(self, low: Self, n: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(n: u32) {
if !(n < <u64>::BITS) {
let msg =
"unsafe precondition(s) violated: u64::unchecked_funnel_shr cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(n); }
};
unsafe { intrinsics::unchecked_funnel_shr(self, low, n) }
}
/// Performs a carry-less multiplication, returning the lower bits.
///
/// This operation is similar to long multiplication in base 2, except that exclusive or is
/// used instead of addition. The implementation is equivalent to:
///
/// ```no_run
#[doc = "pub fn carryless_mul(lhs: u64, rhs: u64) -> u64{"]
/// let mut retval = 0;
#[doc = " for i in 0..u64::BITS {"]
/// if (rhs >> i) & 1 != 0 {
/// // long multiplication would use +=
/// retval ^= lhs << i;
/// }
/// }
/// retval
/// }
/// ```
///
/// The actual implementation is more efficient, and on some platforms lowers directly to a
/// dedicated instruction.
///
/// # Uses
///
/// Carryless multiplication can be used to turn a bitmask of quote characters into a
/// bit mask of characters surrounded by quotes:
///
/// ```no_run
/// r#"abc xxx "foobar" zzz "a"!"#; // input string
/// 0b0000000010000001000001010; // quote_mask
/// 0b0000000001111110000000100; // quote_mask.carryless_mul(!0) & !quote_mask
/// ```
///
/// Another use is in cryptography, where carryless multiplication allows for efficient
/// implementations of polynomial multiplication in `GF(2)[X]`, the polynomial ring
/// over `GF(2)`.
///
/// # Examples
///
/// ```
/// #![feature(uint_carryless_mul)]
///
#[doc = "let a = 0x7890123456789012u64;"]
#[doc = "let b = 0xdd358416f52ecd34u64;"]
///
#[doc = "assert_eq!(a.carryless_mul(b), 0xa6299579b980928);"]
/// ```
#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
#[doc(alias = "clmul")]
#[unstable(feature = "uint_carryless_mul", issue = "152080")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn carryless_mul(self, rhs: Self) -> Self {
intrinsics::carryless_mul(self, rhs)
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1234567890123456u64;"]
/// let m = n.swap_bytes();
///
#[doc = "assert_eq!(m, 0x5634129078563412);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn swap_bytes(self) -> Self {
intrinsics::bswap(self as u64) as Self
}
/// Returns an integer with the bit locations specified by `mask` packed
/// contiguously into the least significant bits of the result.
/// ```
/// #![feature(uint_gather_scatter_bits)]
#[doc = "let n: u64 = 0b1011_1100;"]
///
/// assert_eq!(n.extract_bits(0b0010_0100), 0b0000_0011);
/// assert_eq!(n.extract_bits(0xF0), 0b0000_1011);
/// ```
#[doc(alias = "pext")]
#[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn extract_bits(self, mask: Self) -> Self {
imp::int_bits::u64::extract_impl(self as u64, mask as u64) as u64
}
/// Returns an integer with the least significant bits of `self`
/// distributed to the bit locations specified by `mask`.
/// ```
/// #![feature(uint_gather_scatter_bits)]
#[doc = "let n: u64 = 0b1010_1101;"]
///
/// assert_eq!(n.deposit_bits(0b0101_0101), 0b0101_0001);
/// assert_eq!(n.deposit_bits(0xF0), 0b1101_0000);
/// ```
#[doc(alias = "pdep")]
#[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn deposit_bits(self, mask: Self) -> Self {
imp::int_bits::u64::deposit_impl(self as u64, mask as u64) as u64
}
/// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
/// second least-significant bit becomes second most-significant bit, etc.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1234567890123456u64;"]
/// let m = n.reverse_bits();
///
#[doc = "assert_eq!(m, 0x6a2c48091e6a2c48);"]
#[doc = "assert_eq!(0, 0u64.reverse_bits());"]
/// ```
#[stable(feature = "reverse_bits", since = "1.37.0")]
#[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn reverse_bits(self) -> Self {
intrinsics::bitreverse(self as u64) as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au64;"]
///
/// if cfg!(target_endian = "big") {
#[doc = " assert_eq!(u64::from_be(n), n)"]
/// } else {
#[doc = " assert_eq!(u64::from_be(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use]
#[inline(always)]
pub const fn from_be(x: Self) -> Self { x.swap_bytes() }
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au64;"]
///
/// if cfg!(target_endian = "little") {
#[doc = " assert_eq!(u64::from_le(n), n)"]
/// } else {
#[doc = " assert_eq!(u64::from_le(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use]
#[inline(always)]
pub const fn from_le(x: Self) -> Self { x }
/// Converts `self` to big endian from the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au64;"]
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn to_be(self) -> Self { self.swap_bytes() }
/// Converts `self` to little endian from the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au64;"]
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn to_le(self) -> Self { self }
/// Checked integer addition. Computes `self + rhs`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((u64::MAX - 2).checked_add(1), Some(u64::MAX - 1));"]
#[doc = "assert_eq!((u64::MAX - 2).checked_add(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(intrinsics::add_with_overflow(self, rhs).1) {
None
} else { Some(unsafe { intrinsics::unchecked_add(self, rhs) }) }
}
/// Strict integer addition. Computes `self + rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((u64::MAX - 2).strict_add(1), u64::MAX - 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (u64::MAX - 2).strict_add(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_add(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Unchecked integer addition. Computes `self + rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_add(y)` is semantically equivalent to calling
/// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_add`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self + rhs > u64::MAX`,"]
/// i.e. when [`checked_add`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_add`]: u64::checked_add"]
#[doc = "[`wrapping_add`]: u64::wrapping_add"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u64, rhs: u64) {
if !!lhs.overflowing_add(rhs).1 {
let msg =
"unsafe precondition(s) violated: u64::unchecked_add cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_add(self, rhs) }
}
/// Checked addition with a signed integer. Computes `self + rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u64.checked_add_signed(2), Some(3));"]
#[doc = "assert_eq!(1u64.checked_add_signed(-2), None);"]
#[doc = "assert_eq!((u64::MAX - 2).checked_add_signed(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add_signed(self, rhs: i64) -> Option<Self> {
let (a, b) = self.overflowing_add_signed(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict addition with a signed integer. Computes `self + rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u64.strict_add_signed(2), 3);"]
/// ```
///
/// The following panic because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1u64.strict_add_signed(-2);"]
/// ```
///
/// ```should_panic
#[doc = "let _ = (u64::MAX - 2).strict_add_signed(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add_signed(self, rhs: i64) -> Self {
let (a, b) = self.overflowing_add_signed(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Checked integer subtraction. Computes `self - rhs`, returning
/// `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u64.checked_sub(1), Some(0));"]
#[doc = "assert_eq!(0u64.checked_sub(1), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
if self < rhs {
None
} else { Some(unsafe { intrinsics::unchecked_sub(self, rhs) }) }
}
/// Strict integer subtraction. Computes `self - rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u64.strict_sub(1), 0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0u64.strict_sub(1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_sub(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
/// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_sub`].
///
/// If you find yourself writing code like this:
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if foo >= bar {
/// // SAFETY: just checked it will not overflow
/// let diff = unsafe { foo.unchecked_sub(bar) };
/// // ... use diff ...
/// }
/// ```
///
/// Consider changing it to
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if let Some(diff) = foo.checked_sub(bar) {
/// // ... use diff ...
/// }
/// ```
///
/// As that does exactly the same thing -- including telling the optimizer
/// that the subtraction cannot overflow -- but avoids needing `unsafe`.
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self - rhs < u64::MIN`,"]
/// i.e. when [`checked_sub`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_sub`]: u64::checked_sub"]
#[doc = "[`wrapping_sub`]: u64::wrapping_sub"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u64, rhs: u64) {
if !!lhs.overflowing_sub(rhs).1 {
let msg =
"unsafe precondition(s) violated: u64::unchecked_sub cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_sub(self, rhs) }
}
/// Checked subtraction with a signed integer. Computes `self - rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u64.checked_sub_signed(2), None);"]
#[doc = "assert_eq!(1u64.checked_sub_signed(-2), Some(3));"]
#[doc = "assert_eq!((u64::MAX - 2).checked_sub_signed(-4), None);"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub_signed(self, rhs: i64) -> Option<Self> {
let (res, overflow) = self.overflowing_sub_signed(rhs);
if !overflow { Some(res) } else { None }
}
/// Strict subtraction with a signed integer. Computes `self - rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3u64.strict_sub_signed(2), 1);"]
/// ```
///
/// The following panic because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1u64.strict_sub_signed(2);"]
/// ```
///
/// ```should_panic
#[doc = "let _ = (u64::MAX).strict_sub_signed(-1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub_signed(self, rhs: i64) -> Self {
let (a, b) = self.overflowing_sub_signed(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
#[doc =
"Checked integer subtraction. Computes `self - rhs` and checks if the result fits into an [`i64`], returning `None` if overflow occurred."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10u64.checked_signed_diff(2), Some(8));"]
#[doc = "assert_eq!(2u64.checked_signed_diff(10), Some(-8));"]
#[doc = "assert_eq!(u64::MAX.checked_signed_diff(i64::MAX as u64), None);"]
#[doc =
"assert_eq!((i64::MAX as u64).checked_signed_diff(u64::MAX), Some(i64::MIN));"]
#[doc = "assert_eq!((i64::MAX as u64 + 1).checked_signed_diff(0), None);"]
#[doc = "assert_eq!(u64::MAX.checked_signed_diff(u64::MAX), Some(0));"]
/// ```
#[stable(feature = "unsigned_signed_diff", since = "1.91.0")]
#[rustc_const_stable(feature = "unsigned_signed_diff", since = "1.91.0")]
#[inline]
pub const fn checked_signed_diff(self, rhs: Self) -> Option<i64> {
let res = self.wrapping_sub(rhs) as i64;
let overflow = (self >= rhs) == (res < 0);
if !overflow { Some(res) } else { None }
}
/// Checked integer multiplication. Computes `self * rhs`, returning
/// `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u64.checked_mul(1), Some(5));"]
#[doc = "assert_eq!(u64::MAX.checked_mul(2), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer multiplication. Computes `self * rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u64.strict_mul(1), 5);"]
/// ```
///
/// The following panics because of overflow:
///
/// ``` should_panic
#[doc = "let _ = u64::MAX.strict_mul(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_mul(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_mul(rhs);
if b { imp::overflow_panic::mul() } else { a }
}
/// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
/// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_mul`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self * rhs > u64::MAX`,"]
/// i.e. when [`checked_mul`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_mul`]: u64::checked_mul"]
#[doc = "[`wrapping_mul`]: u64::wrapping_mul"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u64, rhs: u64) {
if !!lhs.overflowing_mul(rhs).1 {
let msg =
"unsafe precondition(s) violated: u64::unchecked_mul cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_mul(self, rhs) }
}
/// Checked integer division. Computes `self / rhs`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128u64.checked_div(2), Some(64));"]
#[doc = "assert_eq!(1u64.checked_div(0), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(unsafe { intrinsics::unchecked_div(self, rhs) }) }
}
/// Strict integer division. Computes `self / rhs`.
///
/// Strict division on unsigned types is just normal division. There's no
/// way overflow could ever happen. This function exists so that all
/// operations are accounted for in the strict operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u64.strict_div(10), 10);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1u64).strict_div(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_div(self, rhs: Self) -> Self { self / rhs }
/// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128u64.checked_div_euclid(2), Some(64));"]
#[doc = "assert_eq!(1u64.checked_div_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(self.div_euclid(rhs)) }
}
/// Strict Euclidean division. Computes `self.div_euclid(rhs)`.
///
/// Strict division on unsigned types is just normal division. There's no
/// way overflow could ever happen. This function exists so that all
/// operations are accounted for in the strict operations. Since, for the
/// positive integers, all common definitions of division are equal, this
/// is exactly equal to `self.strict_div(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u64.strict_div_euclid(10), 10);"]
/// ```
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1u64).strict_div_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Checked integer division without remainder. Computes `self / rhs`,
/// returning `None` if `rhs == 0` or if `self % rhs != 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64u64.checked_div_exact(2), Some(32));"]
#[doc = "assert_eq!(64u64.checked_div_exact(32), Some(2));"]
#[doc = "assert_eq!(64u64.checked_div_exact(0), None);"]
#[doc = "assert_eq!(65u64.checked_div_exact(2), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_exact(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else {
unsafe {
if intrinsics::unlikely(intrinsics::unchecked_rem(self, rhs) != 0)
{
None
} else { Some(intrinsics::exact_div(self, rhs)) }
}
}
}
/// Integer division without remainder. Computes `self / rhs`, returning `None` if `self % rhs != 0`.
///
/// # Panics
///
/// This function will panic if `rhs == 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64u64.div_exact(2), Some(32));"]
#[doc = "assert_eq!(64u64.div_exact(32), Some(2));"]
#[doc = "assert_eq!(65u64.div_exact(2), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn div_exact(self, rhs: Self) -> Option<Self> {
if self % rhs != 0 { None } else { Some(self / rhs) }
}
/// Unchecked integer division without remainder. Computes `self / rhs`.
///
/// # Safety
///
/// This results in undefined behavior when `rhs == 0` or `self % rhs != 0`,
/// i.e. when [`checked_div_exact`](Self::checked_div_exact) would return `None`.
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_div_exact(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u64, rhs: u64) {
if !(rhs > 0 && lhs % rhs == 0) {
let msg =
"unsafe precondition(s) violated: u64::unchecked_div_exact divide by zero or leave a remainder\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::exact_div(self, rhs) }
}
/// Checked integer remainder. Computes `self % rhs`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u64.checked_rem(2), Some(1));"]
#[doc = "assert_eq!(5u64.checked_rem(0), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(unsafe { intrinsics::unchecked_rem(self, rhs) }) }
}
/// Strict integer remainder. Computes `self % rhs`.
///
/// Strict remainder calculation on unsigned types is just the regular
/// remainder calculation. There's no way overflow could ever happen.
/// This function exists so that all operations are accounted for in the
/// strict operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u64.strict_rem(10), 0);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5u64.strict_rem(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_rem(self, rhs: Self) -> Self { self % rhs }
/// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u64.checked_rem_euclid(2), Some(1));"]
#[doc = "assert_eq!(5u64.checked_rem_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(self.rem_euclid(rhs)) }
}
/// Strict Euclidean modulo. Computes `self.rem_euclid(rhs)`.
///
/// Strict modulo calculation on unsigned types is just the regular
/// remainder calculation. There's no way overflow could ever happen.
/// This function exists so that all operations are accounted for in the
/// strict operations. Since, for the positive integers, all common
/// definitions of division are equal, this is exactly equal to
/// `self.strict_rem(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u64.strict_rem_euclid(10), 0);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5u64.strict_rem_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Same value as `self | other`, but UB if any bit position is set in both inputs.
///
/// This is a situational micro-optimization for places where you'd rather
/// use addition on some platforms and bitwise or on other platforms, based
/// on exactly which instructions combine better with whatever else you're
/// doing. Note that there's no reason to bother using this for places
/// where it's clear from the operations involved that they can't overlap.
/// For example, if you're combining `u16`s into a `u32` with
/// `((a as u32) << 16) | (b as u32)`, that's fine, as the backend will
/// know those sides of the `|` are disjoint without needing help.
///
/// # Examples
///
/// ```
/// #![feature(disjoint_bitor)]
///
/// // SAFETY: `1` and `4` have no bits in common.
/// unsafe {
#[doc = " assert_eq!(1_u64.unchecked_disjoint_bitor(4), 5);"]
/// }
/// ```
///
/// # Safety
///
/// Requires that `(self & other) == 0`, otherwise it's immediate UB.
///
/// Equivalently, requires that `(self | other) == (self + other)`.
#[unstable(feature = "disjoint_bitor", issue = "135758")]
#[rustc_const_unstable(feature = "disjoint_bitor", issue = "135758")]
#[inline]
pub const unsafe fn unchecked_disjoint_bitor(self, other: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u64, rhs: u64) {
if !((lhs & rhs) == 0) {
let msg =
"unsafe precondition(s) violated: u64::unchecked_disjoint_bitor cannot have overlapping bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, other);
}
};
unsafe { intrinsics::disjoint_bitor(self, other) }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// This method might not be optimized owing to implementation details;
/// `ilog2` can produce results more efficiently for base 2, and `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));"]
/// ```
#[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 == 2 {
return self.checked_ilog2();
} else 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.
///
/// # 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> {
if exp == 0 { return Some(1); }
let mut base = self;
let mut acc: Self = 1;
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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc: Self = 1;
loop {
if (exp & 1) == 1 {
acc = acc.strict_mul(base);
if exp == 1 { return acc; }
}
exp /= 2;
base = base.strict_mul(base);
}
}
/// 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. The behaviour 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. The behaviour 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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc: Self = 1;
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 { acc = acc.wrapping_mul(base); }
exp /= 2;
base = base.wrapping_mul(base);
}
acc.wrapping_mul(base)
} else {
loop {
if (exp & 1) == 1 {
acc = acc.wrapping_mul(base);
if exp == 1 { return acc; }
}
exp /= 2;
base = base.wrapping_mul(base);
}
}
}
/// 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) {
if exp == 0 { return (1, false); }
let mut base = self;
let mut acc: Self = 1;
let mut overflown = false;
let mut r;
loop {
if (exp & 1) == 1 {
r = acc.overflowing_mul(base);
if exp == 1 { r.1 |= overflown; return r; }
acc = r.0;
overflown |= r.1;
}
exp /= 2;
r = base.overflowing_mul(base);
base = r.0;
overflown |= r.1;
}
}
/// 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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc = 1;
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 { acc = acc * base; }
exp /= 2;
base = base * base;
}
acc * base
} else {
loop {
if (exp & 1) == 1 {
acc = acc * base;
if exp == 1 { return acc; }
}
exp /= 2;
base = base * base;
}
}
}
/// Returns the square root of the number, rounded down.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10u64.isqrt(), 3);"]
/// ```
#[stable(feature = "isqrt", since = "1.84.0")]
#[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn isqrt(self) -> Self {
let result = imp::int_sqrt::u64(self as u64) as Self;
unsafe {
const MAX_RESULT: u64 = imp::int_sqrt::u64(<u64>::MAX) as u64;
crate::hint::assert_unchecked(result <= MAX_RESULT)
}
if self >= 1 { unsafe { crate::hint::assert_unchecked(result >= 1) } }
unsafe {
crate::hint::assert_unchecked(result.unchecked_mul(result) <= self);
crate::hint::assert_unchecked(result <= self);
}
result
}
/// Performs Euclidean division.
///
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self / rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7u64.div_euclid(4), 1); // or any other integer type"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Calculates the least remainder of `self` when divided by
/// `rhs`.
///
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self % rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7u64.rem_euclid(4), 3); // or any other integer type"]
/// ```
#[doc(alias = "modulo", alias = "mod")]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
///
/// This is the same as performing `self / rhs` for all unsigned integers.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "assert_eq!(7_u64.div_floor(4), 1);"]
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn div_floor(self, rhs: Self) -> Self { self / rhs }
/// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7_u64.div_ceil(4), 2);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_ceil(self, rhs: Self) -> Self {
let d = self / rhs;
let r = self % rhs;
if r > 0 { d + 1 } else { d }
}
/// Calculates the smallest value greater than or equal to `self` that
/// is a multiple of `rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// On overflow, this function will panic if overflow checks are enabled (default in debug
/// mode) and wrap if overflow checks are disabled (default in release mode).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(16_u64.next_multiple_of(8), 16);"]
#[doc = "assert_eq!(23_u64.next_multiple_of(8), 24);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_multiple_of(self, rhs: Self) -> Self {
match self % rhs { 0 => self, r => self + (rhs - r), }
}
/// Calculates the smallest value greater than or equal to `self` that
/// is a multiple of `rhs`. Returns `None` if `rhs` is zero or the
/// operation would result in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(16_u64.checked_next_multiple_of(8), Some(16));"]
#[doc = "assert_eq!(23_u64.checked_next_multiple_of(8), Some(24));"]
#[doc = "assert_eq!(1_u64.checked_next_multiple_of(0), None);"]
#[doc = "assert_eq!(u64::MAX.checked_next_multiple_of(2), None);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
match match self.checked_rem(rhs) { Some(x) => x, None => return None, } {
0 => Some(self),
r => self.checked_add(rhs - r),
}
}
/// Returns `true` if `self` is an integer multiple of `rhs`, and false otherwise.
///
/// This function is equivalent to `self % rhs == 0`, except that it will not panic
/// for `rhs == 0`. Instead, `0.is_multiple_of(0) == true`, and for any non-zero `n`,
/// `n.is_multiple_of(0) == false`.
///
/// # Examples
///
/// ```
#[doc = "assert!(6_u64.is_multiple_of(2));"]
#[doc = "assert!(!5_u64.is_multiple_of(2));"]
///
#[doc = "assert!(0_u64.is_multiple_of(0));"]
#[doc = "assert!(!6_u64.is_multiple_of(0));"]
/// ```
#[stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
#[rustc_const_stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
#[must_use]
#[inline]
pub const fn is_multiple_of(self, rhs: Self) -> bool {
match rhs { 0 => self == 0, _ => self % rhs == 0, }
}
/// Returns `true` if and only if `self == 2^k` for some unsigned integer `k`.
///
/// # Examples
///
/// ```
#[doc = "assert!(16u64.is_power_of_two());"]
#[doc = "assert!(!10u64.is_power_of_two());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
#[inline(always)]
pub const fn is_power_of_two(self) -> bool { self.count_ones() == 1 }
#[inline]
const fn one_less_than_next_power_of_two(self) -> Self {
if self <= 1 { return 0; }
let p = self - 1;
let z = unsafe { intrinsics::ctlz_nonzero(p) };
<u64>::MAX >> z
}
/// Returns the smallest power of two greater than or equal to `self`.
///
/// When return value overflows (i.e., `self > (1 << (N-1))` for type
/// `uN`), it panics in debug mode and the return value is wrapped to 0 in
/// release mode (the only situation in which this method can return 0).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u64.next_power_of_two(), 2);"]
#[doc = "assert_eq!(3u64.next_power_of_two(), 4);"]
#[doc = "assert_eq!(0u64.next_power_of_two(), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_power_of_two(self) -> Self {
self.one_less_than_next_power_of_two() + 1
}
/// Returns the smallest power of two greater than or equal to `self`. If
/// the next power of two is greater than the type's maximum value,
/// `None` is returned, otherwise the power of two is wrapped in `Some`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u64.checked_next_power_of_two(), Some(2));"]
#[doc = "assert_eq!(3u64.checked_next_power_of_two(), Some(4));"]
#[doc = "assert_eq!(u64::MAX.checked_next_power_of_two(), None);"]
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn checked_next_power_of_two(self) -> Option<Self> {
self.one_less_than_next_power_of_two().checked_add(1)
}
/// Returns the smallest power of two greater than or equal to `n`. If
/// the next power of two is greater than the type's maximum value,
/// the return value is wrapped to `0`.
///
/// # Examples
///
/// ```
/// #![feature(wrapping_next_power_of_two)]
///
#[doc = "assert_eq!(2u64.wrapping_next_power_of_two(), 2);"]
#[doc = "assert_eq!(3u64.wrapping_next_power_of_two(), 4);"]
#[doc = "assert_eq!(u64::MAX.wrapping_next_power_of_two(), 0);"]
/// ```
#[inline]
#[unstable(feature = "wrapping_next_power_of_two", issue = "32463", reason =
"needs decision on wrapping behavior")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn wrapping_next_power_of_two(self) -> Self {
self.one_less_than_next_power_of_two().wrapping_add(1)
}
/// Returns the memory representation of this integer as a byte array in
/// big-endian (network) byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234567890123456u64.to_be_bytes();"]
#[doc =
"assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
self.to_be().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// little-endian byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234567890123456u64.to_le_bytes();"]
#[doc =
"assert_eq!(bytes, [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
self.to_le().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code
/// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
/// instead.
///
#[doc = ""]
///
/// [`to_be_bytes`]: Self::to_be_bytes
/// [`to_le_bytes`]: Self::to_le_bytes
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234567890123456u64.to_ne_bytes();"]
/// assert_eq!(
/// bytes,
/// if cfg!(target_endian = "big") {
#[doc = " [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]"]
/// } else {
#[doc = " [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]"]
/// }
/// );
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[allow(unnecessary_transmutes)]
#[inline]
pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
unsafe { mem::transmute(self) }
}
/// Creates a native endian integer value from its representation
/// as a byte array in big endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc =
"let value = u64::from_be_bytes([0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]);"]
#[doc = "assert_eq!(value, 0x1234567890123456);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_be_u64(input: &mut &[u8]) -> u64 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u64>());"]
/// *input = rest;
#[doc = " u64::from_be_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_be(Self::from_ne_bytes(bytes))
}
/// Creates a native endian integer value from its representation
/// as a byte array in little endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc =
"let value = u64::from_le_bytes([0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);"]
#[doc = "assert_eq!(value, 0x1234567890123456);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_le_u64(input: &mut &[u8]) -> u64 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u64>());"]
/// *input = rest;
#[doc = " u64::from_le_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_le(Self::from_ne_bytes(bytes))
}
/// Creates a native endian integer value from its memory representation
/// as a byte array in native endianness.
///
/// As the target platform's native endianness is used, portable code
/// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
/// appropriate instead.
///
/// [`from_be_bytes`]: Self::from_be_bytes
/// [`from_le_bytes`]: Self::from_le_bytes
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = u64::from_ne_bytes(if cfg!(target_endian = \"big\") {"]
#[doc = " [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]"]
/// } else {
#[doc = " [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]"]
/// });
#[doc = "assert_eq!(value, 0x1234567890123456);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_ne_u64(input: &mut &[u8]) -> u64 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u64>());"]
/// *input = rest;
#[doc = " u64::from_ne_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use]
#[inline]
pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
unsafe { mem::transmute(bytes) }
}
/// New code should prefer to use
#[doc = "[`u64::MIN`] instead."]
///
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_promotable]
#[inline(always)]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MIN` associated constant on this type")]
#[rustc_diagnostic_item = "u64_legacy_fn_min_value"]
pub const fn min_value() -> Self { Self::MIN }
/// New code should prefer to use
#[doc = "[`u64::MAX`] instead."]
///
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_promotable]
#[inline(always)]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MAX` associated constant on this type")]
#[rustc_diagnostic_item = "u64_legacy_fn_max_value"]
pub const fn max_value() -> Self { Self::MAX }
/// Truncate an integer to an integer of the same size or smaller, preserving the least
/// significant bits.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u8, 120u64.truncate());"]
/// assert_eq!(120u8, 376u32.truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
/// instead of truncating.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u8, 120u64.saturating_truncate());"]
/// assert_eq!(255u8, 376u32.saturating_truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn saturating_truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_saturating_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
/// is outside the bounds of the smaller type.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(Some(120u8), 120u64.checked_truncate());"]
/// assert_eq!(None, 376u32.checked_truncate::<u8>());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn checked_truncate<Target>(self) -> Option<Target> where
Self: [const] traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_checked_truncate(self)
}
/// Widen to an integer of the same size or larger, preserving its value.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u128, 120u8.widen());"]
/// ```
#[must_use =
"this returns the widened value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn widen<Target>(self) -> Target where Self: [const]
traits::WidenTarget<Target> {
traits::WidenTarget::internal_widen(self)
}uint_impl! {
1319Self = u64,
1320 ActualT = u64,
1321 SignedT = i64,
1322 BITS = 64,
1323 BITS_MINUS_ONE = 63,
1324 MAX = 18446744073709551615,
1325 rot = 12,
1326 rot_op = "0xaa00000000006e1",
1327 rot_result = "0x6e10aa",
1328 fsh_op = "0x2fe78e45983acd98",
1329 fshl_result = "0x6e12fe",
1330 fshr_result = "0x6e12fe78e45983ac",
1331 clmul_lhs = "0x7890123456789012",
1332 clmul_rhs = "0xdd358416f52ecd34",
1333 clmul_result = "0xa6299579b980928",
1334 swap_op = "0x1234567890123456",
1335 swapped = "0x5634129078563412",
1336 reversed = "0x6a2c48091e6a2c48",
1337 le_bytes = "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
1338 be_bytes = "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
1339 to_xe_bytes_doc = "",
1340 from_xe_bytes_doc = "",
1341 bound_condition = "",
1342 }1343/// 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 }1344/// 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 }1345/// 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 }1346/// 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 }1347}
13481349impl u128 {
1350/// 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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "uint_bit_width", since =
"CURRENT_RUSTC_VERSION")]
#[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 =
"CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"CURRENT_RUSTC_VERSION")]
#[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 =
"CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"CURRENT_RUSTC_VERSION")]
#[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`.
///
/// # 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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since =
"CURRENT_RUSTC_VERSION")]
#[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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since =
"CURRENT_RUSTC_VERSION")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn lowest_one(self) -> Option<u32> {
match NonZero::new(self) {
Some(v) => Some(v.lowest_one()),
None => None,
}
}
/// Returns the bit pattern of `self` reinterpreted as a signed integer of the same size.
///
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
/// the same.
///
/// # Examples
///
/// ```
#[doc = "let n = u128::MAX;"]
///
#[doc = "assert_eq!(n.cast_signed(), -1i128);"]
/// ```
#[stable(feature = "integer_sign_cast", since = "1.87.0")]
#[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_signed(self) -> i128 { self as i128 }
/// Saturating conversion of `self` to a signed integer of the same size.
///
/// The signed integer's maximum value is returned if `self` is larger
/// than the maximum positive value representable by the signed integer.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`checked_cast_signed`](Self::checked_cast_signed),
/// or [`strict_cast_signed`](Self::strict_cast_signed).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = u128::MAX;"]
///
#[doc = "assert_eq!(n.saturating_cast_signed(), i128::MAX);"]
#[doc = "assert_eq!(64u128.saturating_cast_signed(), 64i128);"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_cast_signed(self) -> i128 {
if self <= <i128>::MAX.cast_unsigned() {
self.cast_signed()
} else { <i128>::MAX }
}
/// Checked conversion of `self` to a signed integer of the same size,
/// returning `None` if `self` is larger than the signed integer's
/// maximum value.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`saturating_cast_signed`](Self::saturating_cast_signed),
/// or [`strict_cast_signed`](Self::strict_cast_signed).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = u128::MAX;"]
///
#[doc = "assert_eq!(n.checked_cast_signed(), None);"]
#[doc = "assert_eq!(64u128.checked_cast_signed(), Some(64i128));"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn checked_cast_signed(self) -> Option<i128> {
if self <= <i128>::MAX.cast_unsigned() {
Some(self.cast_signed())
} else { None }
}
/// Strict conversion of `self` to a signed integer of the same size,
/// which panics if `self` is larger than the signed integer's maximum
/// value.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`checked_cast_signed`](Self::checked_cast_signed),
/// or [`saturating_cast_signed`](Self::saturating_cast_signed).
///
/// # Examples
///
/// ```should_panic
/// #![feature(integer_cast_extras)]
#[doc = "let _ = u128::MAX.strict_cast_signed();"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_cast_signed(self) -> i128 {
match self.checked_cast_signed() {
Some(n) => n,
None => imp::overflow_panic::cast_integer(),
}
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `<<` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x13f40000000000000000000000004f76u128;"]
#[doc = "let m = 0x4f7613f4;"]
///
#[doc = "assert_eq!(n.rotate_left(16), m);"]
#[doc = "assert_eq!(n.rotate_left(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
pub const fn rotate_left(self, n: u32) -> Self {
return intrinsics::rotate_left(self, n);
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `>>` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x4f7613f4u128;"]
#[doc = "let m = 0x13f40000000000000000000000004f76;"]
///
#[doc = "assert_eq!(n.rotate_right(16), m);"]
#[doc = "assert_eq!(n.rotate_right(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
pub const fn rotate_right(self, n: u32) -> Self {
return intrinsics::rotate_right(self, n);
}
/// Performs a left funnel shift (concatenates `self` with `rhs`, with `self`
/// making up the most significant half, then shifts the combined value left
/// by `n`, and most significant half is extracted to produce the result).
///
/// Please note this isn't the same operation as the `<<` shifting operator or
/// [`rotate_left`](Self::rotate_left), although `a.funnel_shl(a, n)` is *equivalent*
/// to `a.rotate_left(n)`.
///
/// # Panics
///
/// If `n` is greater than or equal to the number of bits in `self`
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(funnel_shifts)]
#[doc = "let a = 0x13f40000000000000000000000004f76u128;"]
#[doc = "let b = 0x2fe78e45983acd98039000008736273u128;"]
#[doc = "let m = 0x4f7602fe;"]
///
#[doc = "assert_eq!(a.funnel_shl(b, 16), m);"]
/// ```
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn funnel_shl(self, rhs: Self, n: u32) -> Self {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift left with overflow"));
}
};
unsafe { self.unchecked_funnel_shl(rhs, n) }
}
/// Performs a right funnel shift (concatenates `self` and `rhs`, with `self`
/// making up the most significant half, then shifts the combined value right
/// by `n`, and least significant half is extracted to produce the result).
///
/// Please note this isn't the same operation as the `>>` shifting operator or
/// [`rotate_right`](Self::rotate_right), although `a.funnel_shr(a, n)` is *equivalent*
/// to `a.rotate_right(n)`.
///
/// # Panics
///
/// If `n` is greater than or equal to the number of bits in `self`
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(funnel_shifts)]
#[doc = "let a = 0x13f40000000000000000000000004f76u128;"]
#[doc = "let b = 0x2fe78e45983acd98039000008736273u128;"]
#[doc = "let m = 0x4f7602fe78e45983acd9803900000873;"]
///
#[doc = "assert_eq!(a.funnel_shr(b, 16), m);"]
/// ```
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn funnel_shr(self, rhs: Self, n: u32) -> Self {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift right with overflow"));
}
};
unsafe { self.unchecked_funnel_shr(rhs, n) }
}
/// Unchecked funnel shift left.
///
/// # Safety
///
/// This results in undefined behavior if `n` is greater than or equal to
#[doc = "`u128::BITS`,"]
/// i.e. when [`funnel_shl`](Self::funnel_shl) would panic.
///
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_funnel_shl(self, low: Self, n: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(n: u32) {
if !(n < <u128>::BITS) {
let msg =
"unsafe precondition(s) violated: u128::unchecked_funnel_shl cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(n); }
};
unsafe { intrinsics::unchecked_funnel_shl(self, low, n) }
}
/// Unchecked funnel shift right.
///
/// # Safety
///
/// This results in undefined behavior if `n` is greater than or equal to
#[doc = "`u128::BITS`,"]
/// i.e. when [`funnel_shr`](Self::funnel_shr) would panic.
///
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_funnel_shr(self, low: Self, n: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(n: u32) {
if !(n < <u128>::BITS) {
let msg =
"unsafe precondition(s) violated: u128::unchecked_funnel_shr cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(n); }
};
unsafe { intrinsics::unchecked_funnel_shr(self, low, n) }
}
/// Performs a carry-less multiplication, returning the lower bits.
///
/// This operation is similar to long multiplication in base 2, except that exclusive or is
/// used instead of addition. The implementation is equivalent to:
///
/// ```no_run
#[doc = "pub fn carryless_mul(lhs: u128, rhs: u128) -> u128{"]
/// let mut retval = 0;
#[doc = " for i in 0..u128::BITS {"]
/// if (rhs >> i) & 1 != 0 {
/// // long multiplication would use +=
/// retval ^= lhs << i;
/// }
/// }
/// retval
/// }
/// ```
///
/// The actual implementation is more efficient, and on some platforms lowers directly to a
/// dedicated instruction.
///
/// # Uses
///
/// Carryless multiplication can be used to turn a bitmask of quote characters into a
/// bit mask of characters surrounded by quotes:
///
/// ```no_run
/// r#"abc xxx "foobar" zzz "a"!"#; // input string
/// 0b0000000010000001000001010; // quote_mask
/// 0b0000000001111110000000100; // quote_mask.carryless_mul(!0) & !quote_mask
/// ```
///
/// Another use is in cryptography, where carryless multiplication allows for efficient
/// implementations of polynomial multiplication in `GF(2)[X]`, the polynomial ring
/// over `GF(2)`.
///
/// # Examples
///
/// ```
/// #![feature(uint_carryless_mul)]
///
#[doc = "let a = 0x12345678901234567890123456789012u128;"]
#[doc = "let b = 0x4317e40ab4ddcf05dd358416f52ecd34u128;"]
///
#[doc = "assert_eq!(a.carryless_mul(b), 0xb9cf660de35d0c170a6299579b980928);"]
/// ```
#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
#[doc(alias = "clmul")]
#[unstable(feature = "uint_carryless_mul", issue = "152080")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn carryless_mul(self, rhs: Self) -> Self {
intrinsics::carryless_mul(self, rhs)
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x12345678901234567890123456789012u128;"]
/// let m = n.swap_bytes();
///
#[doc = "assert_eq!(m, 0x12907856341290785634129078563412);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn swap_bytes(self) -> Self {
intrinsics::bswap(self as u128) as Self
}
/// Returns an integer with the bit locations specified by `mask` packed
/// contiguously into the least significant bits of the result.
/// ```
/// #![feature(uint_gather_scatter_bits)]
#[doc = "let n: u128 = 0b1011_1100;"]
///
/// assert_eq!(n.extract_bits(0b0010_0100), 0b0000_0011);
/// assert_eq!(n.extract_bits(0xF0), 0b0000_1011);
/// ```
#[doc(alias = "pext")]
#[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn extract_bits(self, mask: Self) -> Self {
imp::int_bits::u128::extract_impl(self as u128, mask as u128) as u128
}
/// Returns an integer with the least significant bits of `self`
/// distributed to the bit locations specified by `mask`.
/// ```
/// #![feature(uint_gather_scatter_bits)]
#[doc = "let n: u128 = 0b1010_1101;"]
///
/// assert_eq!(n.deposit_bits(0b0101_0101), 0b0101_0001);
/// assert_eq!(n.deposit_bits(0xF0), 0b1101_0000);
/// ```
#[doc(alias = "pdep")]
#[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn deposit_bits(self, mask: Self) -> Self {
imp::int_bits::u128::deposit_impl(self as u128, mask as u128) as u128
}
/// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
/// second least-significant bit becomes second most-significant bit, etc.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x12345678901234567890123456789012u128;"]
/// let m = n.reverse_bits();
///
#[doc = "assert_eq!(m, 0x48091e6a2c48091e6a2c48091e6a2c48);"]
#[doc = "assert_eq!(0, 0u128.reverse_bits());"]
/// ```
#[stable(feature = "reverse_bits", since = "1.37.0")]
#[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn reverse_bits(self) -> Self {
intrinsics::bitreverse(self as u128) as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au128;"]
///
/// if cfg!(target_endian = "big") {
#[doc = " assert_eq!(u128::from_be(n), n)"]
/// } else {
#[doc = " assert_eq!(u128::from_be(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use]
#[inline(always)]
pub const fn from_be(x: Self) -> Self { x.swap_bytes() }
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au128;"]
///
/// if cfg!(target_endian = "little") {
#[doc = " assert_eq!(u128::from_le(n), n)"]
/// } else {
#[doc = " assert_eq!(u128::from_le(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use]
#[inline(always)]
pub const fn from_le(x: Self) -> Self { x }
/// Converts `self` to big endian from the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au128;"]
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn to_be(self) -> Self { self.swap_bytes() }
/// Converts `self` to little endian from the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Au128;"]
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn to_le(self) -> Self { self }
/// Checked integer addition. Computes `self + rhs`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((u128::MAX - 2).checked_add(1), Some(u128::MAX - 1));"]
#[doc = "assert_eq!((u128::MAX - 2).checked_add(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(intrinsics::add_with_overflow(self, rhs).1) {
None
} else { Some(unsafe { intrinsics::unchecked_add(self, rhs) }) }
}
/// Strict integer addition. Computes `self + rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((u128::MAX - 2).strict_add(1), u128::MAX - 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (u128::MAX - 2).strict_add(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_add(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Unchecked integer addition. Computes `self + rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_add(y)` is semantically equivalent to calling
/// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_add`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self + rhs > u128::MAX`,"]
/// i.e. when [`checked_add`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_add`]: u128::checked_add"]
#[doc = "[`wrapping_add`]: u128::wrapping_add"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u128, rhs: u128) {
if !!lhs.overflowing_add(rhs).1 {
let msg =
"unsafe precondition(s) violated: u128::unchecked_add cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_add(self, rhs) }
}
/// Checked addition with a signed integer. Computes `self + rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u128.checked_add_signed(2), Some(3));"]
#[doc = "assert_eq!(1u128.checked_add_signed(-2), None);"]
#[doc = "assert_eq!((u128::MAX - 2).checked_add_signed(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add_signed(self, rhs: i128) -> Option<Self> {
let (a, b) = self.overflowing_add_signed(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict addition with a signed integer. Computes `self + rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u128.strict_add_signed(2), 3);"]
/// ```
///
/// The following panic because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1u128.strict_add_signed(-2);"]
/// ```
///
/// ```should_panic
#[doc = "let _ = (u128::MAX - 2).strict_add_signed(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add_signed(self, rhs: i128) -> Self {
let (a, b) = self.overflowing_add_signed(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Checked integer subtraction. Computes `self - rhs`, returning
/// `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u128.checked_sub(1), Some(0));"]
#[doc = "assert_eq!(0u128.checked_sub(1), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
if self < rhs {
None
} else { Some(unsafe { intrinsics::unchecked_sub(self, rhs) }) }
}
/// Strict integer subtraction. Computes `self - rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u128.strict_sub(1), 0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0u128.strict_sub(1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_sub(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
/// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_sub`].
///
/// If you find yourself writing code like this:
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if foo >= bar {
/// // SAFETY: just checked it will not overflow
/// let diff = unsafe { foo.unchecked_sub(bar) };
/// // ... use diff ...
/// }
/// ```
///
/// Consider changing it to
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if let Some(diff) = foo.checked_sub(bar) {
/// // ... use diff ...
/// }
/// ```
///
/// As that does exactly the same thing -- including telling the optimizer
/// that the subtraction cannot overflow -- but avoids needing `unsafe`.
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self - rhs < u128::MIN`,"]
/// i.e. when [`checked_sub`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_sub`]: u128::checked_sub"]
#[doc = "[`wrapping_sub`]: u128::wrapping_sub"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u128, rhs: u128) {
if !!lhs.overflowing_sub(rhs).1 {
let msg =
"unsafe precondition(s) violated: u128::unchecked_sub cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_sub(self, rhs) }
}
/// Checked subtraction with a signed integer. Computes `self - rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1u128.checked_sub_signed(2), None);"]
#[doc = "assert_eq!(1u128.checked_sub_signed(-2), Some(3));"]
#[doc = "assert_eq!((u128::MAX - 2).checked_sub_signed(-4), None);"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub_signed(self, rhs: i128) -> Option<Self> {
let (res, overflow) = self.overflowing_sub_signed(rhs);
if !overflow { Some(res) } else { None }
}
/// Strict subtraction with a signed integer. Computes `self - rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3u128.strict_sub_signed(2), 1);"]
/// ```
///
/// The following panic because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1u128.strict_sub_signed(2);"]
/// ```
///
/// ```should_panic
#[doc = "let _ = (u128::MAX).strict_sub_signed(-1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub_signed(self, rhs: i128) -> Self {
let (a, b) = self.overflowing_sub_signed(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
#[doc =
"Checked integer subtraction. Computes `self - rhs` and checks if the result fits into an [`i128`], returning `None` if overflow occurred."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10u128.checked_signed_diff(2), Some(8));"]
#[doc = "assert_eq!(2u128.checked_signed_diff(10), Some(-8));"]
#[doc = "assert_eq!(u128::MAX.checked_signed_diff(i128::MAX as u128), None);"]
#[doc =
"assert_eq!((i128::MAX as u128).checked_signed_diff(u128::MAX), Some(i128::MIN));"]
#[doc = "assert_eq!((i128::MAX as u128 + 1).checked_signed_diff(0), None);"]
#[doc = "assert_eq!(u128::MAX.checked_signed_diff(u128::MAX), Some(0));"]
/// ```
#[stable(feature = "unsigned_signed_diff", since = "1.91.0")]
#[rustc_const_stable(feature = "unsigned_signed_diff", since = "1.91.0")]
#[inline]
pub const fn checked_signed_diff(self, rhs: Self) -> Option<i128> {
let res = self.wrapping_sub(rhs) as i128;
let overflow = (self >= rhs) == (res < 0);
if !overflow { Some(res) } else { None }
}
/// Checked integer multiplication. Computes `self * rhs`, returning
/// `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u128.checked_mul(1), Some(5));"]
#[doc = "assert_eq!(u128::MAX.checked_mul(2), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer multiplication. Computes `self * rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u128.strict_mul(1), 5);"]
/// ```
///
/// The following panics because of overflow:
///
/// ``` should_panic
#[doc = "let _ = u128::MAX.strict_mul(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_mul(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_mul(rhs);
if b { imp::overflow_panic::mul() } else { a }
}
/// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
/// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_mul`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self * rhs > u128::MAX`,"]
/// i.e. when [`checked_mul`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_mul`]: u128::checked_mul"]
#[doc = "[`wrapping_mul`]: u128::wrapping_mul"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u128, rhs: u128) {
if !!lhs.overflowing_mul(rhs).1 {
let msg =
"unsafe precondition(s) violated: u128::unchecked_mul cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_mul(self, rhs) }
}
/// Checked integer division. Computes `self / rhs`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128u128.checked_div(2), Some(64));"]
#[doc = "assert_eq!(1u128.checked_div(0), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(unsafe { intrinsics::unchecked_div(self, rhs) }) }
}
/// Strict integer division. Computes `self / rhs`.
///
/// Strict division on unsigned types is just normal division. There's no
/// way overflow could ever happen. This function exists so that all
/// operations are accounted for in the strict operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u128.strict_div(10), 10);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1u128).strict_div(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_div(self, rhs: Self) -> Self { self / rhs }
/// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128u128.checked_div_euclid(2), Some(64));"]
#[doc = "assert_eq!(1u128.checked_div_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(self.div_euclid(rhs)) }
}
/// Strict Euclidean division. Computes `self.div_euclid(rhs)`.
///
/// Strict division on unsigned types is just normal division. There's no
/// way overflow could ever happen. This function exists so that all
/// operations are accounted for in the strict operations. Since, for the
/// positive integers, all common definitions of division are equal, this
/// is exactly equal to `self.strict_div(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u128.strict_div_euclid(10), 10);"]
/// ```
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1u128).strict_div_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Checked integer division without remainder. Computes `self / rhs`,
/// returning `None` if `rhs == 0` or if `self % rhs != 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64u128.checked_div_exact(2), Some(32));"]
#[doc = "assert_eq!(64u128.checked_div_exact(32), Some(2));"]
#[doc = "assert_eq!(64u128.checked_div_exact(0), None);"]
#[doc = "assert_eq!(65u128.checked_div_exact(2), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_exact(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else {
unsafe {
if intrinsics::unlikely(intrinsics::unchecked_rem(self, rhs) != 0)
{
None
} else { Some(intrinsics::exact_div(self, rhs)) }
}
}
}
/// Integer division without remainder. Computes `self / rhs`, returning `None` if `self % rhs != 0`.
///
/// # Panics
///
/// This function will panic if `rhs == 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64u128.div_exact(2), Some(32));"]
#[doc = "assert_eq!(64u128.div_exact(32), Some(2));"]
#[doc = "assert_eq!(65u128.div_exact(2), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn div_exact(self, rhs: Self) -> Option<Self> {
if self % rhs != 0 { None } else { Some(self / rhs) }
}
/// Unchecked integer division without remainder. Computes `self / rhs`.
///
/// # Safety
///
/// This results in undefined behavior when `rhs == 0` or `self % rhs != 0`,
/// i.e. when [`checked_div_exact`](Self::checked_div_exact) would return `None`.
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_div_exact(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u128, rhs: u128) {
if !(rhs > 0 && lhs % rhs == 0) {
let msg =
"unsafe precondition(s) violated: u128::unchecked_div_exact divide by zero or leave a remainder\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::exact_div(self, rhs) }
}
/// Checked integer remainder. Computes `self % rhs`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u128.checked_rem(2), Some(1));"]
#[doc = "assert_eq!(5u128.checked_rem(0), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(unsafe { intrinsics::unchecked_rem(self, rhs) }) }
}
/// Strict integer remainder. Computes `self % rhs`.
///
/// Strict remainder calculation on unsigned types is just the regular
/// remainder calculation. There's no way overflow could ever happen.
/// This function exists so that all operations are accounted for in the
/// strict operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u128.strict_rem(10), 0);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5u128.strict_rem(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_rem(self, rhs: Self) -> Self { self % rhs }
/// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5u128.checked_rem_euclid(2), Some(1));"]
#[doc = "assert_eq!(5u128.checked_rem_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(self.rem_euclid(rhs)) }
}
/// Strict Euclidean modulo. Computes `self.rem_euclid(rhs)`.
///
/// Strict modulo calculation on unsigned types is just the regular
/// remainder calculation. There's no way overflow could ever happen.
/// This function exists so that all operations are accounted for in the
/// strict operations. Since, for the positive integers, all common
/// definitions of division are equal, this is exactly equal to
/// `self.strict_rem(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100u128.strict_rem_euclid(10), 0);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5u128.strict_rem_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Same value as `self | other`, but UB if any bit position is set in both inputs.
///
/// This is a situational micro-optimization for places where you'd rather
/// use addition on some platforms and bitwise or on other platforms, based
/// on exactly which instructions combine better with whatever else you're
/// doing. Note that there's no reason to bother using this for places
/// where it's clear from the operations involved that they can't overlap.
/// For example, if you're combining `u16`s into a `u32` with
/// `((a as u32) << 16) | (b as u32)`, that's fine, as the backend will
/// know those sides of the `|` are disjoint without needing help.
///
/// # Examples
///
/// ```
/// #![feature(disjoint_bitor)]
///
/// // SAFETY: `1` and `4` have no bits in common.
/// unsafe {
#[doc = " assert_eq!(1_u128.unchecked_disjoint_bitor(4), 5);"]
/// }
/// ```
///
/// # Safety
///
/// Requires that `(self & other) == 0`, otherwise it's immediate UB.
///
/// Equivalently, requires that `(self | other) == (self + other)`.
#[unstable(feature = "disjoint_bitor", issue = "135758")]
#[rustc_const_unstable(feature = "disjoint_bitor", issue = "135758")]
#[inline]
pub const unsafe fn unchecked_disjoint_bitor(self, other: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: u128, rhs: u128) {
if !((lhs & rhs) == 0) {
let msg =
"unsafe precondition(s) violated: u128::unchecked_disjoint_bitor cannot have overlapping bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, other);
}
};
unsafe { intrinsics::disjoint_bitor(self, other) }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// This method might not be optimized owing to implementation details;
/// `ilog2` can produce results more efficiently for base 2, and `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));"]
/// ```
#[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 == 2 {
return self.checked_ilog2();
} else 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.
///
/// # 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> {
if exp == 0 { return Some(1); }
let mut base = self;
let mut acc: Self = 1;
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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc: Self = 1;
loop {
if (exp & 1) == 1 {
acc = acc.strict_mul(base);
if exp == 1 { return acc; }
}
exp /= 2;
base = base.strict_mul(base);
}
}
/// 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. The behaviour 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. The behaviour 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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc: Self = 1;
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 { acc = acc.wrapping_mul(base); }
exp /= 2;
base = base.wrapping_mul(base);
}
acc.wrapping_mul(base)
} else {
loop {
if (exp & 1) == 1 {
acc = acc.wrapping_mul(base);
if exp == 1 { return acc; }
}
exp /= 2;
base = base.wrapping_mul(base);
}
}
}
/// 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) {
if exp == 0 { return (1, false); }
let mut base = self;
let mut acc: Self = 1;
let mut overflown = false;
let mut r;
loop {
if (exp & 1) == 1 {
r = acc.overflowing_mul(base);
if exp == 1 { r.1 |= overflown; return r; }
acc = r.0;
overflown |= r.1;
}
exp /= 2;
r = base.overflowing_mul(base);
base = r.0;
overflown |= r.1;
}
}
/// 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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc = 1;
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 { acc = acc * base; }
exp /= 2;
base = base * base;
}
acc * base
} else {
loop {
if (exp & 1) == 1 {
acc = acc * base;
if exp == 1 { return acc; }
}
exp /= 2;
base = base * base;
}
}
}
/// Returns the square root of the number, rounded down.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10u128.isqrt(), 3);"]
/// ```
#[stable(feature = "isqrt", since = "1.84.0")]
#[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn isqrt(self) -> Self {
let result = imp::int_sqrt::u128(self as u128) as Self;
unsafe {
const MAX_RESULT: u128 = imp::int_sqrt::u128(<u128>::MAX) as u128;
crate::hint::assert_unchecked(result <= MAX_RESULT)
}
if self >= 1 { unsafe { crate::hint::assert_unchecked(result >= 1) } }
unsafe {
crate::hint::assert_unchecked(result.unchecked_mul(result) <= self);
crate::hint::assert_unchecked(result <= self);
}
result
}
/// Performs Euclidean division.
///
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self / rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7u128.div_euclid(4), 1); // or any other integer type"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Calculates the least remainder of `self` when divided by
/// `rhs`.
///
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self % rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7u128.rem_euclid(4), 3); // or any other integer type"]
/// ```
#[doc(alias = "modulo", alias = "mod")]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
///
/// This is the same as performing `self / rhs` for all unsigned integers.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "assert_eq!(7_u128.div_floor(4), 1);"]
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn div_floor(self, rhs: Self) -> Self { self / rhs }
/// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7_u128.div_ceil(4), 2);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_ceil(self, rhs: Self) -> Self {
let d = self / rhs;
let r = self % rhs;
if r > 0 { d + 1 } else { d }
}
/// Calculates the smallest value greater than or equal to `self` that
/// is a multiple of `rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// On overflow, this function will panic if overflow checks are enabled (default in debug
/// mode) and wrap if overflow checks are disabled (default in release mode).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(16_u128.next_multiple_of(8), 16);"]
#[doc = "assert_eq!(23_u128.next_multiple_of(8), 24);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_multiple_of(self, rhs: Self) -> Self {
match self % rhs { 0 => self, r => self + (rhs - r), }
}
/// Calculates the smallest value greater than or equal to `self` that
/// is a multiple of `rhs`. Returns `None` if `rhs` is zero or the
/// operation would result in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(16_u128.checked_next_multiple_of(8), Some(16));"]
#[doc = "assert_eq!(23_u128.checked_next_multiple_of(8), Some(24));"]
#[doc = "assert_eq!(1_u128.checked_next_multiple_of(0), None);"]
#[doc = "assert_eq!(u128::MAX.checked_next_multiple_of(2), None);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
match match self.checked_rem(rhs) { Some(x) => x, None => return None, } {
0 => Some(self),
r => self.checked_add(rhs - r),
}
}
/// Returns `true` if `self` is an integer multiple of `rhs`, and false otherwise.
///
/// This function is equivalent to `self % rhs == 0`, except that it will not panic
/// for `rhs == 0`. Instead, `0.is_multiple_of(0) == true`, and for any non-zero `n`,
/// `n.is_multiple_of(0) == false`.
///
/// # Examples
///
/// ```
#[doc = "assert!(6_u128.is_multiple_of(2));"]
#[doc = "assert!(!5_u128.is_multiple_of(2));"]
///
#[doc = "assert!(0_u128.is_multiple_of(0));"]
#[doc = "assert!(!6_u128.is_multiple_of(0));"]
/// ```
#[stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
#[rustc_const_stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
#[must_use]
#[inline]
pub const fn is_multiple_of(self, rhs: Self) -> bool {
match rhs { 0 => self == 0, _ => self % rhs == 0, }
}
/// Returns `true` if and only if `self == 2^k` for some unsigned integer `k`.
///
/// # Examples
///
/// ```
#[doc = "assert!(16u128.is_power_of_two());"]
#[doc = "assert!(!10u128.is_power_of_two());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
#[inline(always)]
pub const fn is_power_of_two(self) -> bool { self.count_ones() == 1 }
#[inline]
const fn one_less_than_next_power_of_two(self) -> Self {
if self <= 1 { return 0; }
let p = self - 1;
let z = unsafe { intrinsics::ctlz_nonzero(p) };
<u128>::MAX >> z
}
/// Returns the smallest power of two greater than or equal to `self`.
///
/// When return value overflows (i.e., `self > (1 << (N-1))` for type
/// `uN`), it panics in debug mode and the return value is wrapped to 0 in
/// release mode (the only situation in which this method can return 0).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u128.next_power_of_two(), 2);"]
#[doc = "assert_eq!(3u128.next_power_of_two(), 4);"]
#[doc = "assert_eq!(0u128.next_power_of_two(), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_power_of_two(self) -> Self {
self.one_less_than_next_power_of_two() + 1
}
/// Returns the smallest power of two greater than or equal to `self`. If
/// the next power of two is greater than the type's maximum value,
/// `None` is returned, otherwise the power of two is wrapped in `Some`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2u128.checked_next_power_of_two(), Some(2));"]
#[doc = "assert_eq!(3u128.checked_next_power_of_two(), Some(4));"]
#[doc = "assert_eq!(u128::MAX.checked_next_power_of_two(), None);"]
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn checked_next_power_of_two(self) -> Option<Self> {
self.one_less_than_next_power_of_two().checked_add(1)
}
/// Returns the smallest power of two greater than or equal to `n`. If
/// the next power of two is greater than the type's maximum value,
/// the return value is wrapped to `0`.
///
/// # Examples
///
/// ```
/// #![feature(wrapping_next_power_of_two)]
///
#[doc = "assert_eq!(2u128.wrapping_next_power_of_two(), 2);"]
#[doc = "assert_eq!(3u128.wrapping_next_power_of_two(), 4);"]
#[doc = "assert_eq!(u128::MAX.wrapping_next_power_of_two(), 0);"]
/// ```
#[inline]
#[unstable(feature = "wrapping_next_power_of_two", issue = "32463", reason =
"needs decision on wrapping behavior")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn wrapping_next_power_of_two(self) -> Self {
self.one_less_than_next_power_of_two().wrapping_add(1)
}
/// Returns the memory representation of this integer as a byte array in
/// big-endian (network) byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12345678901234567890123456789012u128.to_be_bytes();"]
#[doc =
"assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
self.to_be().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// little-endian byte order.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12345678901234567890123456789012u128.to_le_bytes();"]
#[doc =
"assert_eq!(bytes, [0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
self.to_le().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code
/// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
/// instead.
///
#[doc = ""]
///
/// [`to_be_bytes`]: Self::to_be_bytes
/// [`to_le_bytes`]: Self::to_le_bytes
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x12345678901234567890123456789012u128.to_ne_bytes();"]
/// assert_eq!(
/// bytes,
/// if cfg!(target_endian = "big") {
#[doc =
" [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]"]
/// } else {
#[doc =
" [0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]"]
/// }
/// );
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[allow(unnecessary_transmutes)]
#[inline]
pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
unsafe { mem::transmute(self) }
}
/// Creates a native endian integer value from its representation
/// as a byte array in big endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc =
"let value = u128::from_be_bytes([0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]);"]
#[doc = "assert_eq!(value, 0x12345678901234567890123456789012);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_be_u128(input: &mut &[u8]) -> u128 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u128>());"]
/// *input = rest;
#[doc = " u128::from_be_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_be(Self::from_ne_bytes(bytes))
}
/// Creates a native endian integer value from its representation
/// as a byte array in little endian.
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc =
"let value = u128::from_le_bytes([0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);"]
#[doc = "assert_eq!(value, 0x12345678901234567890123456789012);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_le_u128(input: &mut &[u8]) -> u128 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u128>());"]
/// *input = rest;
#[doc = " u128::from_le_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_le(Self::from_ne_bytes(bytes))
}
/// Creates a native endian integer value from its memory representation
/// as a byte array in native endianness.
///
/// As the target platform's native endianness is used, portable code
/// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
/// appropriate instead.
///
/// [`from_be_bytes`]: Self::from_be_bytes
/// [`from_le_bytes`]: Self::from_le_bytes
///
#[doc = ""]
///
/// # Examples
///
/// ```
#[doc = "let value = u128::from_ne_bytes(if cfg!(target_endian = \"big\") {"]
#[doc =
" [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]"]
/// } else {
#[doc =
" [0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]"]
/// });
#[doc = "assert_eq!(value, 0x12345678901234567890123456789012);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_ne_u128(input: &mut &[u8]) -> u128 {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<u128>());"]
/// *input = rest;
#[doc = " u128::from_ne_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use]
#[inline]
pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
unsafe { mem::transmute(bytes) }
}
/// New code should prefer to use
#[doc = "[`u128::MIN`] instead."]
///
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_promotable]
#[inline(always)]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MIN` associated constant on this type")]
#[rustc_diagnostic_item = "u128_legacy_fn_min_value"]
pub const fn min_value() -> Self { Self::MIN }
/// New code should prefer to use
#[doc = "[`u128::MAX`] instead."]
///
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_promotable]
#[inline(always)]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MAX` associated constant on this type")]
#[rustc_diagnostic_item = "u128_legacy_fn_max_value"]
pub const fn max_value() -> Self { Self::MAX }
/// Truncate an integer to an integer of the same size or smaller, preserving the least
/// significant bits.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u8, 120u128.truncate());"]
/// assert_eq!(120u8, 376u32.truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
/// instead of truncating.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u8, 120u128.saturating_truncate());"]
/// assert_eq!(255u8, 376u32.saturating_truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn saturating_truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_saturating_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
/// is outside the bounds of the smaller type.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(Some(120u8), 120u128.checked_truncate());"]
/// assert_eq!(None, 376u32.checked_truncate::<u8>());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn checked_truncate<Target>(self) -> Option<Target> where
Self: [const] traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_checked_truncate(self)
}
/// Widen to an integer of the same size or larger, preserving its value.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u128, 120u8.widen());"]
/// ```
#[must_use =
"this returns the widened value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn widen<Target>(self) -> Target where Self: [const]
traits::WidenTarget<Target> {
traits::WidenTarget::internal_widen(self)
}uint_impl! {
1351Self = u128,
1352 ActualT = u128,
1353 SignedT = i128,
1354 BITS = 128,
1355 BITS_MINUS_ONE = 127,
1356 MAX = 340282366920938463463374607431768211455,
1357 rot = 16,
1358 rot_op = "0x13f40000000000000000000000004f76",
1359 rot_result = "0x4f7613f4",
1360 fsh_op = "0x2fe78e45983acd98039000008736273",
1361 fshl_result = "0x4f7602fe",
1362 fshr_result = "0x4f7602fe78e45983acd9803900000873",
1363 clmul_lhs = "0x12345678901234567890123456789012",
1364 clmul_rhs = "0x4317e40ab4ddcf05dd358416f52ecd34",
1365 clmul_result = "0xb9cf660de35d0c170a6299579b980928",
1366 swap_op = "0x12345678901234567890123456789012",
1367 swapped = "0x12907856341290785634129078563412",
1368 reversed = "0x48091e6a2c48091e6a2c48091e6a2c48",
1369 le_bytes = "[0x12, 0x90, 0x78, 0x56, 0x34, 0x12, 0x90, 0x78, \
1370 0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
1371 be_bytes = "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56, \
1372 0x78, 0x90, 0x12, 0x34, 0x56, 0x78, 0x90, 0x12]",
1373 to_xe_bytes_doc = "",
1374 from_xe_bytes_doc = "",
1375 bound_condition = "",
1376 }1377/// 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 }1378/// 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 }1379}
13801381#[doc(auto_cfg = false)]
1382#[cfg(target_pointer_width = "16")]
1383impl usize {
1384uint_impl! {
1385Self = usize,
1386 ActualT = u16,
1387 SignedT = isize,
1388 BITS = 16,
1389 BITS_MINUS_ONE = 15,
1390 MAX = 65535,
1391 rot = 4,
1392 rot_op = "0xa003",
1393 rot_result = "0x3a",
1394 fsh_op = "0x2de",
1395 fshl_result = "0x30",
1396 fshr_result = "0x302d",
1397 clmul_lhs = "0x9012",
1398 clmul_rhs = "0xcd34",
1399 clmul_result = "0x928",
1400 swap_op = "0x1234",
1401 swapped = "0x3412",
1402 reversed = "0x2c48",
1403 le_bytes = "[0x34, 0x12]",
1404 be_bytes = "[0x12, 0x34]",
1405 to_xe_bytes_doc = usize_isize_to_xe_bytes_doc!(),
1406 from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(),
1407 bound_condition = " on 16-bit targets",
1408 }
1409midpoint_impl! { usize, u32, unsigned }
1410carrying_carryless_mul_impl! { usize, u32 }
1411}
14121413#[doc(auto_cfg = false)]
1414#[cfg(target_pointer_width = "32")]
1415impl usize {
1416uint_impl! {
1417Self = usize,
1418 ActualT = u32,
1419 SignedT = isize,
1420 BITS = 32,
1421 BITS_MINUS_ONE = 31,
1422 MAX = 4294967295,
1423 rot = 8,
1424 rot_op = "0x10000b3",
1425 rot_result = "0xb301",
1426 fsh_op = "0x2fe78e45",
1427 fshl_result = "0xb32f",
1428 fshr_result = "0xb32fe78e",
1429 clmul_lhs = "0x56789012",
1430 clmul_rhs = "0xf52ecd34",
1431 clmul_result = "0x9b980928",
1432 swap_op = "0x12345678",
1433 swapped = "0x78563412",
1434 reversed = "0x1e6a2c48",
1435 le_bytes = "[0x78, 0x56, 0x34, 0x12]",
1436 be_bytes = "[0x12, 0x34, 0x56, 0x78]",
1437 to_xe_bytes_doc = usize_isize_to_xe_bytes_doc!(),
1438 from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(),
1439 bound_condition = " on 32-bit targets",
1440 }
1441midpoint_impl! { usize, u64, unsigned }
1442carrying_carryless_mul_impl! { usize, u64 }
1443}
14441445#[doc(auto_cfg = false)]
1446#[cfg(target_pointer_width = "64")]
1447impl usize {
1448/// 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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "uint_bit_width", since =
"CURRENT_RUSTC_VERSION")]
#[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 =
"CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"CURRENT_RUSTC_VERSION")]
#[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 =
"CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "isolate_most_least_significant_one", since =
"CURRENT_RUSTC_VERSION")]
#[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`.
///
/// # 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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since =
"CURRENT_RUSTC_VERSION")]
#[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 = "CURRENT_RUSTC_VERSION")]
#[rustc_const_stable(feature = "int_lowest_highest_one", since =
"CURRENT_RUSTC_VERSION")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn lowest_one(self) -> Option<u32> {
match NonZero::new(self) {
Some(v) => Some(v.lowest_one()),
None => None,
}
}
/// Returns the bit pattern of `self` reinterpreted as a signed integer of the same size.
///
/// This produces the same result as an `as` cast, but ensures that the bit-width remains
/// the same.
///
/// # Examples
///
/// ```
#[doc = "let n = usize::MAX;"]
///
#[doc = "assert_eq!(n.cast_signed(), -1isize);"]
/// ```
#[stable(feature = "integer_sign_cast", since = "1.87.0")]
#[rustc_const_stable(feature = "integer_sign_cast", since = "1.87.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn cast_signed(self) -> isize { self as isize }
/// Saturating conversion of `self` to a signed integer of the same size.
///
/// The signed integer's maximum value is returned if `self` is larger
/// than the maximum positive value representable by the signed integer.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`checked_cast_signed`](Self::checked_cast_signed),
/// or [`strict_cast_signed`](Self::strict_cast_signed).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = usize::MAX;"]
///
#[doc = "assert_eq!(n.saturating_cast_signed(), isize::MAX);"]
#[doc = "assert_eq!(64usize.saturating_cast_signed(), 64isize);"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn saturating_cast_signed(self) -> isize {
if self <= <isize>::MAX.cast_unsigned() {
self.cast_signed()
} else { <isize>::MAX }
}
/// Checked conversion of `self` to a signed integer of the same size,
/// returning `None` if `self` is larger than the signed integer's
/// maximum value.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`saturating_cast_signed`](Self::saturating_cast_signed),
/// or [`strict_cast_signed`](Self::strict_cast_signed).
///
/// # Examples
///
/// ```
/// #![feature(integer_cast_extras)]
#[doc = "let n = usize::MAX;"]
///
#[doc = "assert_eq!(n.checked_cast_signed(), None);"]
#[doc = "assert_eq!(64usize.checked_cast_signed(), Some(64isize));"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn checked_cast_signed(self) -> Option<isize> {
if self <= <isize>::MAX.cast_unsigned() {
Some(self.cast_signed())
} else { None }
}
/// Strict conversion of `self` to a signed integer of the same size,
/// which panics if `self` is larger than the signed integer's maximum
/// value.
///
/// For other kinds of signed integer casts, see
/// [`cast_signed`](Self::cast_signed),
/// [`checked_cast_signed`](Self::checked_cast_signed),
/// or [`saturating_cast_signed`](Self::saturating_cast_signed).
///
/// # Examples
///
/// ```should_panic
/// #![feature(integer_cast_extras)]
#[doc = "let _ = usize::MAX.strict_cast_signed();"]
/// ```
#[rustc_const_unstable(feature = "integer_cast_extras", issue = "154650")]
#[unstable(feature = "integer_cast_extras", issue = "154650")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_cast_signed(self) -> isize {
match self.checked_cast_signed() {
Some(n) => n,
None => imp::overflow_panic::cast_integer(),
}
}
/// Shifts the bits to the left by a specified amount, `n`,
/// wrapping the truncated bits to the end of the resulting integer.
///
/// `rotate_left(n)` is equivalent to applying `rotate_left(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `<<` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0xaa00000000006e1usize;"]
#[doc = "let m = 0x6e10aa;"]
///
#[doc = "assert_eq!(n.rotate_left(12), m);"]
#[doc = "assert_eq!(n.rotate_left(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
pub const fn rotate_left(self, n: u32) -> Self {
return intrinsics::rotate_left(self, n);
}
/// Shifts the bits to the right by a specified amount, `n`,
/// wrapping the truncated bits to the beginning of the resulting
/// integer.
///
/// `rotate_right(n)` is equivalent to applying `rotate_right(1)` a total of `n` times. In
/// particular, a rotation by the number of bits in `self` returns the input value
/// unchanged.
///
/// Please note this isn't the same operation as the `>>` shifting operator!
///
/// # Examples
///
/// ```
#[doc = "let n = 0x6e10aausize;"]
#[doc = "let m = 0xaa00000000006e1;"]
///
#[doc = "assert_eq!(n.rotate_right(12), m);"]
#[doc = "assert_eq!(n.rotate_right(1024), n);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[rustc_allow_const_fn_unstable(const_trait_impl)]
pub const fn rotate_right(self, n: u32) -> Self {
return intrinsics::rotate_right(self, n);
}
/// Performs a left funnel shift (concatenates `self` with `rhs`, with `self`
/// making up the most significant half, then shifts the combined value left
/// by `n`, and most significant half is extracted to produce the result).
///
/// Please note this isn't the same operation as the `<<` shifting operator or
/// [`rotate_left`](Self::rotate_left), although `a.funnel_shl(a, n)` is *equivalent*
/// to `a.rotate_left(n)`.
///
/// # Panics
///
/// If `n` is greater than or equal to the number of bits in `self`
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(funnel_shifts)]
#[doc = "let a = 0xaa00000000006e1usize;"]
#[doc = "let b = 0x2fe78e45983acd98usize;"]
#[doc = "let m = 0x6e12fe;"]
///
#[doc = "assert_eq!(a.funnel_shl(b, 12), m);"]
/// ```
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn funnel_shl(self, rhs: Self, n: u32) -> Self {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift left with overflow"));
}
};
unsafe { self.unchecked_funnel_shl(rhs, n) }
}
/// Performs a right funnel shift (concatenates `self` and `rhs`, with `self`
/// making up the most significant half, then shifts the combined value right
/// by `n`, and least significant half is extracted to produce the result).
///
/// Please note this isn't the same operation as the `>>` shifting operator or
/// [`rotate_right`](Self::rotate_right), although `a.funnel_shr(a, n)` is *equivalent*
/// to `a.rotate_right(n)`.
///
/// # Panics
///
/// If `n` is greater than or equal to the number of bits in `self`
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// #![feature(funnel_shifts)]
#[doc = "let a = 0xaa00000000006e1usize;"]
#[doc = "let b = 0x2fe78e45983acd98usize;"]
#[doc = "let m = 0x6e12fe78e45983ac;"]
///
#[doc = "assert_eq!(a.funnel_shr(b, 12), m);"]
/// ```
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn funnel_shr(self, rhs: Self, n: u32) -> Self {
if !(n < Self::BITS) {
{
crate::panicking::panic_fmt(format_args!("attempt to funnel shift right with overflow"));
}
};
unsafe { self.unchecked_funnel_shr(rhs, n) }
}
/// Unchecked funnel shift left.
///
/// # Safety
///
/// This results in undefined behavior if `n` is greater than or equal to
#[doc = "`usize::BITS`,"]
/// i.e. when [`funnel_shl`](Self::funnel_shl) would panic.
///
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_funnel_shl(self, low: Self, n: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(n: u32) {
if !(n < <u64>::BITS) {
let msg =
"unsafe precondition(s) violated: usize::unchecked_funnel_shl cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(n); }
};
unsafe { intrinsics::unchecked_funnel_shl(self, low, n) }
}
/// Unchecked funnel shift right.
///
/// # Safety
///
/// This results in undefined behavior if `n` is greater than or equal to
#[doc = "`usize::BITS`,"]
/// i.e. when [`funnel_shr`](Self::funnel_shr) would panic.
///
#[rustc_const_unstable(feature = "funnel_shifts", issue = "145686")]
#[unstable(feature = "funnel_shifts", issue = "145686")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_funnel_shr(self, low: Self, n: u32) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(n: u32) {
if !(n < <u64>::BITS) {
let msg =
"unsafe precondition(s) violated: usize::unchecked_funnel_shr cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() { precondition_check(n); }
};
unsafe { intrinsics::unchecked_funnel_shr(self, low, n) }
}
/// Performs a carry-less multiplication, returning the lower bits.
///
/// This operation is similar to long multiplication in base 2, except that exclusive or is
/// used instead of addition. The implementation is equivalent to:
///
/// ```no_run
#[doc = "pub fn carryless_mul(lhs: usize, rhs: usize) -> usize{"]
/// let mut retval = 0;
#[doc = " for i in 0..usize::BITS {"]
/// if (rhs >> i) & 1 != 0 {
/// // long multiplication would use +=
/// retval ^= lhs << i;
/// }
/// }
/// retval
/// }
/// ```
///
/// The actual implementation is more efficient, and on some platforms lowers directly to a
/// dedicated instruction.
///
/// # Uses
///
/// Carryless multiplication can be used to turn a bitmask of quote characters into a
/// bit mask of characters surrounded by quotes:
///
/// ```no_run
/// r#"abc xxx "foobar" zzz "a"!"#; // input string
/// 0b0000000010000001000001010; // quote_mask
/// 0b0000000001111110000000100; // quote_mask.carryless_mul(!0) & !quote_mask
/// ```
///
/// Another use is in cryptography, where carryless multiplication allows for efficient
/// implementations of polynomial multiplication in `GF(2)[X]`, the polynomial ring
/// over `GF(2)`.
///
/// # Examples
///
/// ```
/// #![feature(uint_carryless_mul)]
///
#[doc = "let a = 0x7890123456789012usize;"]
#[doc = "let b = 0xdd358416f52ecd34usize;"]
///
#[doc = "assert_eq!(a.carryless_mul(b), 0xa6299579b980928);"]
/// ```
#[rustc_const_unstable(feature = "uint_carryless_mul", issue = "152080")]
#[doc(alias = "clmul")]
#[unstable(feature = "uint_carryless_mul", issue = "152080")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn carryless_mul(self, rhs: Self) -> Self {
intrinsics::carryless_mul(self, rhs)
}
/// Reverses the byte order of the integer.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1234567890123456usize;"]
/// let m = n.swap_bytes();
///
#[doc = "assert_eq!(m, 0x5634129078563412);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn swap_bytes(self) -> Self {
intrinsics::bswap(self as u64) as Self
}
/// Returns an integer with the bit locations specified by `mask` packed
/// contiguously into the least significant bits of the result.
/// ```
/// #![feature(uint_gather_scatter_bits)]
#[doc = "let n: usize = 0b1011_1100;"]
///
/// assert_eq!(n.extract_bits(0b0010_0100), 0b0000_0011);
/// assert_eq!(n.extract_bits(0xF0), 0b0000_1011);
/// ```
#[doc(alias = "pext")]
#[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn extract_bits(self, mask: Self) -> Self {
imp::int_bits::u64::extract_impl(self as u64, mask as u64) as usize
}
/// Returns an integer with the least significant bits of `self`
/// distributed to the bit locations specified by `mask`.
/// ```
/// #![feature(uint_gather_scatter_bits)]
#[doc = "let n: usize = 0b1010_1101;"]
///
/// assert_eq!(n.deposit_bits(0b0101_0101), 0b0101_0001);
/// assert_eq!(n.deposit_bits(0xF0), 0b1101_0000);
/// ```
#[doc(alias = "pdep")]
#[unstable(feature = "uint_gather_scatter_bits", issue = "149069")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn deposit_bits(self, mask: Self) -> Self {
imp::int_bits::u64::deposit_impl(self as u64, mask as u64) as usize
}
/// Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,
/// second least-significant bit becomes second most-significant bit, etc.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1234567890123456usize;"]
/// let m = n.reverse_bits();
///
#[doc = "assert_eq!(m, 0x6a2c48091e6a2c48);"]
#[doc = "assert_eq!(0, 0usize.reverse_bits());"]
/// ```
#[stable(feature = "reverse_bits", since = "1.37.0")]
#[rustc_const_stable(feature = "reverse_bits", since = "1.37.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn reverse_bits(self) -> Self {
intrinsics::bitreverse(self as u64) as Self
}
/// Converts an integer from big endian to the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ausize;"]
///
/// if cfg!(target_endian = "big") {
#[doc = " assert_eq!(usize::from_be(n), n)"]
/// } else {
#[doc = " assert_eq!(usize::from_be(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use]
#[inline(always)]
pub const fn from_be(x: Self) -> Self { x.swap_bytes() }
/// Converts an integer from little endian to the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ausize;"]
///
/// if cfg!(target_endian = "little") {
#[doc = " assert_eq!(usize::from_le(n), n)"]
/// } else {
#[doc = " assert_eq!(usize::from_le(n), n.swap_bytes())"]
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use]
#[inline(always)]
pub const fn from_le(x: Self) -> Self { x }
/// Converts `self` to big endian from the target's endianness.
///
/// On big endian this is a no-op. On little endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ausize;"]
///
/// if cfg!(target_endian = "big") {
/// assert_eq!(n.to_be(), n)
/// } else {
/// assert_eq!(n.to_be(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn to_be(self) -> Self { self.swap_bytes() }
/// Converts `self` to little endian from the target's endianness.
///
/// On little endian this is a no-op. On big endian the bytes are
/// swapped.
///
/// # Examples
///
/// ```
#[doc = "let n = 0x1Ausize;"]
///
/// if cfg!(target_endian = "little") {
/// assert_eq!(n.to_le(), n)
/// } else {
/// assert_eq!(n.to_le(), n.swap_bytes())
/// }
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_math", since = "1.32.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
pub const fn to_le(self) -> Self { self }
/// Checked integer addition. Computes `self + rhs`, returning `None`
/// if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((usize::MAX - 2).checked_add(1), Some(usize::MAX - 1));"]
#[doc = "assert_eq!((usize::MAX - 2).checked_add(3), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(intrinsics::add_with_overflow(self, rhs).1) {
None
} else { Some(unsafe { intrinsics::unchecked_add(self, rhs) }) }
}
/// Strict integer addition. Computes `self + rhs`, panicking
/// if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!((usize::MAX - 2).strict_add(1), usize::MAX - 1);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = (usize::MAX - 2).strict_add(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_add(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Unchecked integer addition. Computes `self + rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_add(y)` is semantically equivalent to calling
/// `x.`[`checked_add`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_add`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self + rhs > usize::MAX`,"]
/// i.e. when [`checked_add`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_add`]: usize::checked_add"]
#[doc = "[`wrapping_add`]: usize::wrapping_add"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_add(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: usize, rhs: usize) {
if !!lhs.overflowing_add(rhs).1 {
let msg =
"unsafe precondition(s) violated: usize::unchecked_add cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_add(self, rhs) }
}
/// Checked addition with a signed integer. Computes `self + rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1usize.checked_add_signed(2), Some(3));"]
#[doc = "assert_eq!(1usize.checked_add_signed(-2), None);"]
#[doc = "assert_eq!((usize::MAX - 2).checked_add_signed(3), None);"]
/// ```
#[stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[rustc_const_stable(feature = "mixed_integer_ops", since = "1.66.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_add_signed(self, rhs: isize) -> Option<Self> {
let (a, b) = self.overflowing_add_signed(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict addition with a signed integer. Computes `self + rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1usize.strict_add_signed(2), 3);"]
/// ```
///
/// The following panic because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1usize.strict_add_signed(-2);"]
/// ```
///
/// ```should_panic
#[doc = "let _ = (usize::MAX - 2).strict_add_signed(3);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_add_signed(self, rhs: isize) -> Self {
let (a, b) = self.overflowing_add_signed(rhs);
if b { imp::overflow_panic::add() } else { a }
}
/// Checked integer subtraction. Computes `self - rhs`, returning
/// `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1usize.checked_sub(1), Some(0));"]
#[doc = "assert_eq!(0usize.checked_sub(1), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub(self, rhs: Self) -> Option<Self> {
if self < rhs {
None
} else { Some(unsafe { intrinsics::unchecked_sub(self, rhs) }) }
}
/// Strict integer subtraction. Computes `self - rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1usize.strict_sub(1), 0);"]
/// ```
///
/// The following panics because of overflow:
///
/// ```should_panic
#[doc = "let _ = 0usize.strict_sub(1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_sub(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
/// Unchecked integer subtraction. Computes `self - rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_sub(y)` is semantically equivalent to calling
/// `x.`[`checked_sub`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_sub`].
///
/// If you find yourself writing code like this:
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if foo >= bar {
/// // SAFETY: just checked it will not overflow
/// let diff = unsafe { foo.unchecked_sub(bar) };
/// // ... use diff ...
/// }
/// ```
///
/// Consider changing it to
///
/// ```
/// # let foo = 30_u32;
/// # let bar = 20;
/// if let Some(diff) = foo.checked_sub(bar) {
/// // ... use diff ...
/// }
/// ```
///
/// As that does exactly the same thing -- including telling the optimizer
/// that the subtraction cannot overflow -- but avoids needing `unsafe`.
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self - rhs < usize::MIN`,"]
/// i.e. when [`checked_sub`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_sub`]: usize::checked_sub"]
#[doc = "[`wrapping_sub`]: usize::wrapping_sub"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_sub(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: usize, rhs: usize) {
if !!lhs.overflowing_sub(rhs).1 {
let msg =
"unsafe precondition(s) violated: usize::unchecked_sub cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_sub(self, rhs) }
}
/// Checked subtraction with a signed integer. Computes `self - rhs`,
/// returning `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(1usize.checked_sub_signed(2), None);"]
#[doc = "assert_eq!(1usize.checked_sub_signed(-2), Some(3));"]
#[doc = "assert_eq!((usize::MAX - 2).checked_sub_signed(-4), None);"]
/// ```
#[stable(feature = "mixed_integer_ops_unsigned_sub", since = "1.90.0")]
#[rustc_const_stable(feature = "mixed_integer_ops_unsigned_sub", since =
"1.90.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_sub_signed(self, rhs: isize) -> Option<Self> {
let (res, overflow) = self.overflowing_sub_signed(rhs);
if !overflow { Some(res) } else { None }
}
/// Strict subtraction with a signed integer. Computes `self - rhs`,
/// panicking if overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(3usize.strict_sub_signed(2), 1);"]
/// ```
///
/// The following panic because of overflow:
///
/// ```should_panic
#[doc = "let _ = 1usize.strict_sub_signed(2);"]
/// ```
///
/// ```should_panic
#[doc = "let _ = (usize::MAX).strict_sub_signed(-1);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_sub_signed(self, rhs: isize) -> Self {
let (a, b) = self.overflowing_sub_signed(rhs);
if b { imp::overflow_panic::sub() } else { a }
}
#[doc =
"Checked integer subtraction. Computes `self - rhs` and checks if the result fits into an [`isize`], returning `None` if overflow occurred."]
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10usize.checked_signed_diff(2), Some(8));"]
#[doc = "assert_eq!(2usize.checked_signed_diff(10), Some(-8));"]
#[doc =
"assert_eq!(usize::MAX.checked_signed_diff(isize::MAX as usize), None);"]
#[doc =
"assert_eq!((isize::MAX as usize).checked_signed_diff(usize::MAX), Some(isize::MIN));"]
#[doc = "assert_eq!((isize::MAX as usize + 1).checked_signed_diff(0), None);"]
#[doc = "assert_eq!(usize::MAX.checked_signed_diff(usize::MAX), Some(0));"]
/// ```
#[stable(feature = "unsigned_signed_diff", since = "1.91.0")]
#[rustc_const_stable(feature = "unsigned_signed_diff", since = "1.91.0")]
#[inline]
pub const fn checked_signed_diff(self, rhs: Self) -> Option<isize> {
let res = self.wrapping_sub(rhs) as isize;
let overflow = (self >= rhs) == (res < 0);
if !overflow { Some(res) } else { None }
}
/// Checked integer multiplication. Computes `self * rhs`, returning
/// `None` if overflow occurred.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5usize.checked_mul(1), Some(5));"]
#[doc = "assert_eq!(usize::MAX.checked_mul(2), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_methods", since = "1.47.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_mul(self, rhs: Self) -> Option<Self> {
let (a, b) = self.overflowing_mul(rhs);
if intrinsics::unlikely(b) { None } else { Some(a) }
}
/// Strict integer multiplication. Computes `self * rhs`, panicking if
/// overflow occurred.
///
/// # Panics
///
/// ## Overflow behavior
///
/// This function will always panic on overflow, regardless of whether overflow checks are enabled.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5usize.strict_mul(1), 5);"]
/// ```
///
/// The following panics because of overflow:
///
/// ``` should_panic
#[doc = "let _ = usize::MAX.strict_mul(2);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn strict_mul(self, rhs: Self) -> Self {
let (a, b) = self.overflowing_mul(rhs);
if b { imp::overflow_panic::mul() } else { a }
}
/// Unchecked integer multiplication. Computes `self * rhs`, assuming overflow
/// cannot occur.
///
/// Calling `x.unchecked_mul(y)` is semantically equivalent to calling
/// `x.`[`checked_mul`]`(y).`[`unwrap_unchecked`]`()`.
///
/// If you're just trying to avoid the panic in debug mode, then **do not**
/// use this. Instead, you're looking for [`wrapping_mul`].
///
/// # Safety
///
/// This results in undefined behavior when
#[doc = "`self * rhs > usize::MAX`,"]
/// i.e. when [`checked_mul`] would return `None`.
///
/// [`unwrap_unchecked`]: option/enum.Option.html#method.unwrap_unchecked
#[doc = "[`checked_mul`]: usize::checked_mul"]
#[doc = "[`wrapping_mul`]: usize::wrapping_mul"]
#[stable(feature = "unchecked_math", since = "1.79.0")]
#[rustc_const_stable(feature = "unchecked_math", since = "1.79.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const unsafe fn unchecked_mul(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: usize, rhs: usize) {
if !!lhs.overflowing_mul(rhs).1 {
let msg =
"unsafe precondition(s) violated: usize::unchecked_mul cannot overflow\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::unchecked_mul(self, rhs) }
}
/// Checked integer division. Computes `self / rhs`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128usize.checked_div(2), Some(64));"]
#[doc = "assert_eq!(1usize.checked_div(0), None);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(unsafe { intrinsics::unchecked_div(self, rhs) }) }
}
/// Strict integer division. Computes `self / rhs`.
///
/// Strict division on unsigned types is just normal division. There's no
/// way overflow could ever happen. This function exists so that all
/// operations are accounted for in the strict operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100usize.strict_div(10), 10);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1usize).strict_div(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_div(self, rhs: Self) -> Self { self / rhs }
/// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(128usize.checked_div_euclid(2), Some(64));"]
#[doc = "assert_eq!(1usize.checked_div_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(self.div_euclid(rhs)) }
}
/// Strict Euclidean division. Computes `self.div_euclid(rhs)`.
///
/// Strict division on unsigned types is just normal division. There's no
/// way overflow could ever happen. This function exists so that all
/// operations are accounted for in the strict operations. Since, for the
/// positive integers, all common definitions of division are equal, this
/// is exactly equal to `self.strict_div(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100usize.strict_div_euclid(10), 10);"]
/// ```
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = (1usize).strict_div_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Checked integer division without remainder. Computes `self / rhs`,
/// returning `None` if `rhs == 0` or if `self % rhs != 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64usize.checked_div_exact(2), Some(32));"]
#[doc = "assert_eq!(64usize.checked_div_exact(32), Some(2));"]
#[doc = "assert_eq!(64usize.checked_div_exact(0), None);"]
#[doc = "assert_eq!(65usize.checked_div_exact(2), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_div_exact(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else {
unsafe {
if intrinsics::unlikely(intrinsics::unchecked_rem(self, rhs) != 0)
{
None
} else { Some(intrinsics::exact_div(self, rhs)) }
}
}
}
/// Integer division without remainder. Computes `self / rhs`, returning `None` if `self % rhs != 0`.
///
/// # Panics
///
/// This function will panic if `rhs == 0`.
///
/// # Examples
///
/// ```
/// #![feature(exact_div)]
#[doc = "assert_eq!(64usize.div_exact(2), Some(32));"]
#[doc = "assert_eq!(64usize.div_exact(32), Some(2));"]
#[doc = "assert_eq!(65usize.div_exact(2), None);"]
/// ```
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn div_exact(self, rhs: Self) -> Option<Self> {
if self % rhs != 0 { None } else { Some(self / rhs) }
}
/// Unchecked integer division without remainder. Computes `self / rhs`.
///
/// # Safety
///
/// This results in undefined behavior when `rhs == 0` or `self % rhs != 0`,
/// i.e. when [`checked_div_exact`](Self::checked_div_exact) would return `None`.
#[unstable(feature = "exact_div", issue = "139911",)]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const unsafe fn unchecked_div_exact(self, rhs: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: usize, rhs: usize) {
if !(rhs > 0 && lhs % rhs == 0) {
let msg =
"unsafe precondition(s) violated: usize::unchecked_div_exact divide by zero or leave a remainder\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, rhs);
}
};
unsafe { intrinsics::exact_div(self, rhs) }
}
/// Checked integer remainder. Computes `self % rhs`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5usize.checked_rem(2), Some(1));"]
#[doc = "assert_eq!(5usize.checked_rem(0), None);"]
/// ```
#[stable(feature = "wrapping", since = "1.7.0")]
#[rustc_const_stable(feature = "const_checked_int_div", since = "1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(unsafe { intrinsics::unchecked_rem(self, rhs) }) }
}
/// Strict integer remainder. Computes `self % rhs`.
///
/// Strict remainder calculation on unsigned types is just the regular
/// remainder calculation. There's no way overflow could ever happen.
/// This function exists so that all operations are accounted for in the
/// strict operations.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100usize.strict_rem(10), 0);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5usize.strict_rem(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_rem(self, rhs: Self) -> Self { self % rhs }
/// Checked Euclidean modulo. Computes `self.rem_euclid(rhs)`, returning `None`
/// if `rhs == 0`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(5usize.checked_rem_euclid(2), Some(1));"]
#[doc = "assert_eq!(5usize.checked_rem_euclid(0), None);"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_rem_euclid(self, rhs: Self) -> Option<Self> {
if intrinsics::unlikely(rhs == 0) {
None
} else { Some(self.rem_euclid(rhs)) }
}
/// Strict Euclidean modulo. Computes `self.rem_euclid(rhs)`.
///
/// Strict modulo calculation on unsigned types is just the regular
/// remainder calculation. There's no way overflow could ever happen.
/// This function exists so that all operations are accounted for in the
/// strict operations. Since, for the positive integers, all common
/// definitions of division are equal, this is exactly equal to
/// `self.strict_rem(rhs)`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(100usize.strict_rem_euclid(10), 0);"]
/// ```
///
/// The following panics because of division by zero:
///
/// ```should_panic
#[doc = "let _ = 5usize.strict_rem_euclid(0);"]
/// ```
#[stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[rustc_const_stable(feature = "strict_overflow_ops", since = "1.91.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn strict_rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Same value as `self | other`, but UB if any bit position is set in both inputs.
///
/// This is a situational micro-optimization for places where you'd rather
/// use addition on some platforms and bitwise or on other platforms, based
/// on exactly which instructions combine better with whatever else you're
/// doing. Note that there's no reason to bother using this for places
/// where it's clear from the operations involved that they can't overlap.
/// For example, if you're combining `u16`s into a `u32` with
/// `((a as u32) << 16) | (b as u32)`, that's fine, as the backend will
/// know those sides of the `|` are disjoint without needing help.
///
/// # Examples
///
/// ```
/// #![feature(disjoint_bitor)]
///
/// // SAFETY: `1` and `4` have no bits in common.
/// unsafe {
#[doc = " assert_eq!(1_usize.unchecked_disjoint_bitor(4), 5);"]
/// }
/// ```
///
/// # Safety
///
/// Requires that `(self & other) == 0`, otherwise it's immediate UB.
///
/// Equivalently, requires that `(self | other) == (self + other)`.
#[unstable(feature = "disjoint_bitor", issue = "135758")]
#[rustc_const_unstable(feature = "disjoint_bitor", issue = "135758")]
#[inline]
pub const unsafe fn unchecked_disjoint_bitor(self, other: Self) -> Self {
{
#[rustc_no_mir_inline]
#[inline]
#[rustc_nounwind]
#[track_caller]
const fn precondition_check(lhs: usize, rhs: usize) {
if !((lhs & rhs) == 0) {
let msg =
"unsafe precondition(s) violated: usize::unchecked_disjoint_bitor cannot have overlapping bits\n\nThis indicates a bug in the program. This Undefined Behavior check is optional, and cannot be relied on for safety.";
::core::panicking::panic_nounwind_fmt(::core::fmt::Arguments::from_str(msg),
false);
}
}
if ::core::ub_checks::check_language_ub() {
precondition_check(self, other);
}
};
unsafe { intrinsics::disjoint_bitor(self, other) }
}
/// Returns the logarithm of the number with respect to an arbitrary base,
/// rounded down.
///
/// This method might not be optimized owing to implementation details;
/// `ilog2` can produce results more efficiently for base 2, and `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));"]
/// ```
#[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 == 2 {
return self.checked_ilog2();
} else 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.
///
/// # 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> {
if exp == 0 { return Some(1); }
let mut base = self;
let mut acc: Self = 1;
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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc: Self = 1;
loop {
if (exp & 1) == 1 {
acc = acc.strict_mul(base);
if exp == 1 { return acc; }
}
exp /= 2;
base = base.strict_mul(base);
}
}
/// 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. The behaviour 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. The behaviour 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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc: Self = 1;
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 { acc = acc.wrapping_mul(base); }
exp /= 2;
base = base.wrapping_mul(base);
}
acc.wrapping_mul(base)
} else {
loop {
if (exp & 1) == 1 {
acc = acc.wrapping_mul(base);
if exp == 1 { return acc; }
}
exp /= 2;
base = base.wrapping_mul(base);
}
}
}
/// 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) {
if exp == 0 { return (1, false); }
let mut base = self;
let mut acc: Self = 1;
let mut overflown = false;
let mut r;
loop {
if (exp & 1) == 1 {
r = acc.overflowing_mul(base);
if exp == 1 { r.1 |= overflown; return r; }
acc = r.0;
overflown |= r.1;
}
exp /= 2;
r = base.overflowing_mul(base);
base = r.0;
overflown |= r.1;
}
}
/// 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, mut exp: u32) -> Self {
if exp == 0 { return 1; }
let mut base = self;
let mut acc = 1;
if intrinsics::is_val_statically_known(exp) {
while exp > 1 {
if (exp & 1) == 1 { acc = acc * base; }
exp /= 2;
base = base * base;
}
acc * base
} else {
loop {
if (exp & 1) == 1 {
acc = acc * base;
if exp == 1 { return acc; }
}
exp /= 2;
base = base * base;
}
}
}
/// Returns the square root of the number, rounded down.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(10usize.isqrt(), 3);"]
/// ```
#[stable(feature = "isqrt", since = "1.84.0")]
#[rustc_const_stable(feature = "isqrt", since = "1.84.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn isqrt(self) -> Self {
let result = imp::int_sqrt::u64(self as u64) as Self;
unsafe {
const MAX_RESULT: usize = imp::int_sqrt::u64(<u64>::MAX) as usize;
crate::hint::assert_unchecked(result <= MAX_RESULT)
}
if self >= 1 { unsafe { crate::hint::assert_unchecked(result >= 1) } }
unsafe {
crate::hint::assert_unchecked(result.unchecked_mul(result) <= self);
crate::hint::assert_unchecked(result <= self);
}
result
}
/// Performs Euclidean division.
///
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self / rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7usize.div_euclid(4), 1); // or any other integer type"]
/// ```
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn div_euclid(self, rhs: Self) -> Self { self / rhs }
/// Calculates the least remainder of `self` when divided by
/// `rhs`.
///
/// Since, for the positive integers, all common
/// definitions of division are equal, this
/// is exactly equal to `self % rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7usize.rem_euclid(4), 3); // or any other integer type"]
/// ```
#[doc(alias = "modulo", alias = "mod")]
#[stable(feature = "euclidean_division", since = "1.38.0")]
#[rustc_const_stable(feature = "const_euclidean_int_methods", since =
"1.52.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn rem_euclid(self, rhs: Self) -> Self { self % rhs }
/// Calculates the quotient of `self` and `rhs`, rounding the result towards negative infinity.
///
/// This is the same as performing `self / rhs` for all unsigned integers.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
/// #![feature(int_roundings)]
#[doc = "assert_eq!(7_usize.div_floor(4), 1);"]
/// ```
#[unstable(feature = "int_roundings", issue = "88581")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline(always)]
#[track_caller]
pub const fn div_floor(self, rhs: Self) -> Self { self / rhs }
/// Calculates the quotient of `self` and `rhs`, rounding the result towards positive infinity.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(7_usize.div_ceil(4), 2);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[track_caller]
pub const fn div_ceil(self, rhs: Self) -> Self {
let d = self / rhs;
let r = self % rhs;
if r > 0 { d + 1 } else { d }
}
/// Calculates the smallest value greater than or equal to `self` that
/// is a multiple of `rhs`.
///
/// # Panics
///
/// This function will panic if `rhs` is zero.
///
/// ## Overflow behavior
///
/// On overflow, this function will panic if overflow checks are enabled (default in debug
/// mode) and wrap if overflow checks are disabled (default in release mode).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(16_usize.next_multiple_of(8), 16);"]
#[doc = "assert_eq!(23_usize.next_multiple_of(8), 24);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_multiple_of(self, rhs: Self) -> Self {
match self % rhs { 0 => self, r => self + (rhs - r), }
}
/// Calculates the smallest value greater than or equal to `self` that
/// is a multiple of `rhs`. Returns `None` if `rhs` is zero or the
/// operation would result in overflow.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(16_usize.checked_next_multiple_of(8), Some(16));"]
#[doc = "assert_eq!(23_usize.checked_next_multiple_of(8), Some(24));"]
#[doc = "assert_eq!(1_usize.checked_next_multiple_of(0), None);"]
#[doc = "assert_eq!(usize::MAX.checked_next_multiple_of(2), None);"]
/// ```
#[stable(feature = "int_roundings1", since = "1.73.0")]
#[rustc_const_stable(feature = "int_roundings1", since = "1.73.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn checked_next_multiple_of(self, rhs: Self) -> Option<Self> {
match match self.checked_rem(rhs) { Some(x) => x, None => return None, } {
0 => Some(self),
r => self.checked_add(rhs - r),
}
}
/// Returns `true` if `self` is an integer multiple of `rhs`, and false otherwise.
///
/// This function is equivalent to `self % rhs == 0`, except that it will not panic
/// for `rhs == 0`. Instead, `0.is_multiple_of(0) == true`, and for any non-zero `n`,
/// `n.is_multiple_of(0) == false`.
///
/// # Examples
///
/// ```
#[doc = "assert!(6_usize.is_multiple_of(2));"]
#[doc = "assert!(!5_usize.is_multiple_of(2));"]
///
#[doc = "assert!(0_usize.is_multiple_of(0));"]
#[doc = "assert!(!6_usize.is_multiple_of(0));"]
/// ```
#[stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
#[rustc_const_stable(feature = "unsigned_is_multiple_of", since = "1.87.0")]
#[must_use]
#[inline]
pub const fn is_multiple_of(self, rhs: Self) -> bool {
match rhs { 0 => self == 0, _ => self % rhs == 0, }
}
/// Returns `true` if and only if `self == 2^k` for some unsigned integer `k`.
///
/// # Examples
///
/// ```
#[doc = "assert!(16usize.is_power_of_two());"]
#[doc = "assert!(!10usize.is_power_of_two());"]
/// ```
#[must_use]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_is_power_of_two", since = "1.32.0")]
#[inline(always)]
pub const fn is_power_of_two(self) -> bool { self.count_ones() == 1 }
#[inline]
const fn one_less_than_next_power_of_two(self) -> Self {
if self <= 1 { return 0; }
let p = self - 1;
let z = unsafe { intrinsics::ctlz_nonzero(p) };
<usize>::MAX >> z
}
/// Returns the smallest power of two greater than or equal to `self`.
///
/// When return value overflows (i.e., `self > (1 << (N-1))` for type
/// `uN`), it panics in debug mode and the return value is wrapped to 0 in
/// release mode (the only situation in which this method can return 0).
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2usize.next_power_of_two(), 2);"]
#[doc = "assert_eq!(3usize.next_power_of_two(), 4);"]
#[doc = "assert_eq!(0usize.next_power_of_two(), 1);"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
#[rustc_inherit_overflow_checks]
pub const fn next_power_of_two(self) -> Self {
self.one_less_than_next_power_of_two() + 1
}
/// Returns the smallest power of two greater than or equal to `self`. If
/// the next power of two is greater than the type's maximum value,
/// `None` is returned, otherwise the power of two is wrapped in `Some`.
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(2usize.checked_next_power_of_two(), Some(2));"]
#[doc = "assert_eq!(3usize.checked_next_power_of_two(), Some(4));"]
#[doc = "assert_eq!(usize::MAX.checked_next_power_of_two(), None);"]
/// ```
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_pow", since = "1.50.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn checked_next_power_of_two(self) -> Option<Self> {
self.one_less_than_next_power_of_two().checked_add(1)
}
/// Returns the smallest power of two greater than or equal to `n`. If
/// the next power of two is greater than the type's maximum value,
/// the return value is wrapped to `0`.
///
/// # Examples
///
/// ```
/// #![feature(wrapping_next_power_of_two)]
///
#[doc = "assert_eq!(2usize.wrapping_next_power_of_two(), 2);"]
#[doc = "assert_eq!(3usize.wrapping_next_power_of_two(), 4);"]
#[doc = "assert_eq!(usize::MAX.wrapping_next_power_of_two(), 0);"]
/// ```
#[inline]
#[unstable(feature = "wrapping_next_power_of_two", issue = "32463", reason =
"needs decision on wrapping behavior")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
pub const fn wrapping_next_power_of_two(self) -> Self {
self.one_less_than_next_power_of_two().wrapping_add(1)
}
/// Returns the memory representation of this integer as a byte array in
/// big-endian (network) byte order.
///
#[doc =
"
**Note**: This function returns an array of length 2, 4 or 8 bytes
depending on the target pointer size.
"]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234567890123456usize.to_be_bytes();"]
#[doc =
"assert_eq!(bytes, [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_be_bytes(self) -> [u8; size_of::<Self>()] {
self.to_be().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// little-endian byte order.
///
#[doc =
"
**Note**: This function returns an array of length 2, 4 or 8 bytes
depending on the target pointer size.
"]
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234567890123456usize.to_le_bytes();"]
#[doc =
"assert_eq!(bytes, [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);"]
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[inline]
pub const fn to_le_bytes(self) -> [u8; size_of::<Self>()] {
self.to_le().to_ne_bytes()
}
/// Returns the memory representation of this integer as a byte array in
/// native byte order.
///
/// As the target platform's native endianness is used, portable code
/// should use [`to_be_bytes`] or [`to_le_bytes`], as appropriate,
/// instead.
///
#[doc =
"
**Note**: This function returns an array of length 2, 4 or 8 bytes
depending on the target pointer size.
"]
///
/// [`to_be_bytes`]: Self::to_be_bytes
/// [`to_le_bytes`]: Self::to_le_bytes
///
/// # Examples
///
/// ```
#[doc = "let bytes = 0x1234567890123456usize.to_ne_bytes();"]
/// assert_eq!(
/// bytes,
/// if cfg!(target_endian = "big") {
#[doc = " [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]"]
/// } else {
#[doc = " [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]"]
/// }
/// );
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use =
"this returns the result of the operation, \
without modifying the original"]
#[allow(unnecessary_transmutes)]
#[inline]
pub const fn to_ne_bytes(self) -> [u8; size_of::<Self>()] {
unsafe { mem::transmute(self) }
}
/// Creates a native endian integer value from its representation
/// as a byte array in big endian.
///
#[doc =
"
**Note**: This function takes an array of length 2, 4 or 8 bytes
depending on the target pointer size.
"]
///
/// # Examples
///
/// ```
#[doc =
"let value = usize::from_be_bytes([0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]);"]
#[doc = "assert_eq!(value, 0x1234567890123456);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_be_usize(input: &mut &[u8]) -> usize {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<usize>());"]
/// *input = rest;
#[doc = " usize::from_be_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_be_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_be(Self::from_ne_bytes(bytes))
}
/// Creates a native endian integer value from its representation
/// as a byte array in little endian.
///
#[doc =
"
**Note**: This function takes an array of length 2, 4 or 8 bytes
depending on the target pointer size.
"]
///
/// # Examples
///
/// ```
#[doc =
"let value = usize::from_le_bytes([0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]);"]
#[doc = "assert_eq!(value, 0x1234567890123456);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_le_usize(input: &mut &[u8]) -> usize {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<usize>());"]
/// *input = rest;
#[doc = " usize::from_le_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[must_use]
#[inline]
pub const fn from_le_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
Self::from_le(Self::from_ne_bytes(bytes))
}
/// Creates a native endian integer value from its memory representation
/// as a byte array in native endianness.
///
/// As the target platform's native endianness is used, portable code
/// likely wants to use [`from_be_bytes`] or [`from_le_bytes`], as
/// appropriate instead.
///
/// [`from_be_bytes`]: Self::from_be_bytes
/// [`from_le_bytes`]: Self::from_le_bytes
///
#[doc =
"
**Note**: This function takes an array of length 2, 4 or 8 bytes
depending on the target pointer size.
"]
///
/// # Examples
///
/// ```
#[doc = "let value = usize::from_ne_bytes(if cfg!(target_endian = \"big\") {"]
#[doc = " [0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]"]
/// } else {
#[doc = " [0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]"]
/// });
#[doc = "assert_eq!(value, 0x1234567890123456);"]
/// ```
///
/// When starting from a slice rather than an array, fallible conversion APIs can be used:
///
/// ```
#[doc = "fn read_ne_usize(input: &mut &[u8]) -> usize {"]
#[doc = " let (int_bytes, rest) = input.split_at(size_of::<usize>());"]
/// *input = rest;
#[doc = " usize::from_ne_bytes(int_bytes.try_into().unwrap())"]
/// }
/// ```
#[stable(feature = "int_to_from_bytes", since = "1.32.0")]
#[rustc_const_stable(feature = "const_int_conversion", since = "1.44.0")]
#[allow(unnecessary_transmutes)]
#[must_use]
#[inline]
pub const fn from_ne_bytes(bytes: [u8; size_of::<Self>()]) -> Self {
unsafe { mem::transmute(bytes) }
}
/// New code should prefer to use
#[doc = "[`usize::MIN`] instead."]
///
/// Returns the smallest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_promotable]
#[inline(always)]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MIN` associated constant on this type")]
#[rustc_diagnostic_item = "usize_legacy_fn_min_value"]
pub const fn min_value() -> Self { Self::MIN }
/// New code should prefer to use
#[doc = "[`usize::MAX`] instead."]
///
/// Returns the largest value that can be represented by this integer type.
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_promotable]
#[inline(always)]
#[rustc_const_stable(feature = "const_max_value", since = "1.32.0")]
#[deprecated(since = "TBD", note =
"replaced by the `MAX` associated constant on this type")]
#[rustc_diagnostic_item = "usize_legacy_fn_max_value"]
pub const fn max_value() -> Self { Self::MAX }
/// Truncate an integer to an integer of the same size or smaller, preserving the least
/// significant bits.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u8, 120usize.truncate());"]
/// assert_eq!(120u8, 376u32.truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, saturating at numeric bounds
/// instead of truncating.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u8, 120usize.saturating_truncate());"]
/// assert_eq!(255u8, 376u32.saturating_truncate());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn saturating_truncate<Target>(self) -> Target where Self: [const]
traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_saturating_truncate(self)
}
/// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
/// is outside the bounds of the smaller type.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(Some(120u8), 120usize.checked_truncate());"]
/// assert_eq!(None, 376u32.checked_truncate::<u8>());
/// ```
#[must_use =
"this returns the truncated value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn checked_truncate<Target>(self) -> Option<Target> where
Self: [const] traits::TruncateTarget<Target> {
traits::TruncateTarget::internal_checked_truncate(self)
}
/// Widen to an integer of the same size or larger, preserving its value.
///
/// # Examples
///
/// ```
/// #![feature(integer_widen_truncate)]
#[doc = "assert_eq!(120u128, 120u8.widen());"]
/// ```
#[must_use =
"this returns the widened value and does not modify the original"]
#[unstable(feature = "integer_widen_truncate", issue = "154330")]
#[rustc_const_unstable(feature = "integer_widen_truncate", issue = "154330")]
#[inline]
pub const fn widen<Target>(self) -> Target where Self: [const]
traits::WidenTarget<Target> {
traits::WidenTarget::internal_widen(self)
}uint_impl! {
1449Self = usize,
1450 ActualT = u64,
1451 SignedT = isize,
1452 BITS = 64,
1453 BITS_MINUS_ONE = 63,
1454 MAX = 18446744073709551615,
1455 rot = 12,
1456 rot_op = "0xaa00000000006e1",
1457 rot_result = "0x6e10aa",
1458 fsh_op = "0x2fe78e45983acd98",
1459 fshl_result = "0x6e12fe",
1460 fshr_result = "0x6e12fe78e45983ac",
1461 clmul_lhs = "0x7890123456789012",
1462 clmul_rhs = "0xdd358416f52ecd34",
1463 clmul_result = "0xa6299579b980928",
1464 swap_op = "0x1234567890123456",
1465 swapped = "0x5634129078563412",
1466 reversed = "0x6a2c48091e6a2c48",
1467 le_bytes = "[0x56, 0x34, 0x12, 0x90, 0x78, 0x56, 0x34, 0x12]",
1468 be_bytes = "[0x12, 0x34, 0x56, 0x78, 0x90, 0x12, 0x34, 0x56]",
1469 to_xe_bytes_doc = usize_isize_to_xe_bytes_doc!(),
1470 from_xe_bytes_doc = usize_isize_from_xe_bytes_doc!(),
1471 bound_condition = " on 64-bit targets",
1472 }1473/// 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 }1474/// 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 }1475}
14761477impl usize {
1478/// Returns an `usize` where every byte is equal to `x`.
1479#[inline]
1480pub(crate) const fn repeat_u8(x: u8) -> usize {
1481usize::from_ne_bytes([x; size_of::<usize>()])
1482 }
14831484/// Returns an `usize` where every byte pair is equal to `x`.
1485#[inline]
1486pub(crate) const fn repeat_u16(x: u16) -> usize {
1487let mut r = 0usize;
1488let mut i = 0;
1489while i < size_of::<usize>() {
1490// Use `wrapping_shl` to make it work on targets with 16-bit `usize`
1491r = r.wrapping_shl(16) | (x as usize);
1492 i += 2;
1493 }
1494r1495 }
1496}
14971498/// A classification of floating point numbers.
1499///
1500/// This `enum` is used as the return type for [`f32::classify`] and [`f64::classify`]. See
1501/// their documentation for more.
1502///
1503/// # Examples
1504///
1505/// ```
1506/// use std::num::FpCategory;
1507///
1508/// let num = 12.4_f32;
1509/// let inf = f32::INFINITY;
1510/// let zero = 0f32;
1511/// let sub: f32 = 1.1754942e-38;
1512/// let nan = f32::NAN;
1513///
1514/// assert_eq!(num.classify(), FpCategory::Normal);
1515/// assert_eq!(inf.classify(), FpCategory::Infinite);
1516/// assert_eq!(zero.classify(), FpCategory::Zero);
1517/// assert_eq!(sub.classify(), FpCategory::Subnormal);
1518/// assert_eq!(nan.classify(), FpCategory::Nan);
1519/// ```
1520#[derive(#[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl crate::marker::Copy for FpCategory { }Copy, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl crate::clone::Clone for FpCategory {
#[inline]
fn clone(&self) -> FpCategory { *self }
}Clone, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl crate::cmp::PartialEq for FpCategory {
#[inline]
fn eq(&self, other: &FpCategory) -> bool {
let __self_discr = crate::intrinsics::discriminant_value(self);
let __arg1_discr = crate::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl crate::cmp::Eq for FpCategory {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[automatically_derived]
#[stable(feature = "rust1", since = "1.0.0")]
impl crate::fmt::Debug for FpCategory {
#[inline]
fn fmt(&self, f: &mut crate::fmt::Formatter) -> crate::fmt::Result {
crate::fmt::Formatter::write_str(f,
match self {
FpCategory::Nan => "Nan",
FpCategory::Infinite => "Infinite",
FpCategory::Zero => "Zero",
FpCategory::Subnormal => "Subnormal",
FpCategory::Normal => "Normal",
})
}
}Debug)]
1521#[stable(feature = "rust1", since = "1.0.0")]
1522pub enum FpCategory {
1523/// NaN (not a number): this value results from calculations like `(-1.0).sqrt()`.
1524 ///
1525 /// See [the documentation for `f32`](f32) for more information on the unusual properties
1526 /// of NaN.
1527#[stable(feature = "rust1", since = "1.0.0")]
1528Nan,
15291530/// Positive or negative infinity, which often results from dividing a nonzero number
1531 /// by zero.
1532#[stable(feature = "rust1", since = "1.0.0")]
1533Infinite,
15341535/// Positive or negative zero.
1536 ///
1537 /// See [the documentation for `f32`](f32) for more information on the signedness of zeroes.
1538#[stable(feature = "rust1", since = "1.0.0")]
1539Zero,
15401541/// “Subnormal” or “denormal” floating point representation (less precise, relative to
1542 /// their magnitude, than [`Normal`]).
1543 ///
1544 /// Subnormal numbers are larger in magnitude than [`Zero`] but smaller in magnitude than all
1545 /// [`Normal`] numbers.
1546 ///
1547 /// [`Normal`]: Self::Normal
1548 /// [`Zero`]: Self::Zero
1549#[stable(feature = "rust1", since = "1.0.0")]
1550Subnormal,
15511552/// A regular floating point number, not any of the exceptional categories.
1553 ///
1554 /// The smallest positive normal numbers are [`f32::MIN_POSITIVE`] and [`f64::MIN_POSITIVE`],
1555 /// and the largest positive normal numbers are [`f32::MAX`] and [`f64::MAX`]. (Unlike signed
1556 /// integers, floating point numbers are symmetric in their range, so negating any of these
1557 /// constants will produce their negative counterpart.)
1558#[stable(feature = "rust1", since = "1.0.0")]
1559Normal,
1560}
15611562/// Determines if a string of text of that length of that radix could be guaranteed to be
1563/// stored in the given type T.
1564/// Note that if the radix is known to the compiler, it is just the check of digits.len that
1565/// is done at runtime.
1566#[doc(hidden)]
1567#[inline(always)]
1568#[unstable(issue = "none", feature = "std_internals")]
1569pub const fn can_not_overflow<T>(radix: u32, is_signed_ty: bool, digits: &[u8]) -> bool {
1570radix <= 16 && digits.len() <= size_of::<T>() * 2 - is_signed_tyas usize1571}
15721573#[cfg_attr(not(panic = "immediate-abort"), inline(never))]
1574#[cfg_attr(panic = "immediate-abort", inline)]
1575#[cold]
1576#[track_caller]
1577const fn from_ascii_radix_panic(radix: u32) -> ! {
1578{
#[rustc_allow_const_fn_unstable(const_eval_select)]
#[inline(always)]
#[track_caller]
const fn do_panic(radix: u32) -> ! {
{
#[inline]
#[track_caller]
fn runtime(radix: u32) -> ! {
{
{
crate::panicking::panic_fmt(format_args!("from_ascii_radix: radix must lie in the range `[2, 36]` - found {0}",
radix));
}
}
}
#[inline]
#[track_caller]
const fn compiletime(radix: u32) -> ! {
let _ = radix;
{
{
crate::panicking::panic_fmt(format_args!("from_ascii_radix: radix must lie in the range `[2, 36]`"));
}
}
}
const_eval_select((radix,), compiletime, runtime)
}
}
do_panic(radix)
}const_panic!(
1579"from_ascii_radix: radix must lie in the range `[2, 36]`",
1580"from_ascii_radix: radix must lie in the range `[2, 36]` - found {radix}",
1581 radix: u32 = radix,
1582 )1583}
15841585macro_rules!from_str_int_impl {
1586 ($signedness:ident $($int_ty:ty)+) => {$(
1587#[stable(feature = "rust1", since = "1.0.0")]
1588 #[rustc_const_unstable(feature = "const_convert", issue = "143773")]
1589impl const FromStr for $int_ty {
1590type Err = ParseIntError;
15911592/// Parses an integer from a string slice with decimal digits.
1593 ///
1594 /// The characters are expected to be an optional
1595#[doc = sign_dependent_expr!{
1596$signedness ?
1597if signed {
1598" `+` or `-` "
1599}
1600if unsigned {
1601" `+` "
1602}
1603 }]
1604/// sign followed by only digits. Leading and trailing non-digit characters (including
1605 /// whitespace) represent an error. Underscores (which are accepted in Rust literals)
1606 /// also represent an error.
1607 ///
1608 /// # See also
1609 /// For parsing numbers in other bases, such as binary or hexadecimal,
1610 /// see [`from_str_radix`][Self::from_str_radix].
1611 ///
1612 /// # Examples
1613 ///
1614 /// ```
1615 /// use std::str::FromStr;
1616 ///
1617#[doc = concat!("assert_eq!(", stringify!($int_ty), "::from_str(\"+10\"), Ok(10));")]
1618/// ```
1619 /// Trailing space returns error:
1620 /// ```
1621 /// # use std::str::FromStr;
1622 /// #
1623#[doc = concat!("assert!(", stringify!($int_ty), "::from_str(\"1 \").is_err());")]
1624/// ```
1625#[inline]
1626fn from_str(src: &str) -> Result<$int_ty, ParseIntError> {
1627 <$int_ty>::from_str_radix(src, 10)
1628 }
1629 }
16301631impl $int_ty {
1632/// Parses an integer from a string slice with digits in a given base.
1633 ///
1634 /// The string is expected to be an optional
1635#[doc = sign_dependent_expr!{
1636$signedness ?
1637if signed {
1638" `+` or `-` "
1639}
1640if unsigned {
1641" `+` "
1642}
1643 }]
1644/// sign followed by only digits. Leading and trailing non-digit characters (including
1645 /// whitespace) represent an error. Underscores (which are accepted in Rust literals)
1646 /// also represent an error.
1647 ///
1648 /// Digits are a subset of these characters, depending on `radix`:
1649 /// * `0-9`
1650 /// * `a-z`
1651 /// * `A-Z`
1652 ///
1653 /// # Panics
1654 ///
1655 /// This function panics if `radix` is not in the range from 2 to 36.
1656 ///
1657 /// # See also
1658 /// If the string to be parsed is in base 10 (decimal),
1659 /// [`from_str`] or [`str::parse`] can also be used.
1660 ///
1661// FIXME(#122566): These HTML links work around a rustdoc-json test failure.
1662/// [`from_str`]: #method.from_str
1663 /// [`str::parse`]: primitive.str.html#method.parse
1664 ///
1665 /// # Examples
1666 ///
1667 /// ```
1668#[doc = concat!("assert_eq!(", stringify!($int_ty), "::from_str_radix(\"A\", 16), Ok(10));")]
1669/// ```
1670 /// Trailing space returns error:
1671 /// ```
1672#[doc = concat!("assert!(", stringify!($int_ty), "::from_str_radix(\"1 \", 10).is_err());")]
1673/// ```
1674#[stable(feature = "rust1", since = "1.0.0")]
1675 #[rustc_const_stable(feature = "const_int_from_str", since = "1.82.0")]
1676 #[inline]
1677pub const fn from_str_radix(src: &str, radix: u32) -> Result<$int_ty, ParseIntError> {
1678 <$int_ty>::from_ascii_radix(src.as_bytes(), radix)
1679 }
16801681/// Parses an integer from an ASCII-byte slice with decimal digits.
1682 ///
1683 /// The characters are expected to be an optional
1684#[doc = sign_dependent_expr!{
1685$signedness ?
1686if signed {
1687" `+` or `-` "
1688}
1689if unsigned {
1690" `+` "
1691}
1692 }]
1693/// sign followed by only digits. Leading and trailing non-digit characters (including
1694 /// whitespace) represent an error. Underscores (which are accepted in Rust literals)
1695 /// also represent an error.
1696 ///
1697 /// # Examples
1698 ///
1699 /// ```
1700 /// #![feature(int_from_ascii)]
1701 ///
1702#[doc = concat!("assert_eq!(", stringify!($int_ty), "::from_ascii(b\"+10\"), Ok(10));")]
1703/// ```
1704 /// Trailing space returns error:
1705 /// ```
1706 /// # #![feature(int_from_ascii)]
1707 /// #
1708#[doc = concat!("assert!(", stringify!($int_ty), "::from_ascii(b\"1 \").is_err());")]
1709/// ```
1710#[unstable(feature = "int_from_ascii", issue = "134821")]
1711 #[inline]
1712pub const fn from_ascii(src: &[u8]) -> Result<$int_ty, ParseIntError> {
1713 <$int_ty>::from_ascii_radix(src, 10)
1714 }
17151716/// Parses an integer from an ASCII-byte slice with digits in a given base.
1717 ///
1718 /// The characters are expected to be an optional
1719#[doc = sign_dependent_expr!{
1720$signedness ?
1721if signed {
1722" `+` or `-` "
1723}
1724if unsigned {
1725" `+` "
1726}
1727 }]
1728/// sign followed by only digits. Leading and trailing non-digit characters (including
1729 /// whitespace) represent an error. Underscores (which are accepted in Rust literals)
1730 /// also represent an error.
1731 ///
1732 /// Digits are a subset of these characters, depending on `radix`:
1733 /// * `0-9`
1734 /// * `a-z`
1735 /// * `A-Z`
1736 ///
1737 /// # Panics
1738 ///
1739 /// This function panics if `radix` is not in the range from 2 to 36.
1740 ///
1741 /// # Examples
1742 ///
1743 /// ```
1744 /// #![feature(int_from_ascii)]
1745 ///
1746#[doc = concat!("assert_eq!(", stringify!($int_ty), "::from_ascii_radix(b\"A\", 16), Ok(10));")]
1747/// ```
1748 /// Trailing space returns error:
1749 /// ```
1750 /// # #![feature(int_from_ascii)]
1751 /// #
1752#[doc = concat!("assert!(", stringify!($int_ty), "::from_ascii_radix(b\"1 \", 10).is_err());")]
1753/// ```
1754#[unstable(feature = "int_from_ascii", issue = "134821")]
1755 #[inline]
1756pub const fn from_ascii_radix(src: &[u8], radix: u32) -> Result<$int_ty, ParseIntError> {
1757use self::IntErrorKind::*;
1758use self::ParseIntError as PIE;
17591760if 2 > radix || radix > 36 {
1761 from_ascii_radix_panic(radix);
1762 }
17631764if src.is_empty() {
1765return Err(PIE { kind: Empty });
1766 }
17671768#[allow(unused_comparisons)]
1769let is_signed_ty = 0 > <$int_ty>::MIN;
17701771let (is_positive, mut digits) = match src {
1772 [b'+' | b'-'] => {
1773return Err(PIE { kind: InvalidDigit });
1774 }
1775 [b'+', rest @ ..] => (true, rest),
1776 [b'-', rest @ ..] if is_signed_ty => (false, rest),
1777_ => (true, src),
1778 };
17791780let mut result = 0;
17811782macro_rules! unwrap_or_PIE {
1783 ($option:expr, $kind:ident) => {
1784match $option {
1785Some(value) => value,
1786None => return Err(PIE { kind: $kind }),
1787 }
1788 };
1789 }
17901791if can_not_overflow::<$int_ty>(radix, is_signed_ty, digits) {
1792// If the len of the str is short compared to the range of the type
1793 // we are parsing into, then we can be certain that an overflow will not occur.
1794 // This bound is when `radix.pow(digits.len()) - 1 <= T::MAX` but the condition
1795 // above is a faster (conservative) approximation of this.
1796 //
1797 // Consider radix 16 as it has the highest information density per digit and will thus overflow the earliest:
1798 // `u8::MAX` is `ff` - any str of len 2 is guaranteed to not overflow.
1799 // `i8::MAX` is `7f` - only a str of len 1 is guaranteed to not overflow.
1800macro_rules! run_unchecked_loop {
1801 ($unchecked_additive_op:tt) => {{
1802while let [c, rest @ ..] = digits {
1803 result = result * (radix as $int_ty);
1804let x = unwrap_or_PIE!((*c as char).to_digit(radix), InvalidDigit);
1805 result = result $unchecked_additive_op (x as $int_ty);
1806 digits = rest;
1807 }
1808 }};
1809 }
1810if is_positive {
1811run_unchecked_loop!(+)
1812 } else {
1813run_unchecked_loop!(-)
1814 };
1815 } else {
1816macro_rules! run_checked_loop {
1817 ($checked_additive_op:ident, $overflow_err:ident) => {{
1818while let [c, rest @ ..] = digits {
1819// When `radix` is passed in as a literal, rather than doing a slow `imul`
1820 // the compiler can use shifts if `radix` can be expressed as a
1821 // sum of powers of 2 (x*10 can be written as x*8 + x*2).
1822 // When the compiler can't use these optimisations,
1823 // the latency of the multiplication can be hidden by issuing it
1824 // before the result is needed to improve performance on
1825 // modern out-of-order CPU as multiplication here is slower
1826 // than the other instructions, we can get the end result faster
1827 // doing multiplication first and let the CPU spends other cycles
1828 // doing other computation and get multiplication result later.
1829let mul = result.checked_mul(radix as $int_ty);
1830let x = unwrap_or_PIE!((*c as char).to_digit(radix), InvalidDigit) as $int_ty;
1831 result = unwrap_or_PIE!(mul, $overflow_err);
1832 result = unwrap_or_PIE!(<$int_ty>::$checked_additive_op(result, x), $overflow_err);
1833 digits = rest;
1834 }
1835 }};
1836 }
1837if is_positive {
1838run_checked_loop!(checked_add, PosOverflow)
1839 } else {
1840run_checked_loop!(checked_sub, NegOverflow)
1841 };
1842 }
1843Ok(result)
1844 }
1845 }
1846 )*}
1847}
18481849#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
impl const FromStr for i128 {
type Err = ParseIntError;
/// Parses an integer from a string slice with decimal digits.
///
/// The characters are expected to be an optional
#[doc = " `+` or `-` "]
/// sign followed by only digits. Leading and trailing non-digit characters (including
/// whitespace) represent an error. Underscores (which are accepted in Rust literals)
/// also represent an error.
///
/// # See also
/// For parsing numbers in other bases, such as binary or hexadecimal,
/// see [`from_str_radix`][Self::from_str_radix].
///
/// # Examples
///
/// ```
/// use std::str::FromStr;
///
#[doc = "assert_eq!(i128::from_str(\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # use std::str::FromStr;
/// #
#[doc = "assert!(i128::from_str(\"1 \").is_err());"]
/// ```
#[inline]
fn from_str(src: &str) -> Result<i128, ParseIntError> {
<i128>::from_str_radix(src, 10)
}
}
impl i128 {
/// Parses an integer from a string slice with digits in a given base.
///
/// The string is expected to be an optional
#[doc = " `+` or `-` "]
/// sign followed by only digits. Leading and trailing non-digit characters (including
/// whitespace) represent an error. Underscores (which are accepted in Rust literals)
/// also represent an error.
///
/// Digits are a subset of these characters, depending on `radix`:
/// * `0-9`
/// * `a-z`
/// * `A-Z`
///
/// # Panics
///
/// This function panics if `radix` is not in the range from 2 to 36.
///
/// # See also
/// If the string to be parsed is in base 10 (decimal),
/// [`from_str`] or [`str::parse`] can also be used.
///
/// [`from_str`]: #method.from_str
/// [`str::parse`]: primitive.str.html#method.parse
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(i128::from_str_radix(\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
#[doc = "assert!(i128::from_str_radix(\"1 \", 10).is_err());"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_from_str", since = "1.82.0")]
#[inline]
pub const fn from_str_radix(src: &str, radix: u32)
-> Result<i128, ParseIntError> {
<i128>::from_ascii_radix(src.as_bytes(), radix)
}
/// Parses an integer from an ASCII-byte slice with decimal digits.
///
/// The characters are expected to be an optional
#[doc = " `+` or `-` "]
/// sign followed by only digits. Leading and trailing non-digit characters (including
/// whitespace) represent an error. Underscores (which are accepted in Rust literals)
/// also represent an error.
///
/// # Examples
///
/// ```
/// #![feature(int_from_ascii)]
///
#[doc = "assert_eq!(i128::from_ascii(b\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(i128::from_ascii(b\"1 \").is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[inline]
pub const fn from_ascii(src: &[u8]) -> Result<i128, ParseIntError> {
<i128>::from_ascii_radix(src, 10)
}
/// Parses an integer from an ASCII-byte slice with digits in a given base.
///
/// The characters are expected to be an optional
#[doc = " `+` or `-` "]
/// sign followed by only digits. Leading and trailing non-digit characters (including
/// whitespace) represent an error. Underscores (which are accepted in Rust literals)
/// also represent an error.
///
/// Digits are a subset of these characters, depending on `radix`:
/// * `0-9`
/// * `a-z`
/// * `A-Z`
///
/// # Panics
///
/// This function panics if `radix` is not in the range from 2 to 36.
///
/// # Examples
///
/// ```
/// #![feature(int_from_ascii)]
///
#[doc = "assert_eq!(i128::from_ascii_radix(b\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(i128::from_ascii_radix(b\"1 \", 10).is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[inline]
pub const fn from_ascii_radix(src: &[u8], radix: u32)
-> Result<i128, ParseIntError> {
use self::IntErrorKind::*;
use self::ParseIntError as PIE;
if 2 > radix || radix > 36 { from_ascii_radix_panic(radix); }
if src.is_empty() { return Err(PIE { kind: Empty }); }
#[allow(unused_comparisons)]
let is_signed_ty = 0 > <i128>::MIN;
let (is_positive, mut digits) =
match src {
[b'+' | b'-'] => { return Err(PIE { kind: InvalidDigit }); }
[b'+', rest @ ..] => (true, rest),
[b'-', rest @ ..] if is_signed_ty => (false, rest),
_ => (true, src),
};
let mut result = 0;
macro_rules! unwrap_or_PIE {
($option : expr, $kind : ident) =>
{
match $option
{
Some(value) => value, None => return
Err(PIE { kind : $kind }),
}
};
}
if can_not_overflow::<i128>(radix, is_signed_ty, digits) {
macro_rules! run_unchecked_loop {
($unchecked_additive_op : tt) =>
{{
while let [c, rest @ ..] = digits
{
result = result * (radix as i128); let x = unwrap_or_PIE!
((* c as char).to_digit(radix), InvalidDigit); result =
result $unchecked_additive_op(x as i128); digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
result = result * (radix as i128);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result + (x as i128);
digits = rest;
}
}
} else {
{
while let [c, rest @ ..] = digits {
result = result * (radix as i128);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result - (x as i128);
digits = rest;
}
}
};
} else {
macro_rules! run_checked_loop {
($checked_additive_op : ident, $overflow_err : ident) =>
{{
while let [c, rest @ ..] = digits
{
let mul = result.checked_mul(radix as i128); let x =
unwrap_or_PIE! ((* c as char).to_digit(radix), InvalidDigit)
as i128; result = unwrap_or_PIE! (mul, $overflow_err);
result = unwrap_or_PIE!
(< i128 > :: $checked_additive_op(result, x),
$overflow_err); digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
let mul = result.checked_mul(radix as i128);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as i128;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: PosOverflow }),
};
result =
match <i128>::checked_add(result, x) {
Some(value) => value,
None => return Err(PIE { kind: PosOverflow }),
};
digits = rest;
}
}
} else {
{
while let [c, rest @ ..] = digits {
let mul = result.checked_mul(radix as i128);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as i128;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
result =
match <i128>::checked_sub(result, x) {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
digits = rest;
}
}
};
}
Ok(result)
}
}from_str_int_impl! { signed isizei8i16i32i64i128 }1850#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
impl const FromStr for u128 {
type Err = ParseIntError;
/// Parses an integer from a string slice with decimal digits.
///
/// The characters are expected to be an optional
#[doc = " `+` "]
/// sign followed by only digits. Leading and trailing non-digit characters (including
/// whitespace) represent an error. Underscores (which are accepted in Rust literals)
/// also represent an error.
///
/// # See also
/// For parsing numbers in other bases, such as binary or hexadecimal,
/// see [`from_str_radix`][Self::from_str_radix].
///
/// # Examples
///
/// ```
/// use std::str::FromStr;
///
#[doc = "assert_eq!(u128::from_str(\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # use std::str::FromStr;
/// #
#[doc = "assert!(u128::from_str(\"1 \").is_err());"]
/// ```
#[inline]
fn from_str(src: &str) -> Result<u128, ParseIntError> {
<u128>::from_str_radix(src, 10)
}
}
impl u128 {
/// Parses an integer from a string slice with digits in a given base.
///
/// The string is expected to be an optional
#[doc = " `+` "]
/// sign followed by only digits. Leading and trailing non-digit characters (including
/// whitespace) represent an error. Underscores (which are accepted in Rust literals)
/// also represent an error.
///
/// Digits are a subset of these characters, depending on `radix`:
/// * `0-9`
/// * `a-z`
/// * `A-Z`
///
/// # Panics
///
/// This function panics if `radix` is not in the range from 2 to 36.
///
/// # See also
/// If the string to be parsed is in base 10 (decimal),
/// [`from_str`] or [`str::parse`] can also be used.
///
/// [`from_str`]: #method.from_str
/// [`str::parse`]: primitive.str.html#method.parse
///
/// # Examples
///
/// ```
#[doc = "assert_eq!(u128::from_str_radix(\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
#[doc = "assert!(u128::from_str_radix(\"1 \", 10).is_err());"]
/// ```
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_stable(feature = "const_int_from_str", since = "1.82.0")]
#[inline]
pub const fn from_str_radix(src: &str, radix: u32)
-> Result<u128, ParseIntError> {
<u128>::from_ascii_radix(src.as_bytes(), radix)
}
/// Parses an integer from an ASCII-byte slice with decimal digits.
///
/// The characters are expected to be an optional
#[doc = " `+` "]
/// sign followed by only digits. Leading and trailing non-digit characters (including
/// whitespace) represent an error. Underscores (which are accepted in Rust literals)
/// also represent an error.
///
/// # Examples
///
/// ```
/// #![feature(int_from_ascii)]
///
#[doc = "assert_eq!(u128::from_ascii(b\"+10\"), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(u128::from_ascii(b\"1 \").is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[inline]
pub const fn from_ascii(src: &[u8]) -> Result<u128, ParseIntError> {
<u128>::from_ascii_radix(src, 10)
}
/// Parses an integer from an ASCII-byte slice with digits in a given base.
///
/// The characters are expected to be an optional
#[doc = " `+` "]
/// sign followed by only digits. Leading and trailing non-digit characters (including
/// whitespace) represent an error. Underscores (which are accepted in Rust literals)
/// also represent an error.
///
/// Digits are a subset of these characters, depending on `radix`:
/// * `0-9`
/// * `a-z`
/// * `A-Z`
///
/// # Panics
///
/// This function panics if `radix` is not in the range from 2 to 36.
///
/// # Examples
///
/// ```
/// #![feature(int_from_ascii)]
///
#[doc = "assert_eq!(u128::from_ascii_radix(b\"A\", 16), Ok(10));"]
/// ```
/// Trailing space returns error:
/// ```
/// # #![feature(int_from_ascii)]
/// #
#[doc = "assert!(u128::from_ascii_radix(b\"1 \", 10).is_err());"]
/// ```
#[unstable(feature = "int_from_ascii", issue = "134821")]
#[inline]
pub const fn from_ascii_radix(src: &[u8], radix: u32)
-> Result<u128, ParseIntError> {
use self::IntErrorKind::*;
use self::ParseIntError as PIE;
if 2 > radix || radix > 36 { from_ascii_radix_panic(radix); }
if src.is_empty() { return Err(PIE { kind: Empty }); }
#[allow(unused_comparisons)]
let is_signed_ty = 0 > <u128>::MIN;
let (is_positive, mut digits) =
match src {
[b'+' | b'-'] => { return Err(PIE { kind: InvalidDigit }); }
[b'+', rest @ ..] => (true, rest),
[b'-', rest @ ..] if is_signed_ty => (false, rest),
_ => (true, src),
};
let mut result = 0;
macro_rules! unwrap_or_PIE {
($option : expr, $kind : ident) =>
{
match $option
{
Some(value) => value, None => return
Err(PIE { kind : $kind }),
}
};
}
if can_not_overflow::<u128>(radix, is_signed_ty, digits) {
macro_rules! run_unchecked_loop {
($unchecked_additive_op : tt) =>
{{
while let [c, rest @ ..] = digits
{
result = result * (radix as u128); let x = unwrap_or_PIE!
((* c as char).to_digit(radix), InvalidDigit); result =
result $unchecked_additive_op(x as u128); digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
result = result * (radix as u128);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result + (x as u128);
digits = rest;
}
}
} else {
{
while let [c, rest @ ..] = digits {
result = result * (radix as u128);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
};
result = result - (x as u128);
digits = rest;
}
}
};
} else {
macro_rules! run_checked_loop {
($checked_additive_op : ident, $overflow_err : ident) =>
{{
while let [c, rest @ ..] = digits
{
let mul = result.checked_mul(radix as u128); let x =
unwrap_or_PIE! ((* c as char).to_digit(radix), InvalidDigit)
as u128; result = unwrap_or_PIE! (mul, $overflow_err);
result = unwrap_or_PIE!
(< u128 > :: $checked_additive_op(result, x),
$overflow_err); digits = rest;
}
}};
}
if is_positive {
{
while let [c, rest @ ..] = digits {
let mul = result.checked_mul(radix as u128);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as u128;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: PosOverflow }),
};
result =
match <u128>::checked_add(result, x) {
Some(value) => value,
None => return Err(PIE { kind: PosOverflow }),
};
digits = rest;
}
}
} else {
{
while let [c, rest @ ..] = digits {
let mul = result.checked_mul(radix as u128);
let x =
match (*c as char).to_digit(radix) {
Some(value) => value,
None => return Err(PIE { kind: InvalidDigit }),
} as u128;
result =
match mul {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
result =
match <u128>::checked_sub(result, x) {
Some(value) => value,
None => return Err(PIE { kind: NegOverflow }),
};
digits = rest;
}
}
};
}
Ok(result)
}
}from_str_int_impl! { unsigned usizeu8u16u32u64u128 }18511852macro_rules!impl_sealed {
1853 ($($t:ty)*) => {$(
1854/// Allows extension traits within `core`.
1855#[unstable(feature = "sealed", issue = "none")]
1856impl crate::sealed::Sealed for $t {}
1857 )*}
1858}
1859/// Allows extension traits within `core`.
#[unstable(feature = "sealed", issue = "none")]
impl crate::sealed::Sealed for u128 { }impl_sealed! { isizei8i16i32i64i128usizeu8u16u32u64u128 }