1 /*! `fun`damental `ty`pes 2 3 This crate provides trait unification of the Rust fundamental numbers, allowing 4 users to declare the behavior they want from a number without committing to a 5 single particular numeric type. 6 7 The number types can be categorized along two axes: behavior and width. Traits 8 for each axis and group on that axis are provided: 9 10 ## Numeric Categories 11 12 The most general category is represented by the trait [`IsNumber`]. It is 13 implemented by all the numeric fundamentals, and includes only the traits that 14 they all implement. This is an already-large amount: basic memory management, 15 comparison, rendering, and numeric arithmetic. 16 17 The numbers are then split into [`IsInteger`] and [`IsFloat`]. The former fills 18 out the API of `f32` and `f64`, while the latter covers all of the `iN` and `uN` 19 numbers. 20 21 Lastly, [`IsInteger`] splits further, into [`IsSigned`] and [`IsUnsigned`]. 22 These provide the last specializations unique to the differences between `iN` 23 and `uN`. 24 25 ## Width Categories 26 27 Every number implements the trait `IsN` for the `N` of its bit width. `isize` 28 and `usize` implement the trait that matches their width on the target platform. 29 30 In addition, the trait groups `AtLeastN` and `AtMostN` enable clamping the range 31 of acceptable widths to lower or upper bounds. These traits are equivalent to 32 `mem::size_of::<T>() >= N` and `mem::size_of::<T>() <= N`, respectively. 33 34 [`IsFloat`]: trait.IsFloat.html 35 [`IsInteger`]: trait.IsInteger.html 36 [`IsNumber`]: trait.IsNumber.html 37 [`IsSigned`]: trait.IsSigned.html 38 [`IsUnsigned`]: trait.IsUnsigned.html 39 !*/ 40 41 #![cfg_attr(not(feature = "std"), no_std)] 42 #![deny(unconditional_recursion)] 43 44 use core::{ 45 convert::{ 46 TryFrom, 47 TryInto, 48 }, 49 fmt::{ 50 Binary, 51 Debug, 52 Display, 53 LowerExp, 54 LowerHex, 55 Octal, 56 UpperExp, 57 UpperHex, 58 }, 59 hash::Hash, 60 iter::{ 61 Product, 62 Sum, 63 }, 64 num::{ 65 FpCategory, 66 ParseIntError, 67 }, 68 ops::{ 69 Add, 70 AddAssign, 71 BitAnd, 72 BitAndAssign, 73 BitOr, 74 BitOrAssign, 75 BitXor, 76 BitXorAssign, 77 Div, 78 DivAssign, 79 Mul, 80 MulAssign, 81 Neg, 82 Not, 83 Rem, 84 RemAssign, 85 Shl, 86 ShlAssign, 87 Shr, 88 ShrAssign, 89 Sub, 90 SubAssign, 91 }, 92 str::FromStr, 93 }; 94 95 /// Declare that a type is an abstract number. 96 /// 97 /// This unifies all of the signed-integer, unsigned-integer, and floating-point 98 /// types. 99 pub trait IsNumber: Sized 100 + Send 101 + Sync 102 + Unpin 103 + Clone 104 + Copy 105 + Default 106 + FromStr 107 // cmp 108 + PartialEq<Self> 109 + PartialOrd<Self> 110 // fmt 111 + Debug 112 + Display 113 // iter 114 + Product<Self> 115 + for<'a> Product<&'a Self> 116 + Sum<Self> 117 + for<'a> Sum<&'a Self> 118 // numeric ops 119 + Add<Self, Output = Self> 120 + for<'a> Add<&'a Self, Output = Self> 121 + AddAssign<Self> 122 + for<'a> AddAssign<&'a Self> 123 + Sub<Self, Output = Self> 124 + for<'a> Sub<&'a Self, Output = Self> 125 + SubAssign<Self> 126 + for<'a> SubAssign<&'a Self> 127 + Mul<Self, Output = Self> 128 + for<'a> Mul<&'a Self, Output = Self> 129 + MulAssign<Self> 130 + for<'a> MulAssign<&'a Self> 131 + Div<Self, Output = Self> 132 + for<'a> Div<&'a Self, Output = Self> 133 + DivAssign<Self> 134 + for<'a> DivAssign<&'a Self> 135 + Rem<Self, Output = Self> 136 + for<'a> Rem<&'a Self, Output = Self> 137 + RemAssign<Self> 138 + for<'a> RemAssign<&'a Self> 139 { 140 type Bytes; 141 142 /// Return the memory representation of this number as a byte array in 143 /// big-endian (network) byte order. to_be_bytes(self) -> Self::Bytes144 fn to_be_bytes(self) -> Self::Bytes; 145 146 /// Return the memory representation of this number as a byte array in 147 /// little-endian byte order. to_le_bytes(self) -> Self::Bytes148 fn to_le_bytes(self) -> Self::Bytes; 149 150 /// Return the memory representation of this number as a byte array in 151 /// native byte order. to_ne_bytes(self) -> Self::Bytes152 fn to_ne_bytes(self) -> Self::Bytes; 153 154 /// Create a numeric value from its representation as a byte array in big 155 /// endian. from_be_bytes(bytes: Self::Bytes) -> Self156 fn from_be_bytes(bytes: Self::Bytes) -> Self; 157 158 /// Create a numeric value from its representation as a byte array in little 159 /// endian. from_le_bytes(bytes: Self::Bytes) -> Self160 fn from_le_bytes(bytes: Self::Bytes) -> Self; 161 162 /// Create a numeric value from its memory representation as a byte array in 163 /// native endianness. from_ne_bytes(bytes: Self::Bytes) -> Self164 fn from_ne_bytes(bytes: Self::Bytes) -> Self; 165 } 166 167 /// Declare that a type is a fixed-point integer. 168 /// 169 /// This unifies all of the signed and unsigned integral types. 170 pub trait IsInteger: 171 IsNumber 172 + Hash 173 + Eq 174 + Ord 175 + Binary 176 + LowerHex 177 + UpperHex 178 + Octal 179 + BitAnd<Self, Output = Self> 180 + for<'a> BitAnd<&'a Self, Output = Self> 181 + BitAndAssign<Self> 182 + for<'a> BitAndAssign<&'a Self> 183 + BitOr<Self, Output = Self> 184 + for<'a> BitOr<&'a Self, Output = Self> 185 + BitOrAssign<Self> 186 + for<'a> BitOrAssign<&'a Self> 187 + BitXor<Self, Output = Self> 188 + for<'a> BitXor<&'a Self, Output = Self> 189 + BitXorAssign<Self> 190 + for<'a> BitXorAssign<&'a Self> 191 + Not<Output = Self> 192 + TryFrom<i8> 193 + TryFrom<u8> 194 + TryFrom<i16> 195 + TryFrom<u16> 196 + TryFrom<i32> 197 + TryFrom<u32> 198 + TryFrom<i64> 199 + TryFrom<u64> 200 + TryFrom<i128> 201 + TryFrom<u128> 202 + TryFrom<isize> 203 + TryFrom<usize> 204 + TryInto<i8> 205 + TryInto<u8> 206 + TryInto<i16> 207 + TryInto<u16> 208 + TryInto<i32> 209 + TryInto<u32> 210 + TryInto<i64> 211 + TryInto<u64> 212 + TryInto<i128> 213 + TryInto<u128> 214 + TryInto<isize> 215 + TryInto<usize> 216 + Shl<i8, Output = Self> 217 + for<'a> Shl<&'a i8, Output = Self> 218 + ShlAssign<i8> 219 + for<'a> ShlAssign<&'a i8> 220 + Shr<i8, Output = Self> 221 + for<'a> Shr<&'a i8, Output = Self> 222 + ShrAssign<i8> 223 + for<'a> ShrAssign<&'a i8> 224 + Shl<u8, Output = Self> 225 + for<'a> Shl<&'a u8, Output = Self> 226 + ShlAssign<u8> 227 + for<'a> ShlAssign<&'a u8> 228 + Shr<u8, Output = Self> 229 + for<'a> Shr<&'a u8, Output = Self> 230 + ShrAssign<u8> 231 + for<'a> ShrAssign<&'a u8> 232 + Shl<i16, Output = Self> 233 + for<'a> Shl<&'a i16, Output = Self> 234 + ShlAssign<i16> 235 + for<'a> ShlAssign<&'a i16> 236 + Shr<i16, Output = Self> 237 + for<'a> Shr<&'a i16, Output = Self> 238 + ShrAssign<i16> 239 + for<'a> ShrAssign<&'a i16> 240 + Shl<u16, Output = Self> 241 + for<'a> Shl<&'a u16, Output = Self> 242 + ShlAssign<u16> 243 + for<'a> ShlAssign<&'a u16> 244 + Shr<u16, Output = Self> 245 + for<'a> Shr<&'a u16, Output = Self> 246 + ShrAssign<u16> 247 + for<'a> ShrAssign<&'a u16> 248 + Shl<i32, Output = Self> 249 + for<'a> Shl<&'a i32, Output = Self> 250 + ShlAssign<i32> 251 + for<'a> ShlAssign<&'a i32> 252 + Shr<i32, Output = Self> 253 + for<'a> Shr<&'a i32, Output = Self> 254 + ShrAssign<i32> 255 + for<'a> ShrAssign<&'a i32> 256 + Shl<u32, Output = Self> 257 + for<'a> Shl<&'a u32, Output = Self> 258 + ShlAssign<u32> 259 + for<'a> ShlAssign<&'a u32> 260 + Shr<u32, Output = Self> 261 + for<'a> Shr<&'a u32, Output = Self> 262 + ShrAssign<u32> 263 + for<'a> ShrAssign<&'a u32> 264 + Shl<i64, Output = Self> 265 + for<'a> Shl<&'a i64, Output = Self> 266 + ShlAssign<i64> 267 + for<'a> ShlAssign<&'a i64> 268 + Shr<i64, Output = Self> 269 + for<'a> Shr<&'a i64, Output = Self> 270 + ShrAssign<i64> 271 + for<'a> ShrAssign<&'a i64> 272 + Shl<u64, Output = Self> 273 + for<'a> Shl<&'a u64, Output = Self> 274 + ShlAssign<u64> 275 + for<'a> ShlAssign<&'a u64> 276 + Shr<u64, Output = Self> 277 + for<'a> Shr<&'a u64, Output = Self> 278 + ShrAssign<u64> 279 + for<'a> ShrAssign<&'a u64> 280 + Shl<i128, Output = Self> 281 + for<'a> Shl<&'a i128, Output = Self> 282 + ShlAssign<i128> 283 + for<'a> ShlAssign<&'a i128> 284 + Shr<i128, Output = Self> 285 + for<'a> Shr<&'a i128, Output = Self> 286 + ShrAssign<i128> 287 + for<'a> ShrAssign<&'a i128> 288 + Shl<u128, Output = Self> 289 + for<'a> Shl<&'a u128, Output = Self> 290 + ShlAssign<u128> 291 + for<'a> ShlAssign<&'a u128> 292 + Shr<u128, Output = Self> 293 + for<'a> Shr<&'a u128, Output = Self> 294 + ShrAssign<u128> 295 + for<'a> ShrAssign<&'a u128> 296 + Shl<isize, Output = Self> 297 + for<'a> Shl<&'a isize, Output = Self> 298 + ShlAssign<isize> 299 + for<'a> ShlAssign<&'a isize> 300 + Shr<isize, Output = Self> 301 + for<'a> Shr<&'a isize, Output = Self> 302 + ShrAssign<isize> 303 + for<'a> ShrAssign<&'a isize> 304 + Shl<usize, Output = Self> 305 + for<'a> Shl<&'a usize, Output = Self> 306 + ShlAssign<usize> 307 + for<'a> ShlAssign<&'a usize> 308 + Shr<usize, Output = Self> 309 + for<'a> Shr<&'a usize, Output = Self> 310 + ShrAssign<usize> 311 + for<'a> ShrAssign<&'a usize> 312 { 313 /// The type’s zero value. 314 const ZERO: Self; 315 316 /// The type’s minimum value. This is zero for unsigned integers. 317 const MIN: Self; 318 319 /// The type’s maximum value. 320 const MAX: Self; 321 322 /// Returns the smallest value that can be represented by this integer type. min_value() -> Self323 fn min_value() -> Self; 324 325 /// Returns the largest value that can be represented by this integer type. max_value() -> Self326 fn max_value() -> Self; 327 328 /// Converts a string slice in a given base to an integer. 329 /// 330 /// The string is expected to be an optional `+` or `-` sign followed by 331 /// digits. Leading and trailing whitespace represent an error. Digits are a 332 /// subset of these characters, depending on `radix`: 333 /// 334 /// - `0-9` 335 /// - `a-z` 336 /// - `A-Z` 337 /// 338 /// # Panics 339 /// 340 /// This function panics if `radix` is not in the range from 2 to 36. from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError>341 fn from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError>; 342 343 /// Returns the number of ones in the binary representation of `self`. count_ones(self) -> u32344 fn count_ones(self) -> u32; 345 346 /// Returns the number of zeros in the binary representation of `self`. count_zeros(self) -> u32347 fn count_zeros(self) -> u32; 348 349 /// Returns the number of leading zeros in the binary representation of 350 /// `self`. leading_zeros(self) -> u32351 fn leading_zeros(self) -> u32; 352 353 /// Returns the number of trailing zeros in the binary representation of 354 /// `self`. trailing_zeros(self) -> u32355 fn trailing_zeros(self) -> u32; 356 357 /// Returns the number of leading ones in the binary representation of 358 /// `self`. leading_ones(self) -> u32359 fn leading_ones(self) -> u32; 360 361 /// Returns the number of trailing ones in the binary representation of 362 /// `self`. trailing_ones(self) -> u32363 fn trailing_ones(self) -> u32; 364 365 /// Shifts the bits to the left by a specified amount, `n`, wrapping the 366 /// truncated bits to the end of the resulting integer. 367 /// 368 /// Please note this isn’t the same operation as the `<<` shifting operator! rotate_left(self, n: u32) -> Self369 fn rotate_left(self, n: u32) -> Self; 370 371 /// Shifts the bits to the right by a specified amount, `n`, wrapping the 372 /// truncated bits to the beginning of the resulting integer. 373 /// 374 /// Please note this isn’t the same operation as the `>>` shifting operator! rotate_right(self, n: u32) -> Self375 fn rotate_right(self, n: u32) -> Self; 376 377 /// Reverses the byte order of the integer. swap_bytes(self) -> Self378 fn swap_bytes(self) -> Self; 379 380 /// Reverses the bit pattern of the integer. reverse_bits(self) -> Self381 fn reverse_bits(self) -> Self; 382 383 /// Converts an integer from big endian to the target’s endianness. 384 /// 385 /// On big endian this is a no-op. On little endian the bytes are swapped. from_be(self) -> Self386 fn from_be(self) -> Self; 387 388 /// Converts an integer frm little endian to the target’s endianness. 389 /// 390 /// On little endian this is a no-op. On big endian the bytes are swapped. from_le(self) -> Self391 fn from_le(self) -> Self; 392 393 /// Converts `self` to big endian from the target’s endianness. 394 /// 395 /// On big endian this is a no-op. On little endian the bytes are swapped. to_be(self) -> Self396 fn to_be(self) -> Self; 397 398 /// Converts `self` to little endian from the target’s endianness. 399 /// 400 /// On little endian this is a no-op. On big endian the bytes are swapped. to_le(self) -> Self401 fn to_le(self) -> Self; 402 403 /// Checked integer addition. Computes `self + rhs`, returning `None` if 404 /// overflow occurred. checked_add(self, rhs: Self) -> Option<Self>405 fn checked_add(self, rhs: Self) -> Option<Self>; 406 407 /// Checked integer subtraction. Computes `self - rhs`, returning `None` if 408 /// overflow occurred. checked_sub(self, rhs: Self) -> Option<Self>409 fn checked_sub(self, rhs: Self) -> Option<Self>; 410 411 /// Checked integer multiplication. Computes `self * rhs`, returning `None` 412 /// if overflow occurred. checked_mul(self, rhs: Self) -> Option<Self>413 fn checked_mul(self, rhs: Self) -> Option<Self>; 414 415 /// Checked integer division. Computes `self / rhs`, returning `None` if 416 /// `rhs == 0` or the division results in overflow. checked_div(self, rhs: Self) -> Option<Self>417 fn checked_div(self, rhs: Self) -> Option<Self>; 418 419 /// Checked Euclidean division. Computes `self.div_euclid(rhs)`, returning 420 /// `None` if `rhs == 0` or the division results in overflow. checked_div_euclid(self, rhs: Self) -> Option<Self>421 fn checked_div_euclid(self, rhs: Self) -> Option<Self>; 422 423 /// Checked integer remainder. Computes `self % rhs`, returning `None` if 424 /// `rhs == 0` or the division results in overflow. checked_rem(self, rhs: Self) -> Option<Self>425 fn checked_rem(self, rhs: Self) -> Option<Self>; 426 427 /// Checked Euclidean remainder. Computes `self.rem_euclid(rhs)`, returning 428 /// `None` if `rhs == 0` or the division results in overflow. checked_rem_euclid(self, rhs: Self) -> Option<Self>429 fn checked_rem_euclid(self, rhs: Self) -> Option<Self>; 430 431 /// Checked negation. Computes `-self`, returning `None` if `self == MIN`. 432 /// 433 /// Note that negating any positive integer will overflow. checked_neg(self) -> Option<Self>434 fn checked_neg(self) -> Option<Self>; 435 436 /// Checked shift left. Computes `self << rhs`, returning `None` if `rhs` is 437 /// larger than or equal to the number of bits in `self`. checked_shl(self, rhs: u32) -> Option<Self>438 fn checked_shl(self, rhs: u32) -> Option<Self>; 439 440 /// Checked shift right. Computes `self >> rhs`, returning `None` if `rhs` 441 /// is larger than or equal to the number of bits in `self`. checked_shr(self, rhs: u32) -> Option<Self>442 fn checked_shr(self, rhs: u32) -> Option<Self>; 443 444 /// Checked exponentiation. Computes `self.pow(exp)`, returning `None` if 445 /// overflow occurred. checked_pow(self, rhs: u32) -> Option<Self>446 fn checked_pow(self, rhs: u32) -> Option<Self>; 447 448 /// Saturating integer addition. Computes `self + rhs`, saturating at the 449 /// numeric bounds instead of overflowing. saturating_add(self, rhs: Self) -> Self450 fn saturating_add(self, rhs: Self) -> Self; 451 452 /// Saturating integer subtraction. Computes `self - rhs`, saturating at the 453 /// numeric bounds instead of overflowing. saturating_sub(self, rhs: Self) -> Self454 fn saturating_sub(self, rhs: Self) -> Self; 455 456 /// Saturating integer multiplication. Computes `self * rhs`, saturating at 457 /// the numeric bounds instead of overflowing. saturating_mul(self, rhs: Self) -> Self458 fn saturating_mul(self, rhs: Self) -> Self; 459 460 /// Saturating integer exponentiation. Computes `self.pow(exp)`, saturating 461 /// at the numeric bounds instead of overflowing. saturating_pow(self, rhs: u32) -> Self462 fn saturating_pow(self, rhs: u32) -> Self; 463 464 /// Wrapping (modular) addition. Computes `self + rhs`, wrapping around at 465 /// the boundary of the type. wrapping_add(self, rhs: Self) -> Self466 fn wrapping_add(self, rhs: Self) -> Self; 467 468 /// Wrapping (modular) subtraction. Computes `self - rhs`, wrapping around 469 /// at the boundary of the type. wrapping_sub(self, rhs: Self) -> Self470 fn wrapping_sub(self, rhs: Self) -> Self; 471 472 /// Wrapping (modular) multiplication. Computes `self * rhs`, wrapping 473 /// around at the boundary of the type. wrapping_mul(self, rhs: Self) -> Self474 fn wrapping_mul(self, rhs: Self) -> Self; 475 476 /// Wrapping (modular) division. Computes `self / rhs`, wrapping around at 477 /// the boundary of the type. 478 /// 479 /// # Signed Integers 480 /// 481 /// The only case where such wrapping can occur is when one divides 482 /// `MIN / -1` on a signed type (where `MIN` is the negative minimal value 483 /// for the type); this is equivalent to `-MIN`, a positive value that is 484 /// too large to represent in the type. In such a case, this function 485 /// returns `MIN` itself. 486 /// 487 /// # Unsigned Integers 488 /// 489 /// Wrapping (modular) division. Computes `self / rhs`. Wrapped division on 490 /// unsigned types is just normal division. There’s no way wrapping could 491 /// ever happen. This function exists, so that all operations are accounted 492 /// for in the wrapping operations. 493 /// 494 /// # Panics 495 /// 496 /// This function will panic if `rhs` is 0. wrapping_div(self, rhs: Self) -> Self497 fn wrapping_div(self, rhs: Self) -> Self; 498 499 /// Wrapping Eulidean division. Computes `self.div_euclid(rhs)`, wrapping 500 /// around at the boundary of the type. 501 /// 502 /// # Signed Types 503 /// 504 /// Wrapping will only occur in `MIN / -1` on a signed type (where `MIN` is 505 /// the negative minimal value for the type). This is equivalent to `-MIN`, 506 /// a positive value that is too large to represent in the type. In this 507 /// case, this method returns `MIN` itself. 508 /// 509 /// # Unsigned Types 510 /// 511 /// Wrapped division on unsigned types is just normal division. There’s no 512 /// way wrapping could ever happen. This function exists, so that all 513 /// operations are accounted for in the wrapping operations. Since, for the 514 /// positive integers, all common definitions of division are equal, this is 515 /// exactly equal to `self.wrapping_div(rhs)`. 516 /// 517 /// # Panics 518 /// 519 /// This function will panic if `rhs` is 0. wrapping_div_euclid(self, rhs: Self) -> Self520 fn wrapping_div_euclid(self, rhs: Self) -> Self; 521 522 /// Wrapping (modular) remainder. Computes `self % rhs`, wrapping around at 523 /// the boundary of the type. 524 /// 525 /// # Signed Integers 526 /// 527 /// Such wrap-around never actually occurs mathematically; implementation 528 /// artifacts make `x % y` invalid for `MIN / -1` on a signed type (where 529 /// `MIN` is the negative minimal value). In such a case, this function 530 /// returns `0`. 531 /// 532 /// # Unsigned Integers 533 /// 534 /// Wrapped remainder calculation on unsigned types is just the regular 535 /// remainder calculation. There’s no way wrapping could ever happen. This 536 /// function exists, so that all operations are accounted for in the 537 /// wrapping operations. 538 /// 539 /// # Panics 540 /// 541 /// This function will panic if `rhs` is 0. wrapping_rem(self, rhs: Self) -> Self542 fn wrapping_rem(self, rhs: Self) -> Self; 543 544 /// Wrapping Euclidean remainder. Computes `self.rem_euclid(rhs)`, wrapping 545 /// around at the boundary of the type. 546 /// 547 /// # Signed Integers 548 /// 549 /// Wrapping will only occur in `MIN % -1` on a signed type (where `MIN` is 550 /// the negative minimal value for the type). In this case, this method 551 /// returns 0. 552 /// 553 /// # Unsigned Integers 554 /// 555 /// Wrapped modulo calculation on unsigned types is just the regular 556 /// remainder calculation. There’s no way wrapping could ever happen. This 557 /// function exists, so that all operations are accounted for in the 558 /// wrapping operations. Since, for the positive integers, all common 559 /// definitions of division are equal, this is exactly equal to 560 /// `self.wrapping_rem(rhs)`. 561 /// 562 /// # Panics 563 /// 564 /// This function will panic if `rhs` is 0. wrapping_rem_euclid(self, rhs: Self) -> Self565 fn wrapping_rem_euclid(self, rhs: Self) -> Self; 566 567 /// Wrapping (modular) negation. Computes `-self`, wrapping around at the 568 /// boundary of the type. 569 /// 570 /// # Signed Integers 571 /// 572 /// The only case where such wrapping can occur is when one negates `MIN` 573 /// on a signed type (where `MIN` is the negative minimal value for the 574 /// type); this is a positive value that is too large to represent in the 575 /// type. In such a case, this function returns `MIN` itself. 576 /// 577 /// # Unsigned Integers 578 /// 579 /// Since unsigned types do not have negative equivalents all applications 580 /// of this function will wrap (except for `-0`). For values smaller than 581 /// the corresponding signed type’s maximum the result is the same as 582 /// casting the corresponding signed value. Any larger values are equivalent 583 /// to `MAX + 1 - (val - MAX - 1)` where `MAX` is the corresponding signed 584 /// type’s maximum. wrapping_neg(self) -> Self585 fn wrapping_neg(self) -> Self; 586 587 /// Panic-free bitwise shift-left; yields `self << mask(rhs)`, where `mask` 588 /// removes any high-order bits of `rhs` that would cause the shift to 589 /// exceed the bitwidth of the type. 590 /// 591 /// Note that this is not the same as a rotate-left; the RHS of a wrapping 592 /// shift-left is restricted to the range of the type, rather than the bits 593 /// shifted out of the LHS being returned to the other end. The primitive 594 /// integer types all implement a `rotate_left` function, which may be what 595 /// you want instead. wrapping_shl(self, rhs: u32) -> Self596 fn wrapping_shl(self, rhs: u32) -> Self; 597 598 /// Panic-free bitwise shift-right; yields `self >> mask(rhs)`, where `mask` 599 /// removes any high-order bits of `rhs` that would cause the shift to 600 /// exceed the bitwidth of the type. 601 /// 602 /// Note that this is not the same as a rotate-right; the RHS of a wrapping 603 /// shift-right is restricted to the range of the type, rather than the bits 604 /// shifted out of the LHS being returned to the other end. The primitive 605 /// integer types all implement a `rotate_right` function, which may be what 606 /// you want instead. wrapping_shr(self, rhs: u32) -> Self607 fn wrapping_shr(self, rhs: u32) -> Self; 608 609 /// Wrapping (modular) exponentiation. Computes `self.pow(exp)`, wrapping 610 /// around at the boundary of the type. wrapping_pow(self, rhs: u32) -> Self611 fn wrapping_pow(self, rhs: u32) -> Self; 612 613 /// Calculates `self + rhs` 614 /// 615 /// Returns a tuple of the addition along with a boolean indicating whether 616 /// an arithmetic overflow would occur. If an overflow would have occurred 617 /// then the wrapped value is returned. overflowing_add(self, rhs: Self) -> (Self, bool)618 fn overflowing_add(self, rhs: Self) -> (Self, bool); 619 620 /// Calculates `self - rhs` 621 /// 622 /// Returns a tuple of the subtraction along with a boolean indicating 623 /// whether an arithmetic overflow would occur. If an overflow would have 624 /// occurred then the wrapped value is returned. overflowing_sub(self, rhs: Self) -> (Self, bool)625 fn overflowing_sub(self, rhs: Self) -> (Self, bool); 626 627 /// Calculates the multiplication of `self` and `rhs`. 628 /// 629 /// Returns a tuple of the multiplication along with a boolean indicating 630 /// whether an arithmetic overflow would occur. If an overflow would have 631 /// occurred then the wrapped value is returned. overflowing_mul(self, rhs: Self) -> (Self, bool)632 fn overflowing_mul(self, rhs: Self) -> (Self, bool); 633 634 /// Calculates the divisor when `self` is divided by `rhs`. 635 /// 636 /// Returns a tuple of the divisor along with a boolean indicating whether 637 /// an arithmetic overflow would occur. If an overflow would occur then self 638 /// is returned. 639 /// 640 /// # Panics 641 /// 642 /// This function will panic if `rhs` is 0. overflowing_div(self, rhs: Self) -> (Self, bool)643 fn overflowing_div(self, rhs: Self) -> (Self, bool); 644 645 /// Calculates the quotient of Euclidean division `self.div_euclid(rhs)`. 646 /// 647 /// Returns a tuple of the divisor along with a boolean indicating whether 648 /// an arithmetic overflow would occur. If an overflow would occur then self 649 /// is returned. 650 /// 651 /// # Panics 652 /// 653 /// This function will panic if `rhs` is 0. overflowing_div_euclid(self, rhs: Self) -> (Self, bool)654 fn overflowing_div_euclid(self, rhs: Self) -> (Self, bool); 655 656 /// Calculates the remainder when `self` is divided by `rhs`. 657 /// 658 /// Returns a tuple of the remainder after dividing along with a boolean 659 /// indicating whether an arithmetic overflow would occur. If an overflow 660 /// would occur then 0 is returned. 661 /// 662 /// # Panics 663 /// 664 /// This function will panic if `rhs` is 0. overflowing_rem(self, rhs: Self) -> (Self, bool)665 fn overflowing_rem(self, rhs: Self) -> (Self, bool); 666 667 /// Overflowing Euclidean remainder. Calculates `self.rem_euclid(rhs)`. 668 /// 669 /// Returns a tuple of the remainder after dividing along with a boolean 670 /// indicating whether an arithmetic overflow would occur. If an overflow 671 /// would occur then 0 is returned. 672 /// 673 /// # Panics 674 /// 675 /// This function will panic if rhs is 0. overflowing_rem_euclid(self, rhs: Self) -> (Self, bool)676 fn overflowing_rem_euclid(self, rhs: Self) -> (Self, bool); 677 678 /// Negates self, overflowing if this is equal to the minimum value. 679 /// 680 /// Returns a tuple of the negated version of self along with a boolean 681 /// indicating whether an overflow happened. If `self` is the minimum value 682 /// (e.g., `i32::MIN` for values of type `i32`), then the minimum value will 683 /// be returned again and `true` will be returned for an overflow happening. overflowing_neg(self) -> (Self, bool)684 fn overflowing_neg(self) -> (Self, bool); 685 686 /// Shifts self left by `rhs` bits. 687 /// 688 /// Returns a tuple of the shifted version of self along with a boolean 689 /// indicating whether the shift value was larger than or equal to the 690 /// number of bits. If the shift value is too large, then value is masked 691 /// (N-1) where N is the number of bits, and this value is then used to 692 /// perform the shift. overflowing_shl(self, rhs: u32) -> (Self, bool)693 fn overflowing_shl(self, rhs: u32) -> (Self, bool); 694 695 /// Shifts self right by `rhs` bits. 696 /// 697 /// Returns a tuple of the shifted version of self along with a boolean 698 /// indicating whether the shift value was larger than or equal to the 699 /// number of bits. If the shift value is too large, then value is masked 700 /// (N-1) where N is the number of bits, and this value is then used to 701 /// perform the shift. overflowing_shr(self, rhs: u32) -> (Self, bool)702 fn overflowing_shr(self, rhs: u32) -> (Self, bool); 703 704 /// Raises self to the power of `exp`, using exponentiation by squaring. 705 /// 706 /// Returns a tuple of the exponentiation along with a bool indicating 707 /// whether an overflow happened. overflowing_pow(self, rhs: u32) -> (Self, bool)708 fn overflowing_pow(self, rhs: u32) -> (Self, bool); 709 710 /// Raises self to the power of `exp`, using exponentiation by squaring. pow(self, rhs: u32) -> Self711 fn pow(self, rhs: u32) -> Self; 712 713 /// Calculates the quotient of Euclidean division of self by rhs. 714 /// 715 /// This computes the integer `n` such that 716 /// `self = n * rhs + self.rem_euclid(rhs)`, with 717 /// `0 <= self.rem_euclid(rhs) < rhs`. 718 /// 719 /// In other words, the result is `self / rhs` rounded to the integer `n` 720 /// such that `self >= n * rhs`. If `self > 0`, this is equal to round 721 /// towards zero (the default in Rust); if `self < 0`, this is equal to 722 /// round towards +/- infinity. 723 /// 724 /// # Panics 725 /// 726 /// This function will panic if `rhs` is 0 or the division results in 727 /// overflow. div_euclid(self, rhs: Self) -> Self728 fn div_euclid(self, rhs: Self) -> Self; 729 730 /// Calculates the least nonnegative remainder of `self (mod rhs)`. 731 /// 732 /// This is done as if by the Euclidean division algorithm -- given 733 /// `r = self.rem_euclid(rhs)`, `self = rhs * self.div_euclid(rhs) + r`, and 734 /// `0 <= r < abs(rhs)`. 735 /// 736 /// # Panics 737 /// 738 /// This function will panic if `rhs` is 0 or the division results in 739 /// overflow. rem_euclid(self, rhs: Self) -> Self740 fn rem_euclid(self, rhs: Self) -> Self; 741 } 742 743 /// Declare that a type is a signed integer. 744 pub trait IsSigned: IsInteger + Neg { 745 /// Checked absolute value. Computes `self.abs()`, returning `None` if 746 /// `self == MIN`. checked_abs(self) -> Option<Self>747 fn checked_abs(self) -> Option<Self>; 748 749 /// Wrapping (modular) absolute value. Computes `self.abs()`, wrapping 750 /// around at the boundary of the type. 751 /// 752 /// The only case where such wrapping can occur is when one takes the 753 /// absolute value of the negative minimal value for the type this is a 754 /// positive value that is too large to represent in the type. In such a 755 /// case, this function returns `MIN` itself. wrapping_abs(self) -> Self756 fn wrapping_abs(self) -> Self; 757 758 /// Computes the absolute value of `self`. 759 /// 760 /// Returns a tuple of the absolute version of self along with a boolean 761 /// indicating whether an overflow happened. If self is the minimum value 762 /// (e.g., iN::MIN for values of type iN), then the minimum value will be 763 /// returned again and true will be returned for an overflow happening. overflowing_abs(self) -> (Self, bool)764 fn overflowing_abs(self) -> (Self, bool); 765 766 //// Computes the absolute value of self. 767 /// 768 /// # Overflow behavior 769 /// 770 /// The absolute value of `iN::min_value()` cannot be represented as an 771 /// `iN`, and attempting to calculate it will cause an overflow. This means 772 /// that code in debug mode will trigger a panic on this case and optimized 773 /// code will return `iN::min_value()` without a panic. abs(self) -> Self774 fn abs(self) -> Self; 775 776 /// Returns a number representing sign of `self`. 777 /// 778 /// - `0` if the number is zero 779 /// - `1` if the number is positive 780 /// - `-1` if the number is negative signum(self) -> Self781 fn signum(self) -> Self; 782 783 /// Returns `true` if `self` is positive and `false` if the number is zero 784 /// or negative. is_positive(self) -> bool785 fn is_positive(self) -> bool; 786 787 /// Returns `true` if `self` is negative and `false` if the number is zero 788 /// or positive. is_negative(self) -> bool789 fn is_negative(self) -> bool; 790 } 791 792 /// Declare that a type is an unsigned integer. 793 pub trait IsUnsigned: IsInteger { 794 /// Returns `true` if and only if `self == 2^k` for some `k`. is_power_of_two(self) -> bool795 fn is_power_of_two(self) -> bool; 796 797 /// Returns the smallest power of two greater than or equal to `self`. 798 /// 799 /// When return value overflows (i.e., `self > (1 << (N-1))` for type `uN`), 800 /// it panics in debug mode and return value is wrapped to 0 in release mode 801 /// (the only situation in which method can return 0). next_power_of_two(self) -> Self802 fn next_power_of_two(self) -> Self; 803 804 /// Returns the smallest power of two greater than or equal to `n`. If the 805 /// next power of two is greater than the type’s maximum value, `None` is 806 /// returned, otherwise the power of two is wrapped in `Some`. checked_next_power_of_two(self) -> Option<Self>807 fn checked_next_power_of_two(self) -> Option<Self>; 808 } 809 810 /// Declare that a type is a floating-point number. 811 pub trait IsFloat: 812 IsNumber 813 + LowerExp 814 + UpperExp 815 + Neg 816 + From<f32> 817 + From<i8> 818 + From<i16> 819 + From<u8> 820 + From<u16> 821 { 822 /// The unsigned integer type of the same width as `Self`. 823 type Raw: IsUnsigned; 824 825 /// The radix or base of the internal representation of `f32`. 826 const RADIX: u32; 827 828 /// Number of significant digits in base 2. 829 const MANTISSA_DIGITS: u32; 830 831 /// Approximate number of significant digits in base 10. 832 const DIGITS: u32; 833 834 /// [Machine epsilon] value for `f32`. 835 /// 836 /// This is the difference between `1.0` and the next larger representable 837 /// number. 838 /// 839 /// [Machine epsilon]: https://en.wikipedia.org/wiki/Machine_epsilon 840 const EPSILON: Self; 841 842 /// Smallest finite `f32` value. 843 const MIN: Self; 844 845 /// Smallest positive normal `f32` value. 846 const MIN_POSITIVE: Self; 847 848 /// Largest finite `f32` value. 849 const MAX: Self; 850 851 /// One greater than the minimum possible normal power of 2 exponent. 852 const MIN_EXP: i32; 853 854 /// Maximum possible power of 2 exponent. 855 const MAX_EXP: i32; 856 857 /// Minimum possible normal power of 10 exponent. 858 const MIN_10_EXP: i32; 859 860 /// Maximum possible power of 10 exponent. 861 const MAX_10_EXP: i32; 862 863 /// Not a Number (NaN). 864 const NAN: Self; 865 866 /// Infinity (∞). 867 const INFINITY: Self; 868 869 /// Negative infinity (−∞). 870 const NEG_INFINITY: Self; 871 872 /// Archimedes' constant (π) 873 const PI: Self; 874 875 /// π/2 876 const FRAC_PI_2: Self; 877 878 /// π/3 879 const FRAC_PI_3: Self; 880 881 /// π/4 882 const FRAC_PI_4: Self; 883 884 /// π/6 885 const FRAC_PI_6: Self; 886 887 /// π/8 888 const FRAC_PI_8: Self; 889 890 /// 1/π 891 const FRAC_1_PI: Self; 892 893 /// 2/π 894 const FRAC_2_PI: Self; 895 896 /// 2/sqrt(π) 897 const FRAC_2_SQRT_PI: Self; 898 899 /// sqrt(2) 900 const SQRT_2: Self; 901 902 /// 1/sqrt(2) 903 const FRAC_1_SQRT_2: Self; 904 905 /// Euler’s number (e) 906 const E: Self; 907 908 /// log<sub>2</sub>(e) 909 const LOG2_E: Self; 910 911 /// log<sub>10</sub>(e) 912 const LOG10_E: Self; 913 914 /// ln(2) 915 const LN_2: Self; 916 917 /// ln(10) 918 const LN_10: Self; 919 920 // These functions are only available in `libstd`, because they rely on the 921 // system math library `libm` which is not provided by `libcore`. 922 923 /// Returns the largest integer less than or equal to a number. 924 #[cfg(feature = "std")] floor(self) -> Self925 fn floor(self) -> Self; 926 927 /// Returns the smallest integer greater than or equal to a number. 928 #[cfg(feature = "std")] ceil(self) -> Self929 fn ceil(self) -> Self; 930 931 /// Returns the nearest integer to a number. Round half-way cases away from 932 /// `0.0`. 933 #[cfg(feature = "std")] round(self) -> Self934 fn round(self) -> Self; 935 936 /// Returns the integer part of a number. 937 #[cfg(feature = "std")] trunc(self) -> Self938 fn trunc(self) -> Self; 939 940 /// Returns the fractional part of a number. 941 #[cfg(feature = "std")] fract(self) -> Self942 fn fract(self) -> Self; 943 944 /// Computes the absolute value of `self`. Returns `NAN` if the 945 /// number is `NAN`. 946 #[cfg(feature = "std")] abs(self) -> Self947 fn abs(self) -> Self; 948 949 /// Returns a number that represents the sign of `self`. 950 /// 951 /// - `1.0` if the number is positive, `+0.0` or `INFINITY` 952 /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY` 953 /// - `NAN` if the number is `NAN` 954 #[cfg(feature = "std")] signum(self) -> Self955 fn signum(self) -> Self; 956 957 /// Returns a number composed of the magnitude of `self` and the sign of 958 /// `sign`. 959 /// 960 /// Equal to `self` if the sign of `self` and `sign` are the same, otherwise 961 /// equal to `-self`. If `self` is a `NAN`, then a `NAN` with the sign of 962 /// `sign` is returned. 963 #[cfg(feature = "std")] copysign(self, sign: Self) -> Self964 fn copysign(self, sign: Self) -> Self; 965 966 /// Fused multiply-add. Computes `(self * a) + b` with only one rounding 967 /// error, yielding a more accurate result than an unfused multiply-add. 968 /// 969 /// Using `mul_add` can be more performant than an unfused multiply-add if 970 /// the target architecture has a dedicated `fma` CPU instruction. 971 #[cfg(feature = "std")] mul_add(self, a: Self, b: Self) -> Self972 fn mul_add(self, a: Self, b: Self) -> Self; 973 974 /// Calculates Euclidean division, the matching method for `rem_euclid`. 975 /// 976 /// This computes the integer `n` such that 977 /// `self = n * rhs + self.rem_euclid(rhs)`. 978 /// In other words, the result is `self / rhs` rounded to the integer `n` 979 /// such that `self >= n * rhs`. 980 #[cfg(feature = "std")] div_euclid(self, rhs: Self) -> Self981 fn div_euclid(self, rhs: Self) -> Self; 982 983 /// Calculates the least nonnegative remainder of `self (mod rhs)`. 984 /// 985 /// In particular, the return value `r` satisfies `0.0 <= r < rhs.abs()` in 986 /// most cases. However, due to a floating point round-off error it can 987 /// result in `r == rhs.abs()`, violating the mathematical definition, if 988 /// `self` is much smaller than `rhs.abs()` in magnitude and `self < 0.0`. 989 /// This result is not an element of the function's codomain, but it is the 990 /// closest floating point number in the real numbers and thus fulfills the 991 /// property `self == self.div_euclid(rhs) * rhs + self.rem_euclid(rhs)` 992 /// approximatively. 993 #[cfg(feature = "std")] rem_euclid(self, rhs: Self) -> Self994 fn rem_euclid(self, rhs: Self) -> Self; 995 996 /// Raises a number to an integer power. 997 /// 998 /// Using this function is generally faster than using `powf` 999 #[cfg(feature = "std")] powi(self, n: i32) -> Self1000 fn powi(self, n: i32) -> Self; 1001 1002 /// Raises a number to a floating point power. 1003 #[cfg(feature = "std")] powf(self, n: Self) -> Self1004 fn powf(self, n: Self) -> Self; 1005 1006 /// Returns the square root of a number. 1007 /// 1008 /// Returns NaN if `self` is a negative number. 1009 #[cfg(feature = "std")] sqrt(self) -> Self1010 fn sqrt(self) -> Self; 1011 1012 /// Returns `e^(self)`, (the exponential function). 1013 #[cfg(feature = "std")] exp(self) -> Self1014 fn exp(self) -> Self; 1015 1016 /// Returns `2^(self)`. 1017 #[cfg(feature = "std")] exp2(self) -> Self1018 fn exp2(self) -> Self; 1019 1020 /// Returns the natural logarithm of the number. 1021 #[cfg(feature = "std")] ln(self) -> Self1022 fn ln(self) -> Self; 1023 1024 /// Returns the logarithm of the number with respect to an arbitrary base. 1025 /// 1026 /// The result may not be correctly rounded owing to implementation details; 1027 /// `self.log2()` can produce more accurate results for base 2, and 1028 /// `self.log10()` can produce more accurate results for base 10. 1029 #[cfg(feature = "std")] log(self, base: Self) -> Self1030 fn log(self, base: Self) -> Self; 1031 1032 /// Returns the base 2 logarithm of the number. 1033 #[cfg(feature = "std")] log2(self) -> Self1034 fn log2(self) -> Self; 1035 1036 /// Returns the base 10 logarithm of the number. 1037 #[cfg(feature = "std")] log10(self) -> Self1038 fn log10(self) -> Self; 1039 1040 /// Returns the cubic root of a number. 1041 #[cfg(feature = "std")] cbrt(self) -> Self1042 fn cbrt(self) -> Self; 1043 1044 /// Computes the sine of a number (in radians). 1045 #[cfg(feature = "std")] hypot(self, other: Self) -> Self1046 fn hypot(self, other: Self) -> Self; 1047 1048 /// Computes the sine of a number (in radians). 1049 #[cfg(feature = "std")] sin(self) -> Self1050 fn sin(self) -> Self; 1051 1052 /// Computes the cosine of a number (in radians). 1053 #[cfg(feature = "std")] cos(self) -> Self1054 fn cos(self) -> Self; 1055 1056 /// Computes the tangent of a number (in radians). 1057 #[cfg(feature = "std")] tan(self) -> Self1058 fn tan(self) -> Self; 1059 1060 /// Computes the arcsine of a number. Return value is in radians in the 1061 /// range [-pi/2, pi/2] or NaN if the number is outside the range [-1, 1]. 1062 #[cfg(feature = "std")] asin(self) -> Self1063 fn asin(self) -> Self; 1064 1065 /// Computes the arccosine of a number. Return value is in radians in the 1066 /// range [0, pi] or NaN if the number is outside the range [-1, 1]. 1067 #[cfg(feature = "std")] acos(self) -> Self1068 fn acos(self) -> Self; 1069 1070 /// Computes the arctangent of a number. Return value is in radians in the 1071 /// range [-pi/2, pi/2]; 1072 #[cfg(feature = "std")] atan(self) -> Self1073 fn atan(self) -> Self; 1074 1075 /// Computes the four quadrant arctangent of `self` (`y`) and `other` (`x`) 1076 /// in radians. 1077 /// 1078 /// - `x = 0`, `y = 0`: `0` 1079 /// - `x >= 0`: `arctan(y/x)` -> `[-pi/2, pi/2]` 1080 /// - `y >= 0`: `arctan(y/x) + pi` -> `(pi/2, pi]` 1081 /// - `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)` 1082 #[cfg(feature = "std")] atan2(self, other: Self) -> Self1083 fn atan2(self, other: Self) -> Self; 1084 1085 /// Simultaneously computes the sine and cosine of the number, `x`. Returns 1086 /// `(sin(x), cos(x))`. 1087 #[cfg(feature = "std")] sin_cos(self) -> (Self, Self)1088 fn sin_cos(self) -> (Self, Self); 1089 1090 /// Returns `e^(self) - 1` in a way that is accurate even if the number is 1091 /// close to zero. 1092 #[cfg(feature = "std")] exp_m1(self) -> Self1093 fn exp_m1(self) -> Self; 1094 1095 /// Returns `ln(1+n)` (natural logarithm) more accurately than if the 1096 /// operations were performed separately. 1097 #[cfg(feature = "std")] ln_1p(self) -> Self1098 fn ln_1p(self) -> Self; 1099 1100 /// Hyperbolic sine function. 1101 #[cfg(feature = "std")] sinh(self) -> Self1102 fn sinh(self) -> Self; 1103 1104 /// Hyperbolic cosine function. 1105 #[cfg(feature = "std")] cosh(self) -> Self1106 fn cosh(self) -> Self; 1107 1108 /// Hyperbolic tangent function. 1109 #[cfg(feature = "std")] tanh(self) -> Self1110 fn tanh(self) -> Self; 1111 1112 /// Inverse hyperbolic sine function. 1113 #[cfg(feature = "std")] asinh(self) -> Self1114 fn asinh(self) -> Self; 1115 1116 /// Inverse hyperbolic cosine function. 1117 #[cfg(feature = "std")] acosh(self) -> Self1118 fn acosh(self) -> Self; 1119 1120 /// Inverse hyperbolic tangent function. 1121 #[cfg(feature = "std")] atanh(self) -> Self1122 fn atanh(self) -> Self; 1123 1124 /// Returns `true` if this value is `NaN`. is_nan(self) -> bool1125 fn is_nan(self) -> bool; 1126 1127 /// Returns `true` if this value is positive infinity or negative infinity, 1128 /// and `false` otherwise. is_infinite(self) -> bool1129 fn is_infinite(self) -> bool; 1130 1131 /// Returns `true` if this number is neither infinite nor `NaN`. is_finite(self) -> bool1132 fn is_finite(self) -> bool; 1133 1134 /// Returns `true` if the number is neither zero, infinite, [subnormal], or 1135 /// `NaN`. 1136 /// 1137 /// [subnormal]: https://en.wixipedia.org/wiki/Denormal_number is_normal(self) -> bool1138 fn is_normal(self) -> bool; 1139 1140 /// Returns the floating point category of the number. If only one property 1141 /// is going to be tested, it is generally faster to use the specific 1142 /// predicate instead. classify(self) -> FpCategory1143 fn classify(self) -> FpCategory; 1144 1145 /// Returns `true` if `self` has a positive sign, including `+0.0`, `NaN`s 1146 /// with positive sign bit and positive infinity. is_sign_positive(self) -> bool1147 fn is_sign_positive(self) -> bool; 1148 1149 /// Returns `true` if `self` has a negative sign, including `-0.0`, `NaN`s 1150 /// with negative sign bit and negative infinity. is_sign_negative(self) -> bool1151 fn is_sign_negative(self) -> bool; 1152 1153 /// Takes the reciprocal (inverse) of a number, `1/x`. recip(self) -> Self1154 fn recip(self) -> Self; 1155 1156 /// Converts radians to degrees. to_degrees(self) -> Self1157 fn to_degrees(self) -> Self; 1158 1159 /// Converts degrees to radians. to_radians(self) -> Self1160 fn to_radians(self) -> Self; 1161 1162 /// Returns the maximum of the two numbers. max(self, other: Self) -> Self1163 fn max(self, other: Self) -> Self; 1164 1165 /// Returns the minimum of the two numbers. min(self, other: Self) -> Self1166 fn min(self, other: Self) -> Self; 1167 1168 /// Raw transmutation to `u32`. 1169 /// 1170 /// This is currently identical to `transmute::<f32, u32>(self)` on all 1171 /// platforms. 1172 /// 1173 /// See `from_bits` for some discussion of the portability of this operation 1174 /// (there are almost no issues). 1175 /// 1176 /// Note that this function is distinct from `as` casting, which attempts to 1177 /// preserve the *numeric* value, and not the bitwise value. to_bits(self) -> Self::Raw1178 fn to_bits(self) -> Self::Raw; 1179 1180 /// Raw transmutation from `u32`. 1181 /// 1182 /// This is currently identical to `transmute::<u32, f32>(v)` on all 1183 /// platforms. It turns out this is incredibly portable, for two reasons: 1184 /// 1185 /// - Floats and Ints have the same endianness on all supported platforms. 1186 /// - IEEE-754 very precisely specifies the bit layout of floats. 1187 /// 1188 /// However there is one caveat: prior to the 2008 version of IEEE-754, how 1189 /// to interpret the NaN signaling bit wasn't actually specified. Most 1190 /// platforms (notably x86 and ARM) picked the interpretation that was 1191 /// ultimately standardized in 2008, but some didn't (notably MIPS). As a 1192 /// result, all signaling NaNs on MIPS are quiet NaNs on x86, and 1193 /// vice-versa. 1194 /// 1195 /// Rather than trying to preserve signaling-ness cross-platform, this 1196 /// implementation favors preserving the exact bits. This means that 1197 /// any payloads encoded in NaNs will be preserved even if the result of 1198 /// this method is sent over the network from an x86 machine to a MIPS one. 1199 /// 1200 /// If the results of this method are only manipulated by the same 1201 /// architecture that produced them, then there is no portability concern. 1202 /// 1203 /// If the input isn't NaN, then there is no portability concern. 1204 /// 1205 /// If you don't care about signalingness (very likely), then there is no 1206 /// portability concern. 1207 /// 1208 /// Note that this function is distinct from `as` casting, which attempts to 1209 /// preserve the *numeric* value, and not the bitwise value. from_bits(bits: Self::Raw) -> Self1210 fn from_bits(bits: Self::Raw) -> Self; 1211 } 1212 1213 /// Declare that a type is exactly eight bits wide. 1214 pub trait Is8: IsNumber {} 1215 1216 /// Declare that a type is exactly sixteen bits wide. 1217 pub trait Is16: IsNumber {} 1218 1219 /// Declare that a type is exactly thirty-two bits wide. 1220 pub trait Is32: IsNumber {} 1221 1222 /// Declare that a type is exactly sixty-four bits wide. 1223 pub trait Is64: IsNumber {} 1224 1225 /// Declare that a type is exactly one hundred twenty-eight bits wide. 1226 pub trait Is128: IsNumber {} 1227 1228 /// Declare that a type is eight or more bits wide. 1229 pub trait AtLeast8: IsNumber {} 1230 1231 /// Declare that a type is sixteen or more bits wide. 1232 pub trait AtLeast16: IsNumber {} 1233 1234 /// Declare that a type is thirty-two or more bits wide. 1235 pub trait AtLeast32: IsNumber {} 1236 1237 /// Declare that a type is sixty-four or more bits wide. 1238 pub trait AtLeast64: IsNumber {} 1239 1240 /// Declare that a type is one hundred twenty-eight or more bits wide. 1241 pub trait AtLeast128: IsNumber {} 1242 1243 /// Declare that a type is eight or fewer bits wide. 1244 pub trait AtMost8: IsNumber {} 1245 1246 /// Declare that a type is sixteen or fewer bits wide. 1247 pub trait AtMost16: IsNumber {} 1248 1249 /// Declare that a type is thirty-two or fewer bits wide. 1250 pub trait AtMost32: IsNumber {} 1251 1252 /// Declare that a type is sixty-four or fewer bits wide. 1253 pub trait AtMost64: IsNumber {} 1254 1255 /// Declare that a type is one hundred twenty-eight or fewer bits wide. 1256 pub trait AtMost128: IsNumber {} 1257 1258 macro_rules! func { 1259 ( $name:ident ( self $(, $arg:ident : $t:ty)* ) $( -> $ret:ty )? ) => { 1260 fn $name ( self $(, $arg : $t )* ) $( -> $ret )? { <Self>:: $name ( self $(, $arg )* )} 1261 }; 1262 ( $name:ident ( &self $(, $arg:ident : $t:ty)* ) $( -> $ret:ty )? ) => { 1263 fn $name ( &self $(, $arg : $t )* ) $( -> $ret )? { <Self>:: $name ( &self $(, $arg )* )} 1264 }; 1265 ( $name:ident ( &mut self $(, $arg:ident : $t:ty)* ) $( -> $ret:ty )? ) => { 1266 fn $name ( &mut self $(, $arg : $t )* ) $( -> $ret )? { <Self>:: $name ( &mut self $(, $arg )* )} 1267 }; 1268 ( $name:ident ( $($arg:ident : $t:ty),* ) $( -> $ret:ty )? ) => { 1269 fn $name ( $($arg : $t ),* ) $( -> $ret )? { <Self>:: $name ( $( $arg ),* )} 1270 }; 1271 } 1272 1273 macro_rules! stdfunc { 1274 ( $name:ident ( self $(, $arg:ident : $t:ty)* ) $( -> $ret:ty )? ) => { 1275 #[cfg(feature = "std")] 1276 fn $name ( self $(, $arg : $t )* ) $( -> $ret )? { <Self>:: $name ( self $(, $arg )* )} 1277 }; 1278 ( $name:ident ( &self $(, $arg:ident : $t:ty)* ) $( -> $ret:ty )? ) => { 1279 #[cfg(feature = "std")] 1280 fn $name ( &self $(, $arg : $t )* ) $( -> $ret )? { <Self>:: $name ( &self $(, $arg )* )} 1281 }; 1282 ( $name:ident ( &mut self $(, $arg:ident : $t:ty)* ) $( -> $ret:ty )? ) => { 1283 #[cfg(feature = "std")] 1284 fn $name ( &mut self $(, $arg : $t )* ) $( -> $ret )? { <Self>:: $name ( &mut self $(, $arg )* )} 1285 }; 1286 ( $name:ident ( $($arg:ident : $t:ty),* ) $( -> $ret:ty )? ) => { 1287 #[cfg(feature = "std")] 1288 fn $name ( $($arg : $t ),* ) $( -> $ret )? { <Self>:: $name ( $( $arg ),* )} 1289 }; 1290 } 1291 1292 macro_rules! impl_for { 1293 ( IsNumber => $($t:ty),+ $(,)? ) => { $( 1294 impl IsNumber for $t { 1295 type Bytes = [u8; core::mem::size_of::<Self>()]; 1296 1297 func!(to_be_bytes(self) -> Self::Bytes); 1298 func!(to_le_bytes(self) -> Self::Bytes); 1299 func!(to_ne_bytes(self) -> Self::Bytes); 1300 func!(from_be_bytes(bytes: Self::Bytes) -> Self); 1301 func!(from_le_bytes(bytes: Self::Bytes) -> Self); 1302 func!(from_ne_bytes(bytes: Self::Bytes) -> Self); 1303 } 1304 )+ }; 1305 ( IsInteger => $($t:ty),+ $(,)? ) => { $( 1306 impl IsInteger for $t { 1307 const ZERO: Self = 0; 1308 const MIN: Self = <Self>::min_value(); 1309 const MAX: Self = <Self>::max_value(); 1310 1311 func!(min_value() -> Self); 1312 func!(max_value() -> Self); 1313 func!(from_str_radix(src: &str, radix: u32) -> Result<Self, ParseIntError>); 1314 func!(count_ones(self) -> u32); 1315 func!(count_zeros(self) -> u32); 1316 func!(leading_zeros(self) -> u32); 1317 func!(trailing_zeros(self) -> u32); 1318 func!(leading_ones(self) -> u32); 1319 func!(trailing_ones(self) -> u32); 1320 func!(rotate_left(self, n: u32) -> Self); 1321 func!(rotate_right(self, n: u32) -> Self); 1322 func!(swap_bytes(self) -> Self); 1323 func!(reverse_bits(self) -> Self); 1324 func!(from_be(self) -> Self); 1325 func!(from_le(self) -> Self); 1326 func!(to_be(self) -> Self); 1327 func!(to_le(self) -> Self); 1328 func!(checked_add(self, rhs: Self) -> Option<Self>); 1329 func!(checked_sub(self, rhs: Self) -> Option<Self>); 1330 func!(checked_mul(self, rhs: Self) -> Option<Self>); 1331 func!(checked_div(self, rhs: Self) -> Option<Self>); 1332 func!(checked_div_euclid(self, rhs: Self) -> Option<Self>); 1333 func!(checked_rem(self, rhs: Self) -> Option<Self>); 1334 func!(checked_rem_euclid(self, rhs: Self) -> Option<Self>); 1335 func!(checked_neg(self) -> Option<Self>); 1336 func!(checked_shl(self, rhs: u32) -> Option<Self>); 1337 func!(checked_shr(self, rhs: u32) -> Option<Self>); 1338 func!(checked_pow(self, rhs: u32) -> Option<Self>); 1339 func!(saturating_add(self, rhs: Self) -> Self); 1340 func!(saturating_sub(self, rhs: Self) -> Self); 1341 func!(saturating_mul(self, rhs: Self) -> Self); 1342 func!(saturating_pow(self, rhs: u32) -> Self); 1343 func!(wrapping_add(self, rhs: Self) -> Self); 1344 func!(wrapping_sub(self, rhs: Self) -> Self); 1345 func!(wrapping_mul(self, rhs: Self) -> Self); 1346 func!(wrapping_div(self, rhs: Self) -> Self); 1347 func!(wrapping_div_euclid(self, rhs: Self) -> Self); 1348 func!(wrapping_rem(self, rhs: Self) -> Self); 1349 func!(wrapping_rem_euclid(self, rhs: Self) -> Self); 1350 func!(wrapping_neg(self) -> Self); 1351 func!(wrapping_shl(self, rhs: u32) -> Self); 1352 func!(wrapping_shr(self, rhs: u32) -> Self); 1353 func!(wrapping_pow(self, rhs: u32) -> Self); 1354 func!(overflowing_add(self, rhs: Self) -> (Self, bool)); 1355 func!(overflowing_sub(self, rhs: Self) -> (Self, bool)); 1356 func!(overflowing_mul(self, rhs: Self) -> (Self, bool)); 1357 func!(overflowing_div(self, rhs: Self) -> (Self, bool)); 1358 func!(overflowing_div_euclid(self, rhs: Self) -> (Self, bool)); 1359 func!(overflowing_rem(self, rhs: Self) -> (Self, bool)); 1360 func!(overflowing_rem_euclid(self, rhs: Self) -> (Self, bool)); 1361 func!(overflowing_neg(self) -> (Self, bool)); 1362 func!(overflowing_shl(self, rhs: u32) -> (Self, bool)); 1363 func!(overflowing_shr(self, rhs: u32) -> (Self, bool)); 1364 func!(overflowing_pow(self, rhs: u32) -> (Self, bool)); 1365 func!(pow(self, rhs: u32) -> Self); 1366 func!(div_euclid(self, rhs: Self) -> Self); 1367 func!(rem_euclid(self, rhs: Self) -> Self); 1368 } 1369 )+ }; 1370 ( IsSigned => $($t:ty),+ $(,)? ) => { $( 1371 impl IsSigned for $t { 1372 func!(checked_abs(self) -> Option<Self>); 1373 func!(wrapping_abs(self) -> Self); 1374 func!(overflowing_abs(self) -> (Self, bool)); 1375 func!(abs(self) -> Self); 1376 func!(signum(self) -> Self); 1377 func!(is_positive(self) -> bool); 1378 func!(is_negative(self) -> bool); 1379 } 1380 )+ }; 1381 ( IsUnsigned => $($t:ty),+ $(,)? ) => { $( 1382 impl IsUnsigned for $t { 1383 func!(is_power_of_two(self) -> bool); 1384 func!(next_power_of_two(self) -> Self); 1385 func!(checked_next_power_of_two(self) -> Option<Self>); 1386 } 1387 )+ }; 1388 ( IsFloat => $($t:ident | $u:ty),+ $(,)? ) => { $( 1389 impl IsFloat for $t { 1390 type Raw = $u; 1391 1392 const RADIX: u32 = core::$t::RADIX; 1393 const MANTISSA_DIGITS: u32 = core::$t::MANTISSA_DIGITS; 1394 const DIGITS: u32 = core::$t::DIGITS; 1395 const EPSILON: Self = core::$t::EPSILON; 1396 const MIN: Self = core::$t::MIN; 1397 const MIN_POSITIVE: Self = core::$t::MIN_POSITIVE; 1398 const MAX: Self = core::$t::MAX; 1399 const MIN_EXP: i32 = core::$t::MIN_EXP; 1400 const MAX_EXP: i32 = core::$t::MAX_EXP; 1401 const MIN_10_EXP: i32 = core::$t::MIN_10_EXP; 1402 const MAX_10_EXP: i32 = core::$t::MAX_10_EXP; 1403 const NAN: Self = core::$t::NAN; 1404 const INFINITY: Self = core::$t::INFINITY; 1405 const NEG_INFINITY: Self = core::$t::NEG_INFINITY; 1406 1407 const PI: Self = core::$t::consts::PI; 1408 const FRAC_PI_2: Self = core::$t::consts::FRAC_PI_2; 1409 const FRAC_PI_3: Self = core::$t::consts::FRAC_PI_3; 1410 const FRAC_PI_4: Self = core::$t::consts::FRAC_PI_4; 1411 const FRAC_PI_6: Self = core::$t::consts::FRAC_PI_6; 1412 const FRAC_PI_8: Self = core::$t::consts::FRAC_PI_8; 1413 const FRAC_1_PI: Self = core::$t::consts::FRAC_1_PI; 1414 const FRAC_2_PI: Self = core::$t::consts::FRAC_2_PI; 1415 const FRAC_2_SQRT_PI: Self = core::$t::consts::FRAC_2_SQRT_PI; 1416 const SQRT_2: Self = core::$t::consts::SQRT_2; 1417 const FRAC_1_SQRT_2: Self = core::$t::consts::FRAC_1_SQRT_2; 1418 const E: Self = core::$t::consts::E; 1419 const LOG2_E: Self = core::$t::consts::LOG2_E; 1420 const LOG10_E: Self = core::$t::consts::LOG10_E; 1421 const LN_2: Self = core::$t::consts::LN_2; 1422 const LN_10: Self = core::$t::consts::LN_10; 1423 1424 stdfunc!(floor(self) -> Self); 1425 stdfunc!(ceil(self) -> Self); 1426 stdfunc!(round(self) -> Self); 1427 stdfunc!(trunc(self) -> Self); 1428 stdfunc!(fract(self) -> Self); 1429 stdfunc!(abs(self) -> Self); 1430 stdfunc!(signum(self) -> Self); 1431 stdfunc!(copysign(self, sign: Self) -> Self); 1432 stdfunc!(mul_add(self, a: Self, b: Self) -> Self); 1433 stdfunc!(div_euclid(self, rhs: Self) -> Self); 1434 stdfunc!(rem_euclid(self, rhs: Self) -> Self); 1435 stdfunc!(powi(self, n: i32) -> Self); 1436 stdfunc!(powf(self, n: Self) -> Self); 1437 stdfunc!(sqrt(self) -> Self); 1438 stdfunc!(exp(self) -> Self); 1439 stdfunc!(exp2(self) -> Self); 1440 stdfunc!(ln(self) -> Self); 1441 stdfunc!(log(self, base: Self) -> Self); 1442 stdfunc!(log2(self) -> Self); 1443 stdfunc!(log10(self) -> Self); 1444 stdfunc!(cbrt(self) -> Self); 1445 stdfunc!(hypot(self, other: Self) -> Self); 1446 stdfunc!(sin(self) -> Self); 1447 stdfunc!(cos(self) -> Self); 1448 stdfunc!(tan(self) -> Self); 1449 stdfunc!(asin(self) -> Self); 1450 stdfunc!(acos(self) -> Self); 1451 stdfunc!(atan(self) -> Self); 1452 stdfunc!(atan2(self, other: Self) -> Self); 1453 stdfunc!(sin_cos(self) -> (Self, Self)); 1454 stdfunc!(exp_m1(self) -> Self); 1455 stdfunc!(ln_1p(self) -> Self); 1456 stdfunc!(sinh(self) -> Self); 1457 stdfunc!(cosh(self) -> Self); 1458 stdfunc!(tanh(self) -> Self); 1459 stdfunc!(asinh(self) -> Self); 1460 stdfunc!(acosh(self) -> Self); 1461 stdfunc!(atanh(self) -> Self); 1462 1463 func!(is_nan(self) -> bool); 1464 func!(is_infinite(self) -> bool); 1465 func!(is_finite(self) -> bool); 1466 func!(is_normal(self) -> bool); 1467 func!(classify(self) -> FpCategory); 1468 func!(is_sign_positive(self) -> bool); 1469 func!(is_sign_negative(self) -> bool); 1470 func!(recip(self) -> Self); 1471 func!(to_degrees(self) -> Self); 1472 func!(to_radians(self) -> Self); 1473 func!(max(self, other: Self) -> Self); 1474 func!(min(self, other: Self) -> Self); 1475 func!(to_bits(self) -> Self::Raw); 1476 func!(from_bits(bits: Self::Raw) -> Self); 1477 } 1478 )+ }; 1479 ( $which:ty => $($t:ty),+ $(,)? ) => { $( 1480 impl $which for $t {} 1481 )+ }; 1482 } 1483 1484 impl_for!(IsNumber => i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64); 1485 impl_for!(IsInteger => i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize); 1486 impl_for!(IsSigned => i8, i16, i32, i64, i128, isize); 1487 impl_for!(IsUnsigned => u8, u16, u32, u64, u128, usize); 1488 impl_for!(IsFloat => f32 | u32, f64 | u64); 1489 1490 impl_for!(Is8 => i8, u8); 1491 impl_for!(Is16 => i16, u16); 1492 impl_for!(Is32 => i32, u32, f32); 1493 impl_for!(Is64 => i64, u64, f64); 1494 impl_for!(Is128 => i128, u128); 1495 1496 #[cfg(target_pointer_width = "16")] 1497 impl_for!(Is16 => isize, usize); 1498 1499 #[cfg(target_pointer_width = "32")] 1500 impl_for!(Is32 => isize, usize); 1501 1502 #[cfg(target_pointer_width = "64")] 1503 impl_for!(Is64 => isize, usize); 1504 1505 impl_for!(AtLeast8 => i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64); 1506 impl_for!(AtLeast16 => i16, i32, i64, i128, u16, u32, u64, u128, f32, f64); 1507 impl_for!(AtLeast32 => i32, i64, i128, u32, u64, u128, f32, f64); 1508 impl_for!(AtLeast64 => i64, i128, u64, u128, f64); 1509 impl_for!(AtLeast128 => i128, u128); 1510 1511 #[cfg(any( 1512 target_pointer_width = "16", 1513 target_pointer_width = "32", 1514 target_pointer_width = "64" 1515 ))] 1516 impl_for!(AtLeast16 => isize, usize); 1517 1518 #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))] 1519 impl_for!(AtLeast32 => isize, usize); 1520 1521 #[cfg(target_pointer_width = "64")] 1522 impl_for!(AtLeast64 => isize, usize); 1523 1524 impl_for!(AtMost8 => i8, u8); 1525 impl_for!(AtMost16 => i8, i16, u8, u16); 1526 impl_for!(AtMost32 => i8, i16, i32, u8, u16, u32, f32); 1527 impl_for!(AtMost64 => i8, i16, i32, i64, isize, u8, u16, u32, u64, usize, f32, f64); 1528 impl_for!(AtMost128 => i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize, f32, f64); 1529 1530 #[cfg(target_pointer_width = "16")] 1531 impl_for!(AtMost16 => isize, usize); 1532 1533 #[cfg(any(target_pointer_width = "16", target_pointer_width = "32"))] 1534 impl_for!(AtMost32 => isize, usize); 1535 1536 #[cfg(test)] 1537 mod tests { 1538 use super::*; 1539 use static_assertions::*; 1540 1541 assert_impl_all!(i8: IsInteger, IsSigned, Is8); 1542 assert_impl_all!(i16: IsInteger, IsSigned, Is16); 1543 assert_impl_all!(i32: IsInteger, IsSigned, Is32); 1544 assert_impl_all!(i64: IsInteger, IsSigned, Is64); 1545 assert_impl_all!(i128: IsInteger, IsSigned, Is128); 1546 assert_impl_all!(isize: IsInteger, IsSigned); 1547 1548 assert_impl_all!(u8: IsInteger, IsUnsigned, Is8); 1549 assert_impl_all!(u16: IsInteger, IsUnsigned, Is16); 1550 assert_impl_all!(u32: IsInteger, IsUnsigned, Is32); 1551 assert_impl_all!(u64: IsInteger, IsUnsigned, Is64); 1552 assert_impl_all!(u128: IsInteger, IsUnsigned, Is128); 1553 assert_impl_all!(usize: IsInteger, IsUnsigned); 1554 1555 assert_impl_all!(f32: IsFloat, Is32); 1556 assert_impl_all!(f64: IsFloat, Is64); 1557 } 1558