lib.rs 16 KB

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