lib.rs 16 KB

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