lib.rs 16 KB

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