lib.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  1. // Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
  2. // file at the top-level directory of this distribution and at
  3. // http://rust-lang.org/COPYRIGHT.
  4. //
  5. // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
  6. // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
  7. // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
  8. // option. This file may not be copied, modified, or distributed
  9. // except according to those terms.
  10. //! Numeric traits for generic mathematics
  11. //!
  12. //! ## Compatibility
  13. //!
  14. //! The `num-traits` crate is tested for rustc 1.8 and greater.
  15. #![doc(html_root_url = "https://docs.rs/num-traits/0.2")]
  16. #![deny(unconditional_recursion)]
  17. #![no_std]
  18. #[cfg(feature = "std")]
  19. extern crate std;
  20. // Only `no_std` builds actually use `libm`.
  21. #[cfg(all(not(feature = "std"), feature = "libm"))]
  22. extern crate libm;
  23. use core::fmt;
  24. use core::num::Wrapping;
  25. use core::ops::{Add, Div, Mul, Rem, Sub};
  26. use core::ops::{AddAssign, DivAssign, MulAssign, RemAssign, SubAssign};
  27. pub use bounds::Bounded;
  28. #[cfg(any(feature = "std", feature = "libm"))]
  29. pub use float::Float;
  30. pub use float::FloatConst;
  31. // pub use real::{FloatCore, Real}; // NOTE: Don't do this, it breaks `use num_traits::*;`.
  32. pub use cast::{cast, AsPrimitive, FromPrimitive, NumCast, ToPrimitive};
  33. pub use identities::{one, zero, One, Zero};
  34. pub use int::PrimInt;
  35. pub use ops::checked::{
  36. CheckedAdd, CheckedDiv, CheckedMul, CheckedNeg, CheckedRem, CheckedShl, CheckedShr, CheckedSub,
  37. };
  38. pub use ops::inv::Inv;
  39. pub use ops::mul_add::{MulAdd, MulAddAssign};
  40. pub use ops::saturating::{SaturatingAdd, SaturatingMul, SaturatingSub};
  41. pub use ops::wrapping::{
  42. WrappingAdd, WrappingMul, WrappingNeg, WrappingShl, WrappingShr, WrappingSub,
  43. };
  44. pub use pow::{checked_pow, pow, Pow};
  45. pub use sign::{abs, abs_sub, signum, Signed, Unsigned};
  46. #[macro_use]
  47. mod macros;
  48. pub mod bounds;
  49. pub mod cast;
  50. pub mod float;
  51. pub mod identities;
  52. pub mod int;
  53. pub mod ops;
  54. pub mod pow;
  55. pub mod real;
  56. pub mod sign;
  57. /// The base trait for numeric types, covering `0` and `1` values,
  58. /// comparisons, basic numeric operations, and string conversion.
  59. pub trait Num: PartialEq + Zero + One + NumOps {
  60. type FromStrRadixErr;
  61. /// Convert from a string and radix <= 36.
  62. ///
  63. /// # Examples
  64. ///
  65. /// ```rust
  66. /// use num_traits::Num;
  67. ///
  68. /// let result = <i32 as Num>::from_str_radix("27", 10);
  69. /// assert_eq!(result, Ok(27));
  70. ///
  71. /// let result = <i32 as Num>::from_str_radix("foo", 10);
  72. /// assert!(result.is_err());
  73. /// ```
  74. fn from_str_radix(str: &str, radix: u32) -> Result<Self, Self::FromStrRadixErr>;
  75. }
  76. /// The trait for types implementing basic numeric operations
  77. ///
  78. /// This is automatically implemented for types which implement the operators.
  79. pub trait NumOps<Rhs = Self, Output = Self>:
  80. Add<Rhs, Output = Output>
  81. + Sub<Rhs, Output = Output>
  82. + Mul<Rhs, Output = Output>
  83. + Div<Rhs, Output = Output>
  84. + Rem<Rhs, Output = Output>
  85. {
  86. }
  87. impl<T, Rhs, Output> NumOps<Rhs, Output> for T where
  88. T: Add<Rhs, Output = Output>
  89. + Sub<Rhs, Output = Output>
  90. + Mul<Rhs, Output = Output>
  91. + Div<Rhs, Output = Output>
  92. + Rem<Rhs, Output = Output>
  93. {
  94. }
  95. /// The trait for `Num` types which also implement numeric operations taking
  96. /// the second operand by reference.
  97. ///
  98. /// This is automatically implemented for types which implement the operators.
  99. pub trait NumRef: Num + for<'r> NumOps<&'r Self> {}
  100. impl<T> NumRef for T where T: Num + for<'r> NumOps<&'r T> {}
  101. /// The trait for references which implement numeric operations, taking the
  102. /// second operand either by value or by reference.
  103. ///
  104. /// This is automatically implemented for types which implement the operators.
  105. pub trait RefNum<Base>: NumOps<Base, Base> + for<'r> NumOps<&'r Base, Base> {}
  106. impl<T, Base> RefNum<Base> for T where T: NumOps<Base, Base> + for<'r> NumOps<&'r Base, Base> {}
  107. /// The trait for types implementing numeric assignment operators (like `+=`).
  108. ///
  109. /// This is automatically implemented for types which implement the operators.
  110. pub trait NumAssignOps<Rhs = Self>:
  111. AddAssign<Rhs> + SubAssign<Rhs> + MulAssign<Rhs> + DivAssign<Rhs> + RemAssign<Rhs>
  112. {
  113. }
  114. impl<T, Rhs> NumAssignOps<Rhs> for T where
  115. T: AddAssign<Rhs> + SubAssign<Rhs> + MulAssign<Rhs> + DivAssign<Rhs> + RemAssign<Rhs>
  116. {
  117. }
  118. /// The trait for `Num` types which also implement assignment operators.
  119. ///
  120. /// This is automatically implemented for types which implement the operators.
  121. pub trait NumAssign: Num + NumAssignOps {}
  122. impl<T> NumAssign for T where T: Num + NumAssignOps {}
  123. /// The trait for `NumAssign` types which also implement assignment operations
  124. /// taking the second operand by reference.
  125. ///
  126. /// This is automatically implemented for types which implement the operators.
  127. pub trait NumAssignRef: NumAssign + for<'r> NumAssignOps<&'r Self> {}
  128. impl<T> NumAssignRef for T where T: NumAssign + for<'r> NumAssignOps<&'r T> {}
  129. macro_rules! int_trait_impl {
  130. ($name:ident for $($t:ty)*) => ($(
  131. impl $name for $t {
  132. type FromStrRadixErr = ::core::num::ParseIntError;
  133. #[inline]
  134. fn from_str_radix(s: &str, radix: u32)
  135. -> Result<Self, ::core::num::ParseIntError>
  136. {
  137. <$t>::from_str_radix(s, radix)
  138. }
  139. }
  140. )*)
  141. }
  142. int_trait_impl!(Num for usize u8 u16 u32 u64 isize i8 i16 i32 i64);
  143. #[cfg(has_i128)]
  144. int_trait_impl!(Num for u128 i128);
  145. impl<T: Num> Num for Wrapping<T>
  146. where
  147. Wrapping<T>: Add<Output = Wrapping<T>>
  148. + Sub<Output = Wrapping<T>>
  149. + Mul<Output = Wrapping<T>>
  150. + Div<Output = Wrapping<T>>
  151. + Rem<Output = Wrapping<T>>,
  152. {
  153. type FromStrRadixErr = T::FromStrRadixErr;
  154. fn from_str_radix(str: &str, radix: u32) -> Result<Self, Self::FromStrRadixErr> {
  155. T::from_str_radix(str, radix).map(Wrapping)
  156. }
  157. }
  158. #[derive(Debug)]
  159. pub enum FloatErrorKind {
  160. Empty,
  161. Invalid,
  162. }
  163. // FIXME: core::num::ParseFloatError is stable in 1.0, but opaque to us,
  164. // so there's not really any way for us to reuse it.
  165. #[derive(Debug)]
  166. pub struct ParseFloatError {
  167. pub kind: FloatErrorKind,
  168. }
  169. impl fmt::Display for ParseFloatError {
  170. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  171. let description = match self.kind {
  172. FloatErrorKind::Empty => "cannot parse float from empty string",
  173. FloatErrorKind::Invalid => "invalid float literal",
  174. };
  175. description.fmt(f)
  176. }
  177. }
  178. // FIXME: The standard library from_str_radix on floats was deprecated, so we're stuck
  179. // with this implementation ourselves until we want to make a breaking change.
  180. // (would have to drop it from `Num` though)
  181. macro_rules! float_trait_impl {
  182. ($name:ident for $($t:ident)*) => ($(
  183. impl $name for $t {
  184. type FromStrRadixErr = ParseFloatError;
  185. fn from_str_radix(src: &str, radix: u32)
  186. -> Result<Self, Self::FromStrRadixErr>
  187. {
  188. use self::FloatErrorKind::*;
  189. use self::ParseFloatError as PFE;
  190. // Special values
  191. match src {
  192. "inf" => return Ok(core::$t::INFINITY),
  193. "-inf" => return Ok(core::$t::NEG_INFINITY),
  194. "NaN" => return Ok(core::$t::NAN),
  195. _ => {},
  196. }
  197. fn slice_shift_char(src: &str) -> Option<(char, &str)> {
  198. let mut chars = src.chars();
  199. if let Some(ch) = chars.next() {
  200. Some((ch, chars.as_str()))
  201. } else {
  202. None
  203. }
  204. }
  205. let (is_positive, src) = match slice_shift_char(src) {
  206. None => return Err(PFE { kind: Empty }),
  207. Some(('-', "")) => return Err(PFE { kind: Empty }),
  208. Some(('-', src)) => (false, src),
  209. Some((_, _)) => (true, src),
  210. };
  211. // The significand to accumulate
  212. let mut sig = if is_positive { 0.0 } else { -0.0 };
  213. // Necessary to detect overflow
  214. let mut prev_sig = sig;
  215. let mut cs = src.chars().enumerate();
  216. // Exponent prefix and exponent index offset
  217. let mut exp_info = None::<(char, usize)>;
  218. // Parse the integer part of the significand
  219. for (i, c) in cs.by_ref() {
  220. match c.to_digit(radix) {
  221. Some(digit) => {
  222. // shift significand one digit left
  223. sig = sig * (radix as $t);
  224. // add/subtract current digit depending on sign
  225. if is_positive {
  226. sig = sig + ((digit as isize) as $t);
  227. } else {
  228. sig = sig - ((digit as isize) as $t);
  229. }
  230. // Detect overflow by comparing to last value, except
  231. // if we've not seen any non-zero digits.
  232. if prev_sig != 0.0 {
  233. if is_positive && sig <= prev_sig
  234. { return Ok(core::$t::INFINITY); }
  235. if !is_positive && sig >= prev_sig
  236. { return Ok(core::$t::NEG_INFINITY); }
  237. // Detect overflow by reversing the shift-and-add process
  238. if is_positive && (prev_sig != (sig - digit as $t) / radix as $t)
  239. { return Ok(core::$t::INFINITY); }
  240. if !is_positive && (prev_sig != (sig + digit as $t) / radix as $t)
  241. { return Ok(core::$t::NEG_INFINITY); }
  242. }
  243. prev_sig = sig;
  244. },
  245. None => match c {
  246. 'e' | 'E' | 'p' | 'P' => {
  247. exp_info = Some((c, i + 1));
  248. break; // start of exponent
  249. },
  250. '.' => {
  251. break; // start of fractional part
  252. },
  253. _ => {
  254. return Err(PFE { kind: Invalid });
  255. },
  256. },
  257. }
  258. }
  259. // If we are not yet at the exponent parse the fractional
  260. // part of the significand
  261. if exp_info.is_none() {
  262. let mut power = 1.0;
  263. for (i, c) in cs.by_ref() {
  264. match c.to_digit(radix) {
  265. Some(digit) => {
  266. // Decrease power one order of magnitude
  267. power = power / (radix as $t);
  268. // add/subtract current digit depending on sign
  269. sig = if is_positive {
  270. sig + (digit as $t) * power
  271. } else {
  272. sig - (digit as $t) * power
  273. };
  274. // Detect overflow by comparing to last value
  275. if is_positive && sig < prev_sig
  276. { return Ok(core::$t::INFINITY); }
  277. if !is_positive && sig > prev_sig
  278. { return Ok(core::$t::NEG_INFINITY); }
  279. prev_sig = sig;
  280. },
  281. None => match c {
  282. 'e' | 'E' | 'p' | 'P' => {
  283. exp_info = Some((c, i + 1));
  284. break; // start of exponent
  285. },
  286. _ => {
  287. return Err(PFE { kind: Invalid });
  288. },
  289. },
  290. }
  291. }
  292. }
  293. // Parse and calculate the exponent
  294. let exp = match exp_info {
  295. Some((c, offset)) => {
  296. let base = match c {
  297. 'E' | 'e' if radix == 10 => 10.0,
  298. 'P' | 'p' if radix == 16 => 2.0,
  299. _ => return Err(PFE { kind: Invalid }),
  300. };
  301. // Parse the exponent as decimal integer
  302. let src = &src[offset..];
  303. let (is_positive, exp) = match slice_shift_char(src) {
  304. Some(('-', src)) => (false, src.parse::<usize>()),
  305. Some(('+', src)) => (true, src.parse::<usize>()),
  306. Some((_, _)) => (true, src.parse::<usize>()),
  307. None => return Err(PFE { kind: Invalid }),
  308. };
  309. #[cfg(feature = "std")]
  310. fn pow(base: $t, exp: usize) -> $t {
  311. Float::powi(base, exp as i32)
  312. }
  313. // otherwise uses the generic `pow` from the root
  314. match (is_positive, exp) {
  315. (true, Ok(exp)) => pow(base, exp),
  316. (false, Ok(exp)) => 1.0 / pow(base, exp),
  317. (_, Err(_)) => return Err(PFE { kind: Invalid }),
  318. }
  319. },
  320. None => 1.0, // no exponent
  321. };
  322. Ok(sig * exp)
  323. }
  324. }
  325. )*)
  326. }
  327. float_trait_impl!(Num for f32 f64);
  328. /// A value bounded by a minimum and a maximum
  329. ///
  330. /// If input is less than min then this returns min.
  331. /// If input is greater than max then this returns max.
  332. /// Otherwise this returns input.
  333. ///
  334. /// **Panics** in debug mode if `!(min <= max)`.
  335. #[inline]
  336. pub fn clamp<T: PartialOrd>(input: T, min: T, max: T) -> T {
  337. debug_assert!(min <= max, "min must be less than or equal to max");
  338. if input < min {
  339. min
  340. } else if input > max {
  341. max
  342. } else {
  343. input
  344. }
  345. }
  346. /// A value bounded by a minimum value
  347. ///
  348. /// If input is less than min then this returns min.
  349. /// Otherwise this returns input.
  350. /// `clamp_min(std::f32::NAN, 1.0)` preserves `NAN` different from `f32::min(std::f32::NAN, 1.0)`.
  351. ///
  352. /// **Panics** in debug mode if `!(min == min)`. (This occurs if `min` is `NAN`.)
  353. #[inline]
  354. pub fn clamp_min<T: PartialOrd>(input: T, min: T) -> T {
  355. debug_assert!(min == min, "min must not be NAN");
  356. if input < min {
  357. min
  358. } else {
  359. input
  360. }
  361. }
  362. /// A value bounded by a maximum value
  363. ///
  364. /// If input is greater than max then this returns max.
  365. /// Otherwise this returns input.
  366. /// `clamp_max(std::f32::NAN, 1.0)` preserves `NAN` different from `f32::max(std::f32::NAN, 1.0)`.
  367. ///
  368. /// **Panics** in debug mode if `!(max == max)`. (This occurs if `max` is `NAN`.)
  369. #[inline]
  370. pub fn clamp_max<T: PartialOrd>(input: T, max: T) -> T {
  371. debug_assert!(max == max, "max must not be NAN");
  372. if input > max {
  373. max
  374. } else {
  375. input
  376. }
  377. }
  378. #[test]
  379. fn clamp_test() {
  380. // Int test
  381. assert_eq!(1, clamp(1, -1, 2));
  382. assert_eq!(-1, clamp(-2, -1, 2));
  383. assert_eq!(2, clamp(3, -1, 2));
  384. assert_eq!(1, clamp_min(1, -1));
  385. assert_eq!(-1, clamp_min(-2, -1));
  386. assert_eq!(-1, clamp_max(1, -1));
  387. assert_eq!(-2, clamp_max(-2, -1));
  388. // Float test
  389. assert_eq!(1.0, clamp(1.0, -1.0, 2.0));
  390. assert_eq!(-1.0, clamp(-2.0, -1.0, 2.0));
  391. assert_eq!(2.0, clamp(3.0, -1.0, 2.0));
  392. assert_eq!(1.0, clamp_min(1.0, -1.0));
  393. assert_eq!(-1.0, clamp_min(-2.0, -1.0));
  394. assert_eq!(-1.0, clamp_max(1.0, -1.0));
  395. assert_eq!(-2.0, clamp_max(-2.0, -1.0));
  396. assert!(clamp(::core::f32::NAN, -1.0, 1.0).is_nan());
  397. assert!(clamp_min(::core::f32::NAN, 1.0).is_nan());
  398. assert!(clamp_max(::core::f32::NAN, 1.0).is_nan());
  399. }
  400. #[test]
  401. #[should_panic]
  402. #[cfg(debug_assertions)]
  403. fn clamp_nan_min() {
  404. clamp(0., ::core::f32::NAN, 1.);
  405. }
  406. #[test]
  407. #[should_panic]
  408. #[cfg(debug_assertions)]
  409. fn clamp_nan_max() {
  410. clamp(0., -1., ::core::f32::NAN);
  411. }
  412. #[test]
  413. #[should_panic]
  414. #[cfg(debug_assertions)]
  415. fn clamp_nan_min_max() {
  416. clamp(0., ::core::f32::NAN, ::core::f32::NAN);
  417. }
  418. #[test]
  419. #[should_panic]
  420. #[cfg(debug_assertions)]
  421. fn clamp_min_nan_min() {
  422. clamp_min(0., ::core::f32::NAN);
  423. }
  424. #[test]
  425. #[should_panic]
  426. #[cfg(debug_assertions)]
  427. fn clamp_max_nan_max() {
  428. clamp_max(0., ::core::f32::NAN);
  429. }
  430. #[test]
  431. fn from_str_radix_unwrap() {
  432. // The Result error must impl Debug to allow unwrap()
  433. let i: i32 = Num::from_str_radix("0", 10).unwrap();
  434. assert_eq!(i, 0);
  435. let f: f32 = Num::from_str_radix("0.0", 10).unwrap();
  436. assert_eq!(f, 0.0);
  437. }
  438. #[test]
  439. fn from_str_radix_multi_byte_fail() {
  440. // Ensure parsing doesn't panic, even on invalid sign characters
  441. assert!(f32::from_str_radix("™0.2", 10).is_err());
  442. // Even when parsing the exponent sign
  443. assert!(f32::from_str_radix("0.2E™1", 10).is_err());
  444. }
  445. #[test]
  446. fn wrapping_is_num() {
  447. fn require_num<T: Num>(_: &T) {}
  448. require_num(&Wrapping(42_u32));
  449. require_num(&Wrapping(-42));
  450. }
  451. #[test]
  452. fn wrapping_from_str_radix() {
  453. macro_rules! test_wrapping_from_str_radix {
  454. ($($t:ty)+) => {
  455. $(
  456. for &(s, r) in &[("42", 10), ("42", 2), ("-13.0", 10), ("foo", 10)] {
  457. let w = Wrapping::<$t>::from_str_radix(s, r).map(|w| w.0);
  458. assert_eq!(w, <$t as Num>::from_str_radix(s, r));
  459. }
  460. )+
  461. };
  462. }
  463. test_wrapping_from_str_radix!(usize u8 u16 u32 u64 isize i8 i16 i32 i64);
  464. }
  465. #[test]
  466. fn check_num_ops() {
  467. fn compute<T: Num + Copy>(x: T, y: T) -> T {
  468. x * y / y % y + y - y
  469. }
  470. assert_eq!(compute(1, 2), 1)
  471. }
  472. #[test]
  473. fn check_numref_ops() {
  474. fn compute<T: NumRef>(x: T, y: &T) -> T {
  475. x * y / y % y + y - y
  476. }
  477. assert_eq!(compute(1, &2), 1)
  478. }
  479. #[test]
  480. fn check_refnum_ops() {
  481. fn compute<T: Copy>(x: &T, y: T) -> T
  482. where
  483. for<'a> &'a T: RefNum<T>,
  484. {
  485. &(&(&(&(x * y) / y) % y) + y) - y
  486. }
  487. assert_eq!(compute(&1, 2), 1)
  488. }
  489. #[test]
  490. fn check_refref_ops() {
  491. fn compute<T>(x: &T, y: &T) -> T
  492. where
  493. for<'a> &'a T: RefNum<T>,
  494. {
  495. &(&(&(&(x * y) / y) % y) + y) - y
  496. }
  497. assert_eq!(compute(&1, &2), 1)
  498. }
  499. #[test]
  500. fn check_numassign_ops() {
  501. fn compute<T: NumAssign + Copy>(mut x: T, y: T) -> T {
  502. x *= y;
  503. x /= y;
  504. x %= y;
  505. x += y;
  506. x -= y;
  507. x
  508. }
  509. assert_eq!(compute(1, 2), 1)
  510. }
  511. // TODO test `NumAssignRef`, but even the standard numeric types don't
  512. // implement this yet. (see rust pr41336)