+= operation. Read more+= operation. Read more+= operation. Read moremax aggregation.\nNote that the aggregation uses the total order predicate for floating point values,\nwhich means that this value is a negative NaN.min aggregation.\nNote that the aggregation uses the total order predicate for floating point values,\nwhich means that this value is a positive NaN.atomic_internals)&= operation. Read more&= operation. Read more&= operation. Read more|= operation. Read more|= operation. Read more|= operation. Read moreThe unsigned integers will only be BitStore type parameters\nfor handles to unaliased memory, following the normal Rust\nreference rules.
Self and Self::Alias be equal\nin representation. This is true by fiat for all types except the\nunsigned integers. Read moreBitSlice. It\nis always one of the unsigned integer fundamentals.BitStore implementor that is known to be alias-safe. It is\nused when a BitSlice introduces multiple handles that view the same\nmemory location, and at least one of them has write capabilities to it.\nIt must have the same underlying memory type, and can only change access\npatterns or public-facing usage.::Alias. It is used when a BitSlice removes the\nconditions that required a T -> T::Alias transition.::Access\nrules. This may be called when the value is aliased by a write-capable\nreference.::Access\nconstraints.^= operation. Read more^= operation. Read more^= operation. Read moreNone instead of panicking on division by zero\nand instead of wrapping around on underflow and overflow.None is returned.value is within the range for valid instances of this type,\nreturns Some(converted_value), otherwise, returns None. Read moreC into the underlying integral type. This\nmostly exists otherwise generic code would need unsafe for the value as integer Read moreReader].core_intrinsics_fallbacks)super::disjoint_bitor; we just need the trait indirection to handle\ndifferent types since calling intrinsics with generics doesn’t work.This operation rounds towards zero, truncating any\nfractional part of the exact result.
\nThis operation will panic if other == 0.
/= operation. Read moreSame as self /= other.get(), but because other is a NonZero<_>,\nthere’s never a runtime check for division-by-zero.
This operation rounds towards zero, truncating any fractional\npart of the exact result, and cannot panic.
\n/= operation. Read more/= operation. Read moreself into buf in the expected format for the database.rem_euclid. Read moreself (mod v). Read moredst must be exactly REQUIRED_SPACE bytes.src must be exactly REQUIRED_SPACE bytes.None if dst\ndoesn’t provide enough space to encode this integer. Read moreFixedInt] as [Bytes], the little-endian representation\nof self in the stack.switch_endianness() on\nthe returned value if the source was not encoded in little-endian.&Self. Read moreisize to return an optional value of this type. If the\nvalue cannot be represented by this type, then None is returned.i8 to return an optional value of this type. If the\nvalue cannot be represented by this type, then None is returned.i16 to return an optional value of this type. If the\nvalue cannot be represented by this type, then None is returned.i32 to return an optional value of this type. If the\nvalue cannot be represented by this type, then None is returned.i64 to return an optional value of this type. If the\nvalue cannot be represented by this type, then None is returned.i128 to return an optional value of this type. If the\nvalue cannot be represented by this type, then None is returned. Read moreusize to return an optional value of this type. If the\nvalue cannot be represented by this type, then None is returned.u8 to return an optional value of this type. If the\nvalue cannot be represented by this type, then None is returned.u16 to return an optional value of this type. If the\nvalue cannot be represented by this type, then None is returned.u32 to return an optional value of this type. If the\nvalue cannot be represented by this type, then None is returned.u64 to return an optional value of this type. If the\nvalue cannot be represented by this type, then None is returned.u128 to return an optional value of this type. If the\nvalue cannot be represented by this type, then None is returned. Read moreType in its binary format. Read moreType.Parses an integer from a string slice with decimal digits.
\nThe characters are expected to be an optional\n+\nsign followed by only digits. Leading and trailing non-digit characters (including\nwhitespace) represent an error. Underscores (which are accepted in Rust literals)\nalso represent an error.
use std::str::FromStr;\n\nassert_eq!(u32::from_str(\"+10\"), Ok(10));Trailing space returns error:
\n\nassert!(u32::from_str(\"1 \").is_err());core_intrinsics_fallbacks)super::unchecked_funnel_shl; we just need the trait indirection to handle\ndifferent types since calling intrinsics with generics doesn’t work.core_intrinsics_fallbacks)super::unchecked_funnel_shr; we just need the trait indirection to handle\ndifferent types since calling intrinsics with generics doesn’t work.Unsigned integer division. Returns the same result as div (/).
Unsigned integer modulo operation. Returns the same result as rem (%).
Calculates the Greatest Common Divisor (GCD) of the number and other
Calculates the Lowest Common Multiple (LCM) of the number and other.
Calculates the Greatest Common Divisor (GCD) and\nLowest Common Multiple (LCM) of the number and other.
Returns true if the number is a multiple of other.
Simultaneous truncated integer division and modulus.
\nis_multiple_of instead.(quotient, remainder). Read moreself.self.self.self.self.self.n, wrapping the\ntruncated bits to the end of the resulting integer. Read moren, wrapping the\ntruncated bits to the beginning of the resulting integer. Read moreself + rhs, returning None if\noverflow occurred.self - rhs, returning None if\noverflow occurred.self * rhs, returning None\nif overflow occurred.self / rhs, returning None if\nrhs == 0 or the division results in overflow.self.div_euclid(rhs), returning\nNone if rhs == 0 or the division results in overflow.self % rhs, returning None if\nrhs == 0 or the division results in overflow.self.rem_euclid(rhs), returning\nNone if rhs == 0 or the division results in overflow.self << rhs, returning None if rhs is\nlarger than or equal to the number of bits in self.self >> rhs, returning None if rhs\nis larger than or equal to the number of bits in self.self.pow(exp), returning None if\noverflow occurred.self + rhs, saturating at the\nnumeric bounds instead of overflowing.self - rhs, saturating at the\nnumeric bounds instead of overflowing.self * rhs, saturating at\nthe numeric bounds instead of overflowing.self.pow(exp), saturating\nat the numeric bounds instead of overflowing.self + rhs, wrapping around at\nthe boundary of the type.self - rhs, wrapping around\nat the boundary of the type.self * rhs, wrapping\naround at the boundary of the type.self / rhs, wrapping around at\nthe boundary of the type. Read moreself.div_euclid(rhs), wrapping\naround at the boundary of the type. Read moreself % rhs, wrapping around at\nthe boundary of the type. Read moreself.rem_euclid(rhs), wrapping\naround at the boundary of the type. Read more-self, wrapping around at the\nboundary of the type. Read moreself << mask(rhs), where mask\nremoves any high-order bits of rhs that would cause the shift to\nexceed the bit-width of the type. Read moreself >> mask(rhs), where mask\nremoves any high-order bits of rhs that would cause the shift to\nexceed the bit-width of the type. Read moreself.pow(exp), wrapping\naround at the boundary of the type.self.div_euclid(rhs). Read moreself.rem_euclid(rhs). Read moreexp, using exponentiation by squaring. Read moreself (mod rhs). Read moreself to a BigInt.self to a BigUint.Self. Read moreliteral expression containing a u32
\ngoogle.protobuf.UInt32Value
self. Read moreself.*self = (*self * a) + b*= operation. Read more*= operation. Read more*= operation. Read moregoogle.protobuf.UInt32Value
Message.\nThis name is the same as it appears in the source .proto file, e.g. FooBar.., e.g. google.protobuf.Message, which by default is the full name with a\nleading slash, but may also include a leading domain name, e.g.\ntype.googleapis.com/google.profile.Person.\nThis can be used when serializing into the google.protobuf.Any type.Message.\nIt’s prefixed with the package name and names of any parent messages,\ne.g. google.rpc.BadRequest.FieldViolation.\nBy default, this is the package name followed by the message name.\nFully-qualified names must be unique within a domain of Type URLs.2..=36). Read moreself. Read moreself. Read moreself. Read moreself. Read moreself. Read moreself. Read moren, wrapping\nthe truncated bits to the end of the resulting integer. Read moren, wrapping\nthe truncated bits to the beginning of the resulting integer. Read moren, filling\nzeros in the least significant bits. Read moren, copying\nthe “sign bit” in the most significant bits even for unsigned types. Read moren, filling\nzeros in the least significant bits. Read moren, filling\nzeros in the most significant bits. Read moreself + other.self - other.This operation satisfies n % d == n - (n / d) * d. The\nresult has the same sign as the left operand.
This operation will panic if other == 0.
%= operation. Read more%= operation. Read more%= operation. Read more%= operation. Read more%= operation. Read moreThis operation satisfies n % d == n - (n / d) * d, and cannot panic.
%= operation. Read more%= operation. Read moreUniformSampler implementation supporting type X.UniformSampler implementation supporting type X.self + other, saturating at the relevant high or low boundary of\nthe type.self * other, saturating at the relevant high or low boundary of\nthe type.self - other, saturating at the relevant high or low boundary of\nthe type.Implement [ScalarRef] for primitive types. Note that primitive types are both [Scalar] and [ScalarRef].
Scalar] type.block, byte position inside\nblock byte, and block size bs.bs.<<= operation. Read more<<= operation. Read more<<= operation. Read more<<= operation. Read more<<= operation. Read more<<= operation. Read more<<= operation. Read more<<= operation. Read more<<= operation. Read more<<= operation. Read more<<= operation. Read more<<= operation. Read more<<= operation. Read more<<= operation. Read more<<= operation. Read more<<= operation. Read more<<= operation. Read more<<= operation. Read more<<= operation. Read more<<= operation. Read more<<= operation. Read more<<= operation. Read more<<= operation. Read more<<= operation. Read more<<= operation. Read more>>= operation. Read more>>= operation. Read more>>= operation. Read more>>= operation. Read more>>= operation. Read more>>= operation. Read more>>= operation. Read more>>= operation. Read more>>= operation. Read more>>= operation. Read more>>= operation. Read more>>= operation. Read more>>= operation. Read more>>= operation. Read more>>= operation. Read more>>= operation. Read more>>= operation. Read more>>= operation. Read more>>= operation. Read more>>= operation. Read more>>= operation. Read more>>= operation. Read more>>= operation. Read more>>= operation. Read more>>= operation. Read moreDisplay::fmt. Read moreusize to this implementation’s representation. Read morestep_trait)step_trait)step_trait)step_trait)step_trait)start to end\nlike Iterator::size_hint(). Read more-= operation. Read more-= operation. Read more-= operation. Read moreliteral expression containing a u32
\nself to a BigUint.self to an isize. If the value cannot be\nrepresented by an isize, then None is returned.self to an i8. If the value cannot be\nrepresented by an i8, then None is returned.self to an i16. If the value cannot be\nrepresented by an i16, then None is returned.self to an i32. If the value cannot be\nrepresented by an i32, then None is returned.self to an i64. If the value cannot be\nrepresented by an i64, then None is returned.self to an i128. If the value cannot be\nrepresented by an i128 (i64 under the default implementation), then\nNone is returned. Read moreself to a usize. If the value cannot be\nrepresented by a usize, then None is returned.self to a u8. If the value cannot be\nrepresented by a u8, then None is returned.self to a u16. If the value cannot be\nrepresented by a u16, then None is returned.self to a u32. If the value cannot be\nrepresented by a u32, then None is returned.self to a u64. If the value cannot be\nrepresented by a u64, then None is returned.self to a u128. If the value cannot be\nrepresented by a u128 (u64 under the default implementation), then\nNone is returned. Read moreself into the binary format of the specified\nPostgres Type, appending it to out. Read moreType.proc_macro_totokens)proc_macro_totokens)proc_macro_totokens)Try to convert a Decimal to u32 by truncating and returning the integer component.
Can fail if the Decimal is out of range for u32.
Tries to create the target number type from a source\nnumber type. This returns an error if the source value\nis outside of the range of the target type.
\nTries to create the target number type from a source\nnumber type. This returns an error if the source value\nis outside of the range of the target type.
\nTries to create the target number type from a source\nnumber type. This returns an error if the source value\nis outside of the range of the target type.
\nTries to create the target number type from a source\nnumber type. This returns an error if the source value\nis outside of the range of the target type.
\nTries to create the target number type from a source\nnumber type. This returns an error if the source value\nis outside of the range of the target type.
\nTries to create the target number type from a source\nnumber type. This returns an error if the source value\nis outside of the range of the target type.
\nTries to create the target number type from a source\nnumber type. This returns an error if the source value\nis outside of the range of the target type.
\nTries to create the target number type from a source\nnumber type. This returns an error if the source value\nis outside of the range of the target type.
\nTries to create the target number type from a source\nnumber type. This returns an error if the source value\nis outside of the range of the target type.
\nsource as a &Self with\na DST length equal to count. Read moresource as a &Self with\na DST length equal to count. Read moresource as a &mut Self\nwith a DST length equal to count. Read moresource as a &mut Self\nwith a DST length equal to count. Read moretrue if and only if self == 2^k for some k.self. Read moren. If the\nnext power of two is greater than the type’s maximum value, None is\nreturned, otherwise the power of two is wrapped in Some.required_space() bytes long.\nThe number of bytes taken by the encoded integer is returned.required_space() bytes long.required_space() bytes long.\nThe number of bytes taken by the encoded integer is returned.required_space() bytes long.pos in the verifier’s buffer.\nShould not need to be called directly.self + other, wrapping around at the boundary of\nthe type.self * other, wrapping around at the boundary\nof the type.-self,\nwrapping around at the boundary of the type. Read moreself - other, wrapping around at the boundary\nof the type.write_to_parts, and discards any\nPart annotations.Part annotations to the given sink. Errors from the\nsink are bubbled up. The default implementation delegates to write_to,\nand doesn’t produce any Part annotations.String with the data from this Writeable. Like ToString,\nbut smaller and faster. Read moreSelf<'a>’s lifetime. Read moreself between &'a mut Self<'static> and &'a mut Self<'a>,\nand pass it to f. Read moreint_format_into)Allows users to write an integer (in signed decimal format) into a variable buf of\ntype NumBuffer that is passed by the caller by mutable reference.
#![feature(int_format_into)]\nuse core::fmt::NumBuffer;\n\nlet n = 0u32;\nlet mut buf = NumBuffer::new();\nassert_eq!(n.format_into(&mut buf), \"0\");\n\nlet n1 = 32u32;\nassert_eq!(n1.format_into(&mut buf), \"32\");\n\nlet n2 = u32 :: MAX;\nassert_eq!(n2.format_into(&mut buf), u32 :: MAX.to_string());The smallest value that can be represented by this integer type.
\nassert_eq!(u32::MIN, 0);The largest value that can be represented by this integer type\n(232 − 1).
\nassert_eq!(u32::MAX, 4294967295);Returns the number of ones in the binary representation of self.
let n = 0b01001100u32;\nassert_eq!(n.count_ones(), 3);\n\nlet max = u32::MAX;\nassert_eq!(max.count_ones(), 32);\n\nlet zero = 0u32;\nassert_eq!(zero.count_ones(), 0);Returns the number of zeros in the binary representation of self.
let zero = 0u32;\nassert_eq!(zero.count_zeros(), 32);\n\nlet max = u32::MAX;\nassert_eq!(max.count_zeros(), 0);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\nilog2 function which returns a consistent number, even if the type widens.
let n = u32::MAX >> 2;\nassert_eq!(n.leading_zeros(), 2);\n\nlet zero = 0u32;\nassert_eq!(zero.leading_zeros(), 32);\n\nlet max = u32::MAX;\nassert_eq!(max.leading_zeros(), 0);Returns the number of trailing zeros in the binary representation\nof self.
let n = 0b0101000u32;\nassert_eq!(n.trailing_zeros(), 3);\n\nlet zero = 0u32;\nassert_eq!(zero.trailing_zeros(), 32);\n\nlet max = u32::MAX;\nassert_eq!(max.trailing_zeros(), 0);Returns the number of leading ones in the binary representation of self.
let n = !(u32::MAX >> 2);\nassert_eq!(n.leading_ones(), 2);\n\nlet zero = 0u32;\nassert_eq!(zero.leading_ones(), 0);\n\nlet max = u32::MAX;\nassert_eq!(max.leading_ones(), 32);Returns the number of trailing ones in the binary representation\nof self.
let n = 0b1010111u32;\nassert_eq!(n.trailing_ones(), 3);\n\nlet zero = 0u32;\nassert_eq!(zero.trailing_ones(), 0);\n\nlet max = u32::MAX;\nassert_eq!(max.trailing_ones(), 32);uint_bit_width)Returns the minimum number of bits required to represent self.
This method returns zero if self is zero.
#![feature(uint_bit_width)]\n\nassert_eq!(0_u32.bit_width(), 0);\nassert_eq!(0b111_u32.bit_width(), 3);\nassert_eq!(0b1110_u32.bit_width(), 4);\nassert_eq!(u32::MAX.bit_width(), 32);isolate_most_least_significant_one)Returns self with only the most significant bit set, or 0 if\nthe input is 0.
#![feature(isolate_most_least_significant_one)]\n\nlet n: u32 = 0b_01100100;\n\nassert_eq!(n.isolate_highest_one(), 0b_01000000);\nassert_eq!(0_u32.isolate_highest_one(), 0);isolate_most_least_significant_one)Returns self with only the least significant bit set, or 0 if\nthe input is 0.
#![feature(isolate_most_least_significant_one)]\n\nlet n: u32 = 0b_01100100;\n\nassert_eq!(n.isolate_lowest_one(), 0b_00000100);\nassert_eq!(0_u32.isolate_lowest_one(), 0);int_lowest_highest_one)Returns the index of the highest bit set to one in self, or None\nif self is 0.
#![feature(int_lowest_highest_one)]\n\nassert_eq!(0x0_u32.highest_one(), None);\nassert_eq!(0x1_u32.highest_one(), Some(0));\nassert_eq!(0x10_u32.highest_one(), Some(4));\nassert_eq!(0x1f_u32.highest_one(), Some(4));int_lowest_highest_one)Returns the index of the lowest bit set to one in self, or None\nif self is 0.
#![feature(int_lowest_highest_one)]\n\nassert_eq!(0x0_u32.lowest_one(), None);\nassert_eq!(0x1_u32.lowest_one(), Some(0));\nassert_eq!(0x10_u32.lowest_one(), Some(4));\nassert_eq!(0x1f_u32.lowest_one(), Some(0));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\nthe same.
let n = u32::MAX;\n\nassert_eq!(n.cast_signed(), -1i32);Shifts the bits to the left by a specified amount, n,\nwrapping the truncated bits to the end of the resulting integer.
Please note this isn’t the same operation as the << shifting operator!
let n = 0x10000b3u32;\nlet m = 0xb301;\n\nassert_eq!(n.rotate_left(8), m);Shifts the bits to the right by a specified amount, n,\nwrapping the truncated bits to the beginning of the resulting\ninteger.
Please note this isn’t the same operation as the >> shifting operator!
let n = 0xb301u32;\nlet m = 0x10000b3;\n\nassert_eq!(n.rotate_right(8), m);funnel_shifts)Performs a left funnel shift (concatenates self with rhs, with self\nmaking up the most significant half, then shifts the combined value left\nby n, and most significant half is extracted to produce the result).
Please note this isn’t the same operation as the << shifting operator or\nrotate_left, although a.funnel_shl(a, n) is equivalent\nto a.rotate_left(n).
If n is greater than or equal to the number of bits in self
Basic usage:
\n\n#![feature(funnel_shifts)]\nlet a = 0x10000b3u32;\nlet b = 0x2fe78e45u32;\nlet m = 0xb32f;\n\nassert_eq!(a.funnel_shl(b, 8), m);funnel_shifts)Performs a right funnel shift (concatenates self and rhs, with self\nmaking up the most significant half, then shifts the combined value right\nby n, and least significant half is extracted to produce the result).
Please note this isn’t the same operation as the >> shifting operator or\nrotate_right, although a.funnel_shr(a, n) is equivalent\nto a.rotate_right(n).
If n is greater than or equal to the number of bits in self
Basic usage:
\n\n#![feature(funnel_shifts)]\nlet a = 0x10000b3u32;\nlet b = 0x2fe78e45u32;\nlet m = 0xb32fe78e;\n\nassert_eq!(a.funnel_shr(b, 8), m);Reverses the byte order of the integer.
\nlet n = 0x12345678u32;\nlet m = n.swap_bytes();\n\nassert_eq!(m, 0x78563412);Reverses the order of bits in the integer. The least significant bit becomes the most significant bit,\nsecond least-significant bit becomes second most-significant bit, etc.
\nlet n = 0x12345678u32;\nlet m = n.reverse_bits();\n\nassert_eq!(m, 0x1e6a2c48);\nassert_eq!(0, 0u32.reverse_bits());Converts an integer from big endian to the target’s endianness.
\nOn big endian this is a no-op. On little endian the bytes are\nswapped.
\nlet n = 0x1Au32;\n\nif cfg!(target_endian = \"big\") {\n assert_eq!(u32::from_be(n), n)\n} else {\n assert_eq!(u32::from_be(n), n.swap_bytes())\n}Converts an integer from little endian to the target’s endianness.
\nOn little endian this is a no-op. On big endian the bytes are\nswapped.
\nlet n = 0x1Au32;\n\nif cfg!(target_endian = \"little\") {\n assert_eq!(u32::from_le(n), n)\n} else {\n assert_eq!(u32::from_le(n), n.swap_bytes())\n}Converts self to big endian from the target’s endianness.
On big endian this is a no-op. On little endian the bytes are\nswapped.
\nlet n = 0x1Au32;\n\nif cfg!(target_endian = \"big\") {\n assert_eq!(n.to_be(), n)\n} else {\n assert_eq!(n.to_be(), n.swap_bytes())\n}Converts self to little endian from the target’s endianness.
On little endian this is a no-op. On big endian the bytes are\nswapped.
\nlet n = 0x1Au32;\n\nif cfg!(target_endian = \"little\") {\n assert_eq!(n.to_le(), n)\n} else {\n assert_eq!(n.to_le(), n.swap_bytes())\n}Checked integer addition. Computes self + rhs, returning None\nif overflow occurred.
assert_eq!((u32::MAX - 2).checked_add(1), Some(u32::MAX - 1));\nassert_eq!((u32::MAX - 2).checked_add(3), None);Strict integer addition. Computes self + rhs, panicking\nif overflow occurred.
This function will always panic on overflow, regardless of whether overflow checks are enabled.
\nassert_eq!((u32::MAX - 2).strict_add(1), u32::MAX - 1);The following panics because of overflow:
\n\nlet _ = (u32::MAX - 2).strict_add(3);Unchecked integer addition. Computes self + rhs, assuming overflow\ncannot occur.
Calling x.unchecked_add(y) is semantically equivalent to calling\nx.checked_add(y).unwrap_unchecked().
If you’re just trying to avoid the panic in debug mode, then do not\nuse this. Instead, you’re looking for wrapping_add.
This results in undefined behavior when\nself + rhs > u32::MAX or self + rhs < u32::MIN,\ni.e. when checked_add would return None.
Checked addition with a signed integer. Computes self + rhs,\nreturning None if overflow occurred.
assert_eq!(1u32.checked_add_signed(2), Some(3));\nassert_eq!(1u32.checked_add_signed(-2), None);\nassert_eq!((u32::MAX - 2).checked_add_signed(3), None);Strict addition with a signed integer. Computes self + rhs,\npanicking if overflow occurred.
This function will always panic on overflow, regardless of whether overflow checks are enabled.
\nassert_eq!(1u32.strict_add_signed(2), 3);The following panic because of overflow:
\n\nlet _ = 1u32.strict_add_signed(-2);let _ = (u32::MAX - 2).strict_add_signed(3);Checked integer subtraction. Computes self - rhs, returning\nNone if overflow occurred.
assert_eq!(1u32.checked_sub(1), Some(0));\nassert_eq!(0u32.checked_sub(1), None);Strict integer subtraction. Computes self - rhs, panicking if\noverflow occurred.
This function will always panic on overflow, regardless of whether overflow checks are enabled.
\nassert_eq!(1u32.strict_sub(1), 0);The following panics because of overflow:
\n\nlet _ = 0u32.strict_sub(1);Unchecked integer subtraction. Computes self - rhs, assuming overflow\ncannot occur.
Calling x.unchecked_sub(y) is semantically equivalent to calling\nx.checked_sub(y).unwrap_unchecked().
If you’re just trying to avoid the panic in debug mode, then do not\nuse this. Instead, you’re looking for wrapping_sub.
If you find yourself writing code like this:
\n\nif foo >= bar {\n // SAFETY: just checked it will not overflow\n let diff = unsafe { foo.unchecked_sub(bar) };\n // ... use diff ...\n}Consider changing it to
\n\nif let Some(diff) = foo.checked_sub(bar) {\n // ... use diff ...\n}As that does exactly the same thing – including telling the optimizer\nthat the subtraction cannot overflow – but avoids needing unsafe.
This results in undefined behavior when\nself - rhs > u32::MAX or self - rhs < u32::MIN,\ni.e. when checked_sub would return None.
Checked subtraction with a signed integer. Computes self - rhs,\nreturning None if overflow occurred.
assert_eq!(1u32.checked_sub_signed(2), None);\nassert_eq!(1u32.checked_sub_signed(-2), Some(3));\nassert_eq!((u32::MAX - 2).checked_sub_signed(-4), None);Strict subtraction with a signed integer. Computes self - rhs,\npanicking if overflow occurred.
This function will always panic on overflow, regardless of whether overflow checks are enabled.
\nassert_eq!(3u32.strict_sub_signed(2), 1);The following panic because of overflow:
\n\nlet _ = 1u32.strict_sub_signed(2);let _ = (u32::MAX).strict_sub_signed(-1);Checked integer subtraction. Computes self - rhs and checks if the result fits into an i32, returning None if overflow occurred.
assert_eq!(10u32.checked_signed_diff(2), Some(8));\nassert_eq!(2u32.checked_signed_diff(10), Some(-8));\nassert_eq!(u32::MAX.checked_signed_diff(i32::MAX as u32), None);\nassert_eq!((i32::MAX as u32).checked_signed_diff(u32::MAX), Some(i32::MIN));\nassert_eq!((i32::MAX as u32 + 1).checked_signed_diff(0), None);\nassert_eq!(u32::MAX.checked_signed_diff(u32::MAX), Some(0));Checked integer multiplication. Computes self * rhs, returning\nNone if overflow occurred.
assert_eq!(5u32.checked_mul(1), Some(5));\nassert_eq!(u32::MAX.checked_mul(2), None);Strict integer multiplication. Computes self * rhs, panicking if\noverflow occurred.
This function will always panic on overflow, regardless of whether overflow checks are enabled.
\nassert_eq!(5u32.strict_mul(1), 5);The following panics because of overflow:
\n\nlet _ = u32::MAX.strict_mul(2);Unchecked integer multiplication. Computes self * rhs, assuming overflow\ncannot occur.
Calling x.unchecked_mul(y) is semantically equivalent to calling\nx.checked_mul(y).unwrap_unchecked().
If you’re just trying to avoid the panic in debug mode, then do not\nuse this. Instead, you’re looking for wrapping_mul.
This results in undefined behavior when\nself * rhs > u32::MAX or self * rhs < u32::MIN,\ni.e. when checked_mul would return None.
Checked integer division. Computes self / rhs, returning None\nif rhs == 0.
assert_eq!(128u32.checked_div(2), Some(64));\nassert_eq!(1u32.checked_div(0), None);Strict integer division. Computes self / rhs.
Strict division on unsigned types is just normal division. There’s no\nway overflow could ever happen. This function exists so that all\noperations are accounted for in the strict operations.
\nThis function will panic if rhs is zero.
assert_eq!(100u32.strict_div(10), 10);The following panics because of division by zero:
\n\nlet _ = (1u32).strict_div(0);Checked Euclidean division. Computes self.div_euclid(rhs), returning None\nif rhs == 0.
assert_eq!(128u32.checked_div_euclid(2), Some(64));\nassert_eq!(1u32.checked_div_euclid(0), None);Strict Euclidean division. Computes self.div_euclid(rhs).
Strict division on unsigned types is just normal division. There’s no\nway overflow could ever happen. This function exists so that all\noperations are accounted for in the strict operations. Since, for the\npositive integers, all common definitions of division are equal, this\nis exactly equal to self.strict_div(rhs).
This function will panic if rhs is zero.
assert_eq!(100u32.strict_div_euclid(10), 10);The following panics because of division by zero:
\n\nlet _ = (1u32).strict_div_euclid(0);exact_div)Checked integer division without remainder. Computes self / rhs,\nreturning None if rhs == 0 or if self % rhs != 0.
#![feature(exact_div)]\nassert_eq!(64u32.checked_exact_div(2), Some(32));\nassert_eq!(64u32.checked_exact_div(32), Some(2));\nassert_eq!(64u32.checked_exact_div(0), None);\nassert_eq!(65u32.checked_exact_div(2), None);exact_div)exact_div)Unchecked integer division without remainder. Computes self / rhs.
This results in undefined behavior when rhs == 0 or self % rhs != 0,\ni.e. when checked_exact_div would return None.
Checked integer remainder. Computes self % rhs, returning None\nif rhs == 0.
assert_eq!(5u32.checked_rem(2), Some(1));\nassert_eq!(5u32.checked_rem(0), None);Strict integer remainder. Computes self % rhs.
Strict remainder calculation on unsigned types is just the regular\nremainder calculation. There’s no way overflow could ever happen.\nThis function exists so that all operations are accounted for in the\nstrict operations.
\nThis function will panic if rhs is zero.
assert_eq!(100u32.strict_rem(10), 0);The following panics because of division by zero:
\n\nlet _ = 5u32.strict_rem(0);Checked Euclidean modulo. Computes self.rem_euclid(rhs), returning None\nif rhs == 0.
assert_eq!(5u32.checked_rem_euclid(2), Some(1));\nassert_eq!(5u32.checked_rem_euclid(0), None);Strict Euclidean modulo. Computes self.rem_euclid(rhs).
Strict modulo calculation on unsigned types is just the regular\nremainder calculation. There’s no way overflow could ever happen.\nThis function exists so that all operations are accounted for in the\nstrict operations. Since, for the positive integers, all common\ndefinitions of division are equal, this is exactly equal to\nself.strict_rem(rhs).
This function will panic if rhs is zero.
assert_eq!(100u32.strict_rem_euclid(10), 0);The following panics because of division by zero:
\n\nlet _ = 5u32.strict_rem_euclid(0);disjoint_bitor)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\nuse addition on some platforms and bitwise or on other platforms, based\non exactly which instructions combine better with whatever else you’re\ndoing. Note that there’s no reason to bother using this for places\nwhere it’s clear from the operations involved that they can’t overlap.\nFor example, if you’re combining u16s into a u32 with\n((a as u32) << 16) | (b as u32), that’s fine, as the backend will\nknow those sides of the | are disjoint without needing help.
#![feature(disjoint_bitor)]\n\n// SAFETY: `1` and `4` have no bits in common.\nunsafe {\n assert_eq!(1_u32.unchecked_disjoint_bitor(4), 5);\n}Requires that (self & other) == 0, otherwise it’s immediate UB.
Equivalently, requires that (self | other) == (self + other).
Returns the logarithm of the number with respect to an arbitrary base,\nrounded down.
\nThis method might not be optimized owing to implementation details;\nilog2 can produce results more efficiently for base 2, and ilog10\ncan produce results more efficiently for base 10.
This function will panic if self is zero, or if base is less than 2.
assert_eq!(5u32.ilog(5), 1);Returns the logarithm of the number with respect to an arbitrary base,\nrounded down.
\nReturns 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;\nchecked_ilog2 can produce results more efficiently for base 2, and\nchecked_ilog10 can produce results more efficiently for base 10.
assert_eq!(5u32.checked_ilog(5), Some(1));Returns the base 2 logarithm of the number, rounded down.
\nReturns None if the number is zero.
assert_eq!(2u32.checked_ilog2(), Some(1));Returns the base 10 logarithm of the number, rounded down.
\nReturns None if the number is zero.
assert_eq!(10u32.checked_ilog10(), Some(1));Checked negation. Computes -self, returning None unless self == 0.
Note that negating any positive integer will overflow.
\nassert_eq!(0u32.checked_neg(), Some(0));\nassert_eq!(1u32.checked_neg(), None);Strict negation. Computes -self, panicking unless self == 0.
Note that negating any positive integer will overflow.
\nThis function will always panic on overflow, regardless of whether overflow checks are enabled.
\nassert_eq!(0u32.strict_neg(), 0);The following panics because of overflow:
\n\nlet _ = 1u32.strict_neg();Checked shift left. Computes self << rhs, returning None\nif rhs is larger than or equal to the number of bits in self.
assert_eq!(0x1u32.checked_shl(4), Some(0x10));\nassert_eq!(0x10u32.checked_shl(129), None);\nassert_eq!(0x10u32.checked_shl(31), Some(0));Strict shift left. Computes self << rhs, panicking if rhs is larger\nthan or equal to the number of bits in self.
This function will always panic on overflow, regardless of whether overflow checks are enabled.
\nassert_eq!(0x1u32.strict_shl(4), 0x10);The following panics because of overflow:
\n\nlet _ = 0x10u32.strict_shl(129);unchecked_shifts)Unchecked shift left. Computes self << rhs, assuming that\nrhs is less than the number of bits in self.
This results in undefined behavior if rhs is larger than\nor equal to the number of bits in self,\ni.e. when checked_shl would return None.
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,\nthe entire value is shifted out, and 0 is returned.
assert_eq!(0x1u32.unbounded_shl(4), 0x10);\nassert_eq!(0x1u32.unbounded_shl(129), 0);exact_bitshifts)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 >=\nu32::BITS.\nOtherwise, returns Some(self << rhs).
#![feature(exact_bitshifts)]\n\nassert_eq!(0x1u32.exact_shl(4), Some(0x10));\nassert_eq!(0x1u32.exact_shl(129), None);exact_bitshifts)Unchecked exact shift left. Computes self << rhs, assuming the operation can be\nlosslessly reversed rhs cannot be larger than\nu32::BITS.
This results in undefined behavior when rhs > self.leading_zeros() || rhs >= u32::BITS\ni.e. when\nu32::exact_shl\nwould return None.
Checked shift right. Computes self >> rhs, returning None\nif rhs is larger than or equal to the number of bits in self.
assert_eq!(0x10u32.checked_shr(4), Some(0x1));\nassert_eq!(0x10u32.checked_shr(129), None);Strict shift right. Computes self >> rhs, panicking rhs is\nlarger than or equal to the number of bits in self.
This function will always panic on overflow, regardless of whether overflow checks are enabled.
\nassert_eq!(0x10u32.strict_shr(4), 0x1);The following panics because of overflow:
\n\nlet _ = 0x10u32.strict_shr(129);unchecked_shifts)Unchecked shift right. Computes self >> rhs, assuming that\nrhs is less than the number of bits in self.
This results in undefined behavior if rhs is larger than\nor equal to the number of bits in self,\ni.e. when checked_shr would return None.
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,\nthe entire value is shifted out, and 0 is returned.
assert_eq!(0x10u32.unbounded_shr(4), 0x1);\nassert_eq!(0x10u32.unbounded_shr(129), 0);exact_bitshifts)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 >=\nu32::BITS.\nOtherwise, returns Some(self >> rhs).
#![feature(exact_bitshifts)]\n\nassert_eq!(0x10u32.exact_shr(4), Some(0x1));\nassert_eq!(0x10u32.exact_shr(5), None);exact_bitshifts)Unchecked exact shift right. Computes self >> rhs, assuming the operation can be\nlosslessly reversed and rhs cannot be larger than\nu32::BITS.
This results in undefined behavior when rhs > self.trailing_zeros() || rhs >= u32::BITS\ni.e. when\nu32::exact_shr\nwould return None.
Checked exponentiation. Computes self.pow(exp), returning None if\noverflow occurred.
assert_eq!(2u32.checked_pow(5), Some(32));\nassert_eq!(u32::MAX.checked_pow(2), None);Strict exponentiation. Computes self.pow(exp), panicking if\noverflow occurred.
This function will always panic on overflow, regardless of whether overflow checks are enabled.
\nassert_eq!(2u32.strict_pow(5), 32);The following panics because of overflow:
\n\nlet _ = u32::MAX.strict_pow(2);Saturating integer addition. Computes self + rhs, saturating at\nthe numeric bounds instead of overflowing.
assert_eq!(100u32.saturating_add(1), 101);\nassert_eq!(u32::MAX.saturating_add(127), u32::MAX);Saturating addition with a signed integer. Computes self + rhs,\nsaturating at the numeric bounds instead of overflowing.
assert_eq!(1u32.saturating_add_signed(2), 3);\nassert_eq!(1u32.saturating_add_signed(-2), 0);\nassert_eq!((u32::MAX - 2).saturating_add_signed(4), u32::MAX);Saturating integer subtraction. Computes self - rhs, saturating\nat the numeric bounds instead of overflowing.
assert_eq!(100u32.saturating_sub(27), 73);\nassert_eq!(13u32.saturating_sub(127), 0);Saturating integer subtraction. Computes self - rhs, saturating at\nthe numeric bounds instead of overflowing.
assert_eq!(1u32.saturating_sub_signed(2), 0);\nassert_eq!(1u32.saturating_sub_signed(-2), 3);\nassert_eq!((u32::MAX - 2).saturating_sub_signed(-4), u32::MAX);Saturating integer multiplication. Computes self * rhs,\nsaturating at the numeric bounds instead of overflowing.
assert_eq!(2u32.saturating_mul(10), 20);\nassert_eq!((u32::MAX).saturating_mul(10), u32::MAX);Saturating integer exponentiation. Computes self.pow(exp),\nsaturating at the numeric bounds instead of overflowing.
assert_eq!(4u32.saturating_pow(3), 64);\nassert_eq!(u32::MAX.saturating_pow(2), u32::MAX);Wrapping (modular) addition. Computes self + rhs,\nwrapping around at the boundary of the type.
assert_eq!(200u32.wrapping_add(55), 255);\nassert_eq!(200u32.wrapping_add(u32::MAX), 199);Wrapping (modular) addition with a signed integer. Computes\nself + rhs, wrapping around at the boundary of the type.
assert_eq!(1u32.wrapping_add_signed(2), 3);\nassert_eq!(1u32.wrapping_add_signed(-2), u32::MAX);\nassert_eq!((u32::MAX - 2).wrapping_add_signed(4), 1);Wrapping (modular) subtraction. Computes self - rhs,\nwrapping around at the boundary of the type.
assert_eq!(100u32.wrapping_sub(100), 0);\nassert_eq!(100u32.wrapping_sub(u32::MAX), 101);Wrapping (modular) subtraction with a signed integer. Computes\nself - rhs, wrapping around at the boundary of the type.
assert_eq!(1u32.wrapping_sub_signed(2), u32::MAX);\nassert_eq!(1u32.wrapping_sub_signed(-2), 3);\nassert_eq!((u32::MAX - 2).wrapping_sub_signed(-4), 1);Wrapping (modular) multiplication. Computes self * rhs, wrapping around at the boundary of the type.
Please note that this example is shared among integer types, which is why u8 is used.
assert_eq!(10u8.wrapping_mul(12), 120);\nassert_eq!(25u8.wrapping_mul(12), 44);Wrapping (modular) division. Computes self / rhs.
Wrapped division on unsigned types is just normal division. There’s\nno way wrapping could ever happen. This function exists so that all\noperations are accounted for in the wrapping operations.
\nThis function will panic if rhs is zero.
assert_eq!(100u32.wrapping_div(10), 10);Wrapping Euclidean division. Computes self.div_euclid(rhs).
Wrapped division on unsigned types is just normal division. There’s\nno way wrapping could ever happen. This function exists so that all\noperations are accounted for in the wrapping operations. Since, for\nthe positive integers, all common definitions of division are equal,\nthis is exactly equal to self.wrapping_div(rhs).
This function will panic if rhs is zero.
assert_eq!(100u32.wrapping_div_euclid(10), 10);Wrapping (modular) remainder. Computes self % rhs.
Wrapped remainder calculation on unsigned types is just the regular\nremainder calculation. There’s no way wrapping could ever happen.\nThis function exists so that all operations are accounted for in the\nwrapping operations.
\nThis function will panic if rhs is zero.
assert_eq!(100u32.wrapping_rem(10), 0);Wrapping Euclidean modulo. Computes self.rem_euclid(rhs).
Wrapped modulo calculation on unsigned types is just the regular\nremainder calculation. There’s no way wrapping could ever happen.\nThis function exists so that all operations are accounted for in the\nwrapping operations. Since, for the positive integers, all common\ndefinitions of division are equal, this is exactly equal to\nself.wrapping_rem(rhs).
This function will panic if rhs is zero.
assert_eq!(100u32.wrapping_rem_euclid(10), 0);Wrapping (modular) negation. Computes -self,\nwrapping around at the boundary of the type.
Since unsigned types do not have negative equivalents\nall applications of this function will wrap (except for -0).\nFor values smaller than the corresponding signed type’s maximum\nthe result is the same as casting the corresponding signed value.\nAny larger values are equivalent to MAX + 1 - (val - MAX - 1) where\nMAX is the corresponding signed type’s maximum.
assert_eq!(0_u32.wrapping_neg(), 0);\nassert_eq!(u32::MAX.wrapping_neg(), 1);\nassert_eq!(13_u32.wrapping_neg(), (!13) + 1);\nassert_eq!(42_u32.wrapping_neg(), !(42 - 1));Panic-free bitwise shift-left; yields self << mask(rhs),\nwhere mask removes any high-order bits of rhs that\nwould cause the shift to exceed the bitwidth of the type.
Note that this is not the same as a rotate-left; the\nRHS of a wrapping shift-left is restricted to the range\nof the type, rather than the bits shifted out of the LHS\nbeing returned to the other end. The primitive integer\ntypes all implement a rotate_left function,\nwhich may be what you want instead.
assert_eq!(1u32.wrapping_shl(7), 128);\nassert_eq!(1u32.wrapping_shl(128), 1);Panic-free bitwise shift-right; yields self >> mask(rhs),\nwhere mask removes any high-order bits of rhs that\nwould cause the shift to exceed the bitwidth of the type.
Note that this is not the same as a rotate-right; the\nRHS of a wrapping shift-right is restricted to the range\nof the type, rather than the bits shifted out of the LHS\nbeing returned to the other end. The primitive integer\ntypes all implement a rotate_right function,\nwhich may be what you want instead.
assert_eq!(128u32.wrapping_shr(7), 1);\nassert_eq!(128u32.wrapping_shr(128), 128);Wrapping (modular) exponentiation. Computes self.pow(exp),\nwrapping around at the boundary of the type.
assert_eq!(3u32.wrapping_pow(5), 243);\nassert_eq!(3u8.wrapping_pow(6), 217);Calculates self + rhs.
Returns a tuple of the addition along with a boolean indicating\nwhether an arithmetic overflow would occur. If an overflow would\nhave occurred then the wrapped value is returned.
\nassert_eq!(5u32.overflowing_add(2), (7, false));\nassert_eq!(u32::MAX.overflowing_add(1), (0, true));Calculates self + rhs + carry and returns a tuple containing\nthe sum and the output carry (in that order).
Performs “ternary addition” of two integer operands and a carry-in\nbit, and returns an output integer and a carry-out bit. This allows\nchaining together multiple additions to create a wider addition, and\ncan be useful for bignum addition.
\nThis can be thought of as a 32-bit “full adder”, in the electronics sense.
\nIf the input carry is false, this method is equivalent to\noverflowing_add, and the output carry is\nequal to the overflow flag. Note that although carry and overflow\nflags are similar for unsigned integers, they are different for\nsigned integers.
// 3 MAX (a = 3 × 2^32 + 2^32 - 1)\n// + 5 7 (b = 5 × 2^32 + 7)\n// ---------\n// 9 6 (sum = 9 × 2^32 + 6)\n\nlet (a1, a0): (u32, u32) = (3, u32::MAX);\nlet (b1, b0): (u32, u32) = (5, 7);\nlet carry0 = false;\n\nlet (sum0, carry1) = a0.carrying_add(b0, carry0);\nassert_eq!(carry1, true);\nlet (sum1, carry2) = a1.carrying_add(b1, carry1);\nassert_eq!(carry2, false);\n\nassert_eq!((sum1, sum0), (9, 6));Calculates self + rhs with a signed rhs.
Returns a tuple of the addition along with a boolean indicating\nwhether an arithmetic overflow would occur. If an overflow would\nhave occurred then the wrapped value is returned.
\nassert_eq!(1u32.overflowing_add_signed(2), (3, false));\nassert_eq!(1u32.overflowing_add_signed(-2), (u32::MAX, true));\nassert_eq!((u32::MAX - 2).overflowing_add_signed(4), (1, true));Calculates self - rhs.
Returns a tuple of the subtraction along with a boolean indicating\nwhether an arithmetic overflow would occur. If an overflow would\nhave occurred then the wrapped value is returned.
\nassert_eq!(5u32.overflowing_sub(2), (3, false));\nassert_eq!(0u32.overflowing_sub(1), (u32::MAX, true));Calculates self − rhs − borrow and returns a tuple\ncontaining the difference and the output borrow.
Performs “ternary subtraction” by subtracting both an integer\noperand and a borrow-in bit from self, and returns an output\ninteger and a borrow-out bit. This allows chaining together multiple\nsubtractions to create a wider subtraction, and can be useful for\nbignum subtraction.
// 9 6 (a = 9 × 2^32 + 6)\n// - 5 7 (b = 5 × 2^32 + 7)\n// ---------\n// 3 MAX (diff = 3 × 2^32 + 2^32 - 1)\n\nlet (a1, a0): (u32, u32) = (9, 6);\nlet (b1, b0): (u32, u32) = (5, 7);\nlet borrow0 = false;\n\nlet (diff0, borrow1) = a0.borrowing_sub(b0, borrow0);\nassert_eq!(borrow1, true);\nlet (diff1, borrow2) = a1.borrowing_sub(b1, borrow1);\nassert_eq!(borrow2, false);\n\nassert_eq!((diff1, diff0), (3, u32::MAX));Calculates self - rhs with a signed rhs
Returns a tuple of the subtraction along with a boolean indicating\nwhether an arithmetic overflow would occur. If an overflow would\nhave occurred then the wrapped value is returned.
\nassert_eq!(1u32.overflowing_sub_signed(2), (u32::MAX, true));\nassert_eq!(1u32.overflowing_sub_signed(-2), (3, false));\nassert_eq!((u32::MAX - 2).overflowing_sub_signed(-4), (1, true));Computes the absolute difference between self and other.
assert_eq!(100u32.abs_diff(80), 20u32);\nassert_eq!(100u32.abs_diff(110), 10u32);Calculates the multiplication of self and rhs.
Returns a tuple of the multiplication along with a boolean\nindicating whether an arithmetic overflow would occur. If an\noverflow would have occurred then the wrapped value is returned.
\nIf you want the value of the overflow, rather than just whether\nan overflow occurred, see Self::carrying_mul.
Please note that this example is shared among integer types, which is why u32 is used.
assert_eq!(5u32.overflowing_mul(2), (10, false));\nassert_eq!(1_000_000_000u32.overflowing_mul(10), (1410065408, true));bigint_helper_methods)Calculates the complete double-width product self * rhs.
This returns the low-order (wrapping) bits and the high-order (overflow) bits\nof the result as two separate values, in that order. As such,\na.widening_mul(b).0 produces the same result as a.wrapping_mul(b).
If you also need to add a value and carry to the wide result, then you want\nSelf::carrying_mul_add instead.
If you also need to add a carry to the wide result, then you want\nSelf::carrying_mul instead.
If you just want to know whether the multiplication overflowed, then you\nwant Self::overflowing_mul instead.
#![feature(bigint_helper_methods)]\nassert_eq!(5_u32.widening_mul(7), (35, 0));\nassert_eq!(u32::MAX.widening_mul(u32::MAX), (1, u32::MAX - 1));Compared to other *_mul methods:
#![feature(bigint_helper_methods)]\nassert_eq!(u32::widening_mul(1 << 31, 6), (0, 3));\nassert_eq!(u32::overflowing_mul(1 << 31, 6), (0, true));\nassert_eq!(u32::wrapping_mul(1 << 31, 6), 0);\nassert_eq!(u32::checked_mul(1 << 31, 6), None);Please note that this example is shared among integer types, which is why u32 is used.
#![feature(bigint_helper_methods)]\nassert_eq!(5u32.widening_mul(2), (10, 0));\nassert_eq!(1_000_000_000u32.widening_mul(10), (1410065408, 2));Calculates the “full multiplication” self * rhs + carry\nwithout the possibility to overflow.
This returns the low-order (wrapping) bits and the high-order (overflow) bits\nof the result as two separate values, in that order.
\nPerforms “long multiplication” which takes in an extra amount to add, and may return an\nadditional amount of overflow. This allows for chaining together multiple\nmultiplications to create “big integers” which represent larger values.
\nIf you also need to add a value, then use Self::carrying_mul_add.
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));\nassert_eq!(5u32.carrying_mul(2, 10), (20, 0));\nassert_eq!(1_000_000_000u32.carrying_mul(10, 0), (1410065408, 2));\nassert_eq!(1_000_000_000u32.carrying_mul(10, 10), (1410065418, 2));\nassert_eq!(u32::MAX.carrying_mul(u32::MAX, u32::MAX), (0, u32::MAX));This is the core operation needed for scalar multiplication when\nimplementing it for wider-than-native types.
\n\n#![feature(bigint_helper_methods)]\nfn scalar_mul_eq(little_endian_digits: &mut Vec<u16>, multiplicand: u16) {\n let mut carry = 0;\n for d in little_endian_digits.iter_mut() {\n (*d, carry) = d.carrying_mul(multiplicand, carry);\n }\n if carry != 0 {\n little_endian_digits.push(carry);\n }\n}\n\nlet mut v = vec![10, 20];\nscalar_mul_eq(&mut v, 3);\nassert_eq!(v, [30, 60]);\n\nassert_eq!(0x87654321_u64 * 0xFEED, 0x86D3D159E38D);\nlet mut v = vec![0x4321, 0x8765];\nscalar_mul_eq(&mut v, 0xFEED);\nassert_eq!(v, [0xE38D, 0xD159, 0x86D3]);If carry is zero, this is similar to overflowing_mul,\nexcept that it gives the value of the overflow instead of just whether one happened:
#![feature(bigint_helper_methods)]\nlet r = u8::carrying_mul(7, 13, 0);\nassert_eq!((r.0, r.1 != 0), u8::overflowing_mul(7, 13));\nlet r = u8::carrying_mul(13, 42, 0);\nassert_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\nby combining the wrapping_mul and\nwrapping_add methods:
#![feature(bigint_helper_methods)]\nassert_eq!(\n 789_u16.carrying_mul(456, 123).0,\n 789_u16.wrapping_mul(456).wrapping_add(123),\n);Calculates the “full multiplication” self * rhs + carry1 + carry2.
This returns the low-order (wrapping) bits and the high-order (overflow) bits\nof the result as two separate values, in that order.
\nThis cannot overflow, as the double-width result has exactly enough\nspace for the largest possible result. This is equivalent to how, in\ndecimal, 9 × 9 + 9 + 9 = 81 + 18 = 99 = 9×10⁰ + 9×10¹ = 10² - 1.
\nPerforms “long multiplication” which takes in an extra amount to add, and may return an\nadditional amount of overflow. This allows for chaining together multiple\nmultiplications to create “big integers” which represent larger values.
\nIf you don’t need the add part, then you can use Self::carrying_mul instead.
Please note that this example is shared between integer types,\nwhich explains why u32 is used here.
assert_eq!(5u32.carrying_mul_add(2, 0, 0), (10, 0));\nassert_eq!(5u32.carrying_mul_add(2, 10, 10), (30, 0));\nassert_eq!(1_000_000_000u32.carrying_mul_add(10, 0, 0), (1410065408, 2));\nassert_eq!(1_000_000_000u32.carrying_mul_add(10, 10, 10), (1410065428, 2));\nassert_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.
\nPlease note that this example is shared between integer types,\nusing u8 for simplicity of the demonstration.
fn quadratic_mul<const N: usize>(a: [u8; N], b: [u8; N]) -> [u8; N] {\n let mut out = [0; N];\n for j in 0..N {\n let mut carry = 0;\n for i in 0..(N - j) {\n (out[j + i], carry) = u8::carrying_mul_add(a[i], b[j], out[j + i], carry);\n }\n }\n out\n}\n\n// -1 * -1 == 1\nassert_eq!(quadratic_mul([0xFF; 3], [0xFF; 3]), [1, 0, 0]);\n\nassert_eq!(u32::wrapping_mul(0x9e3779b9, 0x7f4a7c15), 0xcffc982d);\nassert_eq!(\n quadratic_mul(u32::to_le_bytes(0x9e3779b9), u32::to_le_bytes(0x7f4a7c15)),\n u32::to_le_bytes(0xcffc982d)\n);Calculates the divisor when self is divided by rhs.
Returns a tuple of the divisor along with a boolean indicating\nwhether an arithmetic overflow would occur. Note that for unsigned\nintegers overflow never occurs, so the second value is always\nfalse.
This function will panic if rhs is zero.
assert_eq!(5u32.overflowing_div(2), (2, false));Calculates the quotient of Euclidean division self.div_euclid(rhs).
Returns a tuple of the divisor along with a boolean indicating\nwhether an arithmetic overflow would occur. Note that for unsigned\nintegers overflow never occurs, so the second value is always\nfalse.\nSince, for the positive integers, all common\ndefinitions of division are equal, this\nis exactly equal to self.overflowing_div(rhs).
This function will panic if rhs is zero.
assert_eq!(5u32.overflowing_div_euclid(2), (2, false));Calculates the remainder when self is divided by rhs.
Returns a tuple of the remainder after dividing along with a boolean\nindicating whether an arithmetic overflow would occur. Note that for\nunsigned integers overflow never occurs, so the second value is\nalways false.
This function will panic if rhs is zero.
assert_eq!(5u32.overflowing_rem(2), (1, 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\nindicating whether an arithmetic overflow would occur. Note that for\nunsigned integers overflow never occurs, so the second value is\nalways false.\nSince, for the positive integers, all common\ndefinitions of division are equal, this operation\nis exactly equal to self.overflowing_rem(rhs).
This function will panic if rhs is zero.
assert_eq!(5u32.overflowing_rem_euclid(2), (1, false));Negates self in an overflowing fashion.
\nReturns !self + 1 using wrapping operations to return the value\nthat represents the negation of this unsigned value. Note that for\npositive unsigned values overflow always occurs, but negating 0 does\nnot overflow.
assert_eq!(0u32.overflowing_neg(), (0, false));\nassert_eq!(2u32.overflowing_neg(), (-2i32 as u32, true));Shifts self left by rhs bits.
Returns a tuple of the shifted version of self along with a boolean\nindicating whether the shift value was larger than or equal to the\nnumber of bits. If the shift value is too large, then value is\nmasked (N-1) where N is the number of bits, and this value is then\nused to perform the shift.
\nassert_eq!(0x1u32.overflowing_shl(4), (0x10, false));\nassert_eq!(0x1u32.overflowing_shl(132), (0x10, true));\nassert_eq!(0x10u32.overflowing_shl(31), (0, false));Shifts self right by rhs bits.
Returns a tuple of the shifted version of self along with a boolean\nindicating whether the shift value was larger than or equal to the\nnumber of bits. If the shift value is too large, then value is\nmasked (N-1) where N is the number of bits, and this value is then\nused to perform the shift.
\nassert_eq!(0x10u32.overflowing_shr(4), (0x1, false));\nassert_eq!(0x10u32.overflowing_shr(132), (0x1, true));Raises self to the power of exp, using exponentiation by squaring.
Returns a tuple of the exponentiation along with a bool indicating\nwhether an overflow happened.
\nassert_eq!(3u32.overflowing_pow(5), (243, false));\nassert_eq!(3u8.overflowing_pow(6), (217, true));Raises self to the power of exp, using exponentiation by squaring.
assert_eq!(2u32.pow(5), 32);int_roundings)Calculates the smallest value greater than or equal to self that\nis a multiple of rhs.
This function will panic if rhs is zero.
On overflow, this function will panic if overflow checks are enabled (default in debug\nmode) and wrap if overflow checks are disabled (default in release mode).
\nassert_eq!(16_u32.next_multiple_of(8), 16);\nassert_eq!(23_u32.next_multiple_of(8), 24);Calculates the smallest value greater than or equal to self that\nis a multiple of rhs. Returns None if rhs is zero or the\noperation would result in overflow.
assert_eq!(16_u32.checked_next_multiple_of(8), Some(16));\nassert_eq!(23_u32.checked_next_multiple_of(8), Some(24));\nassert_eq!(1_u32.checked_next_multiple_of(0), None);\nassert_eq!(u32::MAX.checked_next_multiple_of(2), None);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\nfor rhs == 0. Instead, 0.is_multiple_of(0) == true, and for any non-zero n,\nn.is_multiple_of(0) == false.
assert!(6_u32.is_multiple_of(2));\nassert!(!5_u32.is_multiple_of(2));\n\nassert!(0_u32.is_multiple_of(0));\nassert!(!6_u32.is_multiple_of(0));Returns true if and only if self == 2^k for some unsigned integer k.
assert!(16u32.is_power_of_two());\nassert!(!10u32.is_power_of_two());Returns the smallest power of two greater than or equal to self.
When return value overflows (i.e., self > (1 << (N-1)) for type\nuN), it panics in debug mode and the return value is wrapped to 0 in\nrelease mode (the only situation in which this method can return 0).
assert_eq!(2u32.next_power_of_two(), 2);\nassert_eq!(3u32.next_power_of_two(), 4);\nassert_eq!(0u32.next_power_of_two(), 1);Returns the smallest power of two greater than or equal to self. If\nthe next power of two is greater than the type’s maximum value,\nNone is returned, otherwise the power of two is wrapped in Some.
assert_eq!(2u32.checked_next_power_of_two(), Some(2));\nassert_eq!(3u32.checked_next_power_of_two(), Some(4));\nassert_eq!(u32::MAX.checked_next_power_of_two(), None);wrapping_next_power_of_two)Returns the smallest power of two greater than or equal to n. If\nthe next power of two is greater than the type’s maximum value,\nthe return value is wrapped to 0.
#![feature(wrapping_next_power_of_two)]\n\nassert_eq!(2u32.wrapping_next_power_of_two(), 2);\nassert_eq!(3u32.wrapping_next_power_of_two(), 4);\nassert_eq!(u32::MAX.wrapping_next_power_of_two(), 0);Returns the memory representation of this integer as a byte array in\nbig-endian (network) byte order.
\nlet bytes = 0x12345678u32.to_be_bytes();\nassert_eq!(bytes, [0x12, 0x34, 0x56, 0x78]);Returns the memory representation of this integer as a byte array in\nlittle-endian byte order.
\nlet bytes = 0x12345678u32.to_le_bytes();\nassert_eq!(bytes, [0x78, 0x56, 0x34, 0x12]);Returns the memory representation of this integer as a byte array in\nnative byte order.
\nAs the target platform’s native endianness is used, portable code\nshould use to_be_bytes or to_le_bytes, as appropriate,\ninstead.
let bytes = 0x12345678u32.to_ne_bytes();\nassert_eq!(\n bytes,\n if cfg!(target_endian = \"big\") {\n [0x12, 0x34, 0x56, 0x78]\n } else {\n [0x78, 0x56, 0x34, 0x12]\n }\n);Creates a native endian integer value from its representation\nas a byte array in big endian.
\nlet value = u32::from_be_bytes([0x12, 0x34, 0x56, 0x78]);\nassert_eq!(value, 0x12345678);When starting from a slice rather than an array, fallible conversion APIs can be used:
\n\nfn read_be_u32(input: &mut &[u8]) -> u32 {\n let (int_bytes, rest) = input.split_at(size_of::<u32>());\n *input = rest;\n u32::from_be_bytes(int_bytes.try_into().unwrap())\n}Creates a native endian integer value from its representation\nas a byte array in little endian.
\nlet value = u32::from_le_bytes([0x78, 0x56, 0x34, 0x12]);\nassert_eq!(value, 0x12345678);When starting from a slice rather than an array, fallible conversion APIs can be used:
\n\nfn read_le_u32(input: &mut &[u8]) -> u32 {\n let (int_bytes, rest) = input.split_at(size_of::<u32>());\n *input = rest;\n u32::from_le_bytes(int_bytes.try_into().unwrap())\n}Creates a native endian integer value from its memory representation\nas a byte array in native endianness.
\nAs the target platform’s native endianness is used, portable code\nlikely wants to use from_be_bytes or from_le_bytes, as\nappropriate instead.
let value = u32::from_ne_bytes(if cfg!(target_endian = \"big\") {\n [0x12, 0x34, 0x56, 0x78]\n} else {\n [0x78, 0x56, 0x34, 0x12]\n});\nassert_eq!(value, 0x12345678);When starting from a slice rather than an array, fallible conversion APIs can be used:
\n\nfn read_ne_u32(input: &mut &[u8]) -> u32 {\n let (int_bytes, rest) = input.split_at(size_of::<u32>());\n *input = rest;\n u32::from_ne_bytes(int_bytes.try_into().unwrap())\n}MIN associated constant on this typeNew code should prefer to use\nu32::MIN instead.
Returns the smallest value that can be represented by this integer type.
\nMAX associated constant on this typeNew code should prefer to use\nu32::MAX instead.
Returns the largest value that can be represented by this integer type.
\nCalculates the midpoint (average) between self and rhs.
midpoint(a, b) is (a + b) / 2 as if it were performed in a\nsufficiently-large unsigned integral type. This implies that the result is\nalways rounded towards zero and that no overflow will ever occur.
assert_eq!(0u32.midpoint(4), 2);\nassert_eq!(1u32.midpoint(4), 2);Parses an integer from a string slice with digits in a given base.
\nThe string is expected to be an optional\n+\nsign followed by only digits. Leading and trailing non-digit characters (including\nwhitespace) represent an error. Underscores (which are accepted in Rust literals)\nalso represent an error.
Digits are a subset of these characters, depending on radix:
0-9a-zA-ZThis function panics if radix is not in the range from 2 to 36.
assert_eq!(u32::from_str_radix(\"A\", 16), Ok(10));Trailing space returns error:
\n\nassert!(u32::from_str_radix(\"1 \", 10).is_err());int_from_ascii)Parses an integer from an ASCII-byte slice with decimal digits.
\nThe characters are expected to be an optional\n+\nsign followed by only digits. Leading and trailing non-digit characters (including\nwhitespace) represent an error. Underscores (which are accepted in Rust literals)\nalso represent an error.
#![feature(int_from_ascii)]\n\nassert_eq!(u32::from_ascii(b\"+10\"), Ok(10));Trailing space returns error:
\n\nassert!(u32::from_ascii(b\"1 \").is_err());int_from_ascii)Parses an integer from an ASCII-byte slice with digits in a given base.
\nThe characters are expected to be an optional\n+\nsign followed by only digits. Leading and trailing non-digit characters (including\nwhitespace) represent an error. Underscores (which are accepted in Rust literals)\nalso represent an error.
Digits are a subset of these characters, depending on radix:
0-9a-zA-ZThis function panics if radix is not in the range from 2 to 36.
#![feature(int_from_ascii)]\n\nassert_eq!(u32::from_ascii_radix(b\"A\", 16), Ok(10));Trailing space returns error:
\n\nassert!(u32::from_ascii_radix(b\"1 \", 10).is_err());Serialize into a u32
\n+= operation. Read more+= operation. Read more+= operation. Read moremax aggregation.\nNote that the aggregation uses the total order predicate for floating point values,\nwhich means that this value is a negative NaN.min aggregation.\nNote that the aggregation uses the total order predicate for floating point values,\nwhich means that this value is a positive NaN.atomic_internals)&= operation. Read more&= operation. Read more&= operation. Read more|= operation. Read more|= operation. Read more|= operation. Read moreThe unsigned integers will only be BitStore type parameters\nfor handles to unaliased memory, following the normal Rust\nreference rules.
Self and Self::Alias be equal\nin representation. This is true by fiat for all types except the\nunsigned integers. Read moreBitSlice. It\nis always one of the unsigned integer fundamentals.BitStore implementor that is known to be alias-safe. It is\nused when a BitSlice introduces multiple handles that view the same\nmemory location, and at least one of them has write capabilities to it.\nIt must have the same underlying memory type, and can only change access\npatterns or public-facing usage.::Alias. It is used when a BitSlice removes the\nconditions that required a T -> T::Alias transition.::Access\nrules. This may be called when the value is aliased by a write-capable\nreference.::Access\nconstraints.^= operation. Read more^= operation. Read more^= operation. Read moreNone instead of panicking on division by zero\nand instead of wrapping around on underflow and overflow.None is returned.value is within the range for valid instances of this type,\nreturns Some(converted_value), otherwise, returns None. Read moreC into the underlying integral type. This\nmostly exists otherwise generic code would need unsafe for the value as integer Read moreReader].core_intrinsics_fallbacks)super::disjoint_bitor; we just need the trait indirection to handle\ndifferent types since calling intrinsics with generics doesn’t work.This operation rounds towards zero, truncating any\nfractional part of the exact result.
\nThis operation will panic if other == 0.
/= operation. Read moreSame as self /= other.get(), but because other is a NonZero<_>,\nthere’s never a runtime check for division-by-zero.
This operation rounds towards zero, truncating any fractional\npart of the exact result, and cannot panic.
\n/= operation. Read more/= operation. Read moreself into buf in the expected format for the database.rem_euclid. Read moreself (mod v). Read moredst must be exactly REQUIRED_SPACE bytes.src must be exactly REQUIRED_SPACE bytes.None if dst\ndoesn’t provide enough space to encode this integer. Read moreFixedInt] as [Bytes], the little-endian representation\nof self in the stack.switch_endianness() on\nthe returned value if the source was not encoded in little-endian.&Self. Read more