traits.rs 69 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450
  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. use std::ops::{Add, Sub, Mul, Div, Rem, Neg};
  12. use std::ops::{Not, BitAnd, BitOr, BitXor, Shl, Shr};
  13. use std::{usize, u8, u16, u32, u64};
  14. use std::{isize, i8, i16, i32, i64};
  15. use std::{f32, f64};
  16. use std::mem::{self, size_of};
  17. use std::num::FpCategory;
  18. /// The base trait for numeric types
  19. pub trait Num: PartialEq + Zero + One
  20. + Add<Output = Self> + Sub<Output = Self>
  21. + Mul<Output = Self> + Div<Output = Self> + Rem<Output = Self>
  22. {
  23. /// Parse error for `from_str_radix`
  24. type FromStrRadixErr;
  25. /// Convert from a string and radix <= 36.
  26. fn from_str_radix(str: &str, radix: u32) -> Result<Self, Self::FromStrRadixErr>;
  27. }
  28. macro_rules! int_trait_impl {
  29. ($name:ident for $($t:ty)*) => ($(
  30. impl $name for $t {
  31. type FromStrRadixErr = ::std::num::ParseIntError;
  32. fn from_str_radix(s: &str, radix: u32)
  33. -> Result<Self, ::std::num::ParseIntError>
  34. {
  35. <$t>::from_str_radix(s, radix)
  36. }
  37. }
  38. )*)
  39. }
  40. // FIXME: Temporary replacements for unstable ::std::num::ParseFloatError and
  41. // ::std::num::FloatErrorKind. These can be removed once the std float implementation of
  42. // from_str_radix stabilises.
  43. pub enum FloatErrorKind { Empty, Invalid }
  44. pub struct ParseFloatError { pub kind: FloatErrorKind }
  45. // FIXME: This should be removed and replaced with the std implementation of from_str_radix once
  46. // it is stabilised.
  47. macro_rules! float_trait_impl {
  48. ($name:ident for $($t:ty)*) => ($(
  49. impl $name for $t {
  50. type FromStrRadixErr = ParseFloatError;
  51. fn from_str_radix(src: &str, radix: u32)
  52. -> Result<Self, ParseFloatError>
  53. {
  54. use self::FloatErrorKind::*;
  55. use self::ParseFloatError as PFE;
  56. // Special values
  57. match src {
  58. "inf" => return Ok(Float::infinity()),
  59. "-inf" => return Ok(Float::neg_infinity()),
  60. "NaN" => return Ok(Float::nan()),
  61. _ => {},
  62. }
  63. fn slice_shift_char(src: &str) -> Option<(char, &str)> {
  64. src.chars().nth(0).map(|ch| (ch, &src[1..]))
  65. }
  66. let (is_positive, src) = match slice_shift_char(src) {
  67. None => return Err(PFE { kind: Empty }),
  68. Some(('-', "")) => return Err(PFE { kind: Empty }),
  69. Some(('-', src)) => (false, src),
  70. Some((_, _)) => (true, src),
  71. };
  72. // The significand to accumulate
  73. let mut sig = if is_positive { 0.0 } else { -0.0 };
  74. // Necessary to detect overflow
  75. let mut prev_sig = sig;
  76. let mut cs = src.chars().enumerate();
  77. // Exponent prefix and exponent index offset
  78. let mut exp_info = None::<(char, usize)>;
  79. // Parse the integer part of the significand
  80. for (i, c) in cs.by_ref() {
  81. match c.to_digit(radix) {
  82. Some(digit) => {
  83. // shift significand one digit left
  84. sig = sig * (radix as $t);
  85. // add/subtract current digit depending on sign
  86. if is_positive {
  87. sig = sig + ((digit as isize) as $t);
  88. } else {
  89. sig = sig - ((digit as isize) as $t);
  90. }
  91. // Detect overflow by comparing to last value, except
  92. // if we've not seen any non-zero digits.
  93. if prev_sig != 0.0 {
  94. if is_positive && sig <= prev_sig
  95. { return Ok(Float::infinity()); }
  96. if !is_positive && sig >= prev_sig
  97. { return Ok(Float::neg_infinity()); }
  98. // Detect overflow by reversing the shift-and-add process
  99. if is_positive && (prev_sig != (sig - digit as $t) / radix as $t)
  100. { return Ok(Float::infinity()); }
  101. if !is_positive && (prev_sig != (sig + digit as $t) / radix as $t)
  102. { return Ok(Float::neg_infinity()); }
  103. }
  104. prev_sig = sig;
  105. },
  106. None => match c {
  107. 'e' | 'E' | 'p' | 'P' => {
  108. exp_info = Some((c, i + 1));
  109. break; // start of exponent
  110. },
  111. '.' => {
  112. break; // start of fractional part
  113. },
  114. _ => {
  115. return Err(PFE { kind: Invalid });
  116. },
  117. },
  118. }
  119. }
  120. // If we are not yet at the exponent parse the fractional
  121. // part of the significand
  122. if exp_info.is_none() {
  123. let mut power = 1.0;
  124. for (i, c) in cs.by_ref() {
  125. match c.to_digit(radix) {
  126. Some(digit) => {
  127. // Decrease power one order of magnitude
  128. power = power / (radix as $t);
  129. // add/subtract current digit depending on sign
  130. sig = if is_positive {
  131. sig + (digit as $t) * power
  132. } else {
  133. sig - (digit as $t) * power
  134. };
  135. // Detect overflow by comparing to last value
  136. if is_positive && sig < prev_sig
  137. { return Ok(Float::infinity()); }
  138. if !is_positive && sig > prev_sig
  139. { return Ok(Float::neg_infinity()); }
  140. prev_sig = sig;
  141. },
  142. None => match c {
  143. 'e' | 'E' | 'p' | 'P' => {
  144. exp_info = Some((c, i + 1));
  145. break; // start of exponent
  146. },
  147. _ => {
  148. return Err(PFE { kind: Invalid });
  149. },
  150. },
  151. }
  152. }
  153. }
  154. // Parse and calculate the exponent
  155. let exp = match exp_info {
  156. Some((c, offset)) => {
  157. let base = match c {
  158. 'E' | 'e' if radix == 10 => 10.0,
  159. 'P' | 'p' if radix == 16 => 2.0,
  160. _ => return Err(PFE { kind: Invalid }),
  161. };
  162. // Parse the exponent as decimal integer
  163. let src = &src[offset..];
  164. let (is_positive, exp) = match slice_shift_char(src) {
  165. Some(('-', src)) => (false, src.parse::<usize>()),
  166. Some(('+', src)) => (true, src.parse::<usize>()),
  167. Some((_, _)) => (true, src.parse::<usize>()),
  168. None => return Err(PFE { kind: Invalid }),
  169. };
  170. match (is_positive, exp) {
  171. (true, Ok(exp)) => base.powi(exp as i32),
  172. (false, Ok(exp)) => 1.0 / base.powi(exp as i32),
  173. (_, Err(_)) => return Err(PFE { kind: Invalid }),
  174. }
  175. },
  176. None => 1.0, // no exponent
  177. };
  178. Ok(sig * exp)
  179. }
  180. }
  181. )*)
  182. }
  183. int_trait_impl!(Num for usize u8 u16 u32 u64 isize i8 i16 i32 i64);
  184. float_trait_impl!(Num for f32 f64);
  185. /// Defines an additive identity element for `Self`.
  186. ///
  187. /// # Deriving
  188. ///
  189. /// This trait can be automatically be derived using `#[deriving(Zero)]`
  190. /// attribute. If you choose to use this, make sure that the laws outlined in
  191. /// the documentation for `Zero::zero` still hold.
  192. pub trait Zero: Sized + Add<Self, Output = Self> {
  193. /// Returns the additive identity element of `Self`, `0`.
  194. ///
  195. /// # Laws
  196. ///
  197. /// ```{.text}
  198. /// a + 0 = a ∀ a ∈ Self
  199. /// 0 + a = a ∀ a ∈ Self
  200. /// ```
  201. ///
  202. /// # Purity
  203. ///
  204. /// This function should return the same result at all times regardless of
  205. /// external mutable state, for example values stored in TLS or in
  206. /// `static mut`s.
  207. // FIXME (#5527): This should be an associated constant
  208. fn zero() -> Self;
  209. /// Returns `true` if `self` is equal to the additive identity.
  210. #[inline]
  211. fn is_zero(&self) -> bool;
  212. }
  213. macro_rules! zero_impl {
  214. ($t:ty, $v:expr) => {
  215. impl Zero for $t {
  216. #[inline]
  217. fn zero() -> $t { $v }
  218. #[inline]
  219. fn is_zero(&self) -> bool { *self == $v }
  220. }
  221. }
  222. }
  223. zero_impl!(usize, 0usize);
  224. zero_impl!(u8, 0u8);
  225. zero_impl!(u16, 0u16);
  226. zero_impl!(u32, 0u32);
  227. zero_impl!(u64, 0u64);
  228. zero_impl!(isize, 0isize);
  229. zero_impl!(i8, 0i8);
  230. zero_impl!(i16, 0i16);
  231. zero_impl!(i32, 0i32);
  232. zero_impl!(i64, 0i64);
  233. zero_impl!(f32, 0.0f32);
  234. zero_impl!(f64, 0.0f64);
  235. /// Defines a multiplicative identity element for `Self`.
  236. pub trait One: Sized + Mul<Self, Output = Self> {
  237. /// Returns the multiplicative identity element of `Self`, `1`.
  238. ///
  239. /// # Laws
  240. ///
  241. /// ```{.text}
  242. /// a * 1 = a ∀ a ∈ Self
  243. /// 1 * a = a ∀ a ∈ Self
  244. /// ```
  245. ///
  246. /// # Purity
  247. ///
  248. /// This function should return the same result at all times regardless of
  249. /// external mutable state, for example values stored in TLS or in
  250. /// `static mut`s.
  251. // FIXME (#5527): This should be an associated constant
  252. fn one() -> Self;
  253. }
  254. macro_rules! one_impl {
  255. ($t:ty, $v:expr) => {
  256. impl One for $t {
  257. #[inline]
  258. fn one() -> $t { $v }
  259. }
  260. }
  261. }
  262. one_impl!(usize, 1usize);
  263. one_impl!(u8, 1u8);
  264. one_impl!(u16, 1u16);
  265. one_impl!(u32, 1u32);
  266. one_impl!(u64, 1u64);
  267. one_impl!(isize, 1isize);
  268. one_impl!(i8, 1i8);
  269. one_impl!(i16, 1i16);
  270. one_impl!(i32, 1i32);
  271. one_impl!(i64, 1i64);
  272. one_impl!(f32, 1.0f32);
  273. one_impl!(f64, 1.0f64);
  274. /// Useful functions for signed numbers (i.e. numbers that can be negative).
  275. pub trait Signed: Sized + Num + Neg<Output = Self> {
  276. /// Computes the absolute value.
  277. ///
  278. /// For `f32` and `f64`, `NaN` will be returned if the number is `NaN`.
  279. ///
  280. /// For signed integers, `::MIN` will be returned if the number is `::MIN`.
  281. fn abs(&self) -> Self;
  282. /// The positive difference of two numbers.
  283. ///
  284. /// Returns `zero` if the number is less than or equal to `other`, otherwise the difference
  285. /// between `self` and `other` is returned.
  286. fn abs_sub(&self, other: &Self) -> Self;
  287. /// Returns the sign of the number.
  288. ///
  289. /// For `f32` and `f64`:
  290. ///
  291. /// * `1.0` if the number is positive, `+0.0` or `INFINITY`
  292. /// * `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
  293. /// * `NaN` if the number is `NaN`
  294. ///
  295. /// For signed integers:
  296. ///
  297. /// * `0` if the number is zero
  298. /// * `1` if the number is positive
  299. /// * `-1` if the number is negative
  300. fn signum(&self) -> Self;
  301. /// Returns true if the number is positive and false if the number is zero or negative.
  302. fn is_positive(&self) -> bool;
  303. /// Returns true if the number is negative and false if the number is zero or positive.
  304. fn is_negative(&self) -> bool;
  305. }
  306. macro_rules! signed_impl {
  307. ($($t:ty)*) => ($(
  308. impl Signed for $t {
  309. #[inline]
  310. fn abs(&self) -> $t {
  311. if self.is_negative() { -*self } else { *self }
  312. }
  313. #[inline]
  314. fn abs_sub(&self, other: &$t) -> $t {
  315. if *self <= *other { 0 } else { *self - *other }
  316. }
  317. #[inline]
  318. fn signum(&self) -> $t {
  319. match *self {
  320. n if n > 0 => 1,
  321. 0 => 0,
  322. _ => -1,
  323. }
  324. }
  325. #[inline]
  326. fn is_positive(&self) -> bool { *self > 0 }
  327. #[inline]
  328. fn is_negative(&self) -> bool { *self < 0 }
  329. }
  330. )*)
  331. }
  332. signed_impl!(isize i8 i16 i32 i64);
  333. macro_rules! signed_float_impl {
  334. ($t:ty, $nan:expr, $inf:expr, $neg_inf:expr) => {
  335. impl Signed for $t {
  336. /// Computes the absolute value. Returns `NAN` if the number is `NAN`.
  337. #[inline]
  338. fn abs(&self) -> $t {
  339. <$t>::abs(*self)
  340. }
  341. /// The positive difference of two numbers. Returns `0.0` if the number is
  342. /// less than or equal to `other`, otherwise the difference between`self`
  343. /// and `other` is returned.
  344. #[inline]
  345. fn abs_sub(&self, other: &$t) -> $t {
  346. <$t>::abs_sub(*self, *other)
  347. }
  348. /// # Returns
  349. ///
  350. /// - `1.0` if the number is positive, `+0.0` or `INFINITY`
  351. /// - `-1.0` if the number is negative, `-0.0` or `NEG_INFINITY`
  352. /// - `NAN` if the number is NaN
  353. #[inline]
  354. fn signum(&self) -> $t {
  355. <$t>::signum(*self)
  356. }
  357. /// Returns `true` if the number is positive, including `+0.0` and `INFINITY`
  358. #[inline]
  359. fn is_positive(&self) -> bool { *self > 0.0 || (1.0 / *self) == $inf }
  360. /// Returns `true` if the number is negative, including `-0.0` and `NEG_INFINITY`
  361. #[inline]
  362. fn is_negative(&self) -> bool { *self < 0.0 || (1.0 / *self) == $neg_inf }
  363. }
  364. }
  365. }
  366. signed_float_impl!(f32, f32::NAN, f32::INFINITY, f32::NEG_INFINITY);
  367. signed_float_impl!(f64, f64::NAN, f64::INFINITY, f64::NEG_INFINITY);
  368. /// A trait for values which cannot be negative
  369. pub trait Unsigned: Num {}
  370. macro_rules! empty_trait_impl {
  371. ($name:ident for $($t:ty)*) => ($(
  372. impl $name for $t {}
  373. )*)
  374. }
  375. empty_trait_impl!(Unsigned for usize u8 u16 u32 u64);
  376. /// Numbers which have upper and lower bounds
  377. pub trait Bounded {
  378. // FIXME (#5527): These should be associated constants
  379. /// returns the smallest finite number this type can represent
  380. fn min_value() -> Self;
  381. /// returns the largest finite number this type can represent
  382. fn max_value() -> Self;
  383. }
  384. macro_rules! bounded_impl {
  385. ($t:ty, $min:expr, $max:expr) => {
  386. impl Bounded for $t {
  387. #[inline]
  388. fn min_value() -> $t { $min }
  389. #[inline]
  390. fn max_value() -> $t { $max }
  391. }
  392. }
  393. }
  394. bounded_impl!(usize, usize::MIN, usize::MAX);
  395. bounded_impl!(u8, u8::MIN, u8::MAX);
  396. bounded_impl!(u16, u16::MIN, u16::MAX);
  397. bounded_impl!(u32, u32::MIN, u32::MAX);
  398. bounded_impl!(u64, u64::MIN, u64::MAX);
  399. bounded_impl!(isize, isize::MIN, isize::MAX);
  400. bounded_impl!(i8, i8::MIN, i8::MAX);
  401. bounded_impl!(i16, i16::MIN, i16::MAX);
  402. bounded_impl!(i32, i32::MIN, i32::MAX);
  403. bounded_impl!(i64, i64::MIN, i64::MAX);
  404. bounded_impl!(f32, f32::MIN, f32::MAX);
  405. bounded_impl!(f64, f64::MIN, f64::MAX);
  406. macro_rules! for_each_tuple_ {
  407. ( $m:ident !! ) => (
  408. $m! { }
  409. );
  410. ( $m:ident !! $h:ident, $($t:ident,)* ) => (
  411. $m! { $h $($t)* }
  412. for_each_tuple_! { $m !! $($t,)* }
  413. );
  414. }
  415. macro_rules! for_each_tuple {
  416. ( $m:ident ) => (
  417. for_each_tuple_! { $m !! A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, }
  418. );
  419. }
  420. macro_rules! bounded_tuple {
  421. ( $($name:ident)* ) => (
  422. impl<$($name: Bounded,)*> Bounded for ($($name,)*) {
  423. fn min_value() -> Self {
  424. ($($name::min_value(),)*)
  425. }
  426. fn max_value() -> Self {
  427. ($($name::max_value(),)*)
  428. }
  429. }
  430. );
  431. }
  432. for_each_tuple!(bounded_tuple);
  433. /// Saturating math operations
  434. pub trait Saturating {
  435. /// Saturating addition operator.
  436. /// Returns a+b, saturating at the numeric bounds instead of overflowing.
  437. fn saturating_add(self, v: Self) -> Self;
  438. /// Saturating subtraction operator.
  439. /// Returns a-b, saturating at the numeric bounds instead of overflowing.
  440. fn saturating_sub(self, v: Self) -> Self;
  441. }
  442. impl<T: CheckedAdd + CheckedSub + Zero + PartialOrd + Bounded> Saturating for T {
  443. #[inline]
  444. fn saturating_add(self, v: T) -> T {
  445. match self.checked_add(&v) {
  446. Some(x) => x,
  447. None => if v >= Zero::zero() {
  448. Bounded::max_value()
  449. } else {
  450. Bounded::min_value()
  451. }
  452. }
  453. }
  454. #[inline]
  455. fn saturating_sub(self, v: T) -> T {
  456. match self.checked_sub(&v) {
  457. Some(x) => x,
  458. None => if v >= Zero::zero() {
  459. Bounded::min_value()
  460. } else {
  461. Bounded::max_value()
  462. }
  463. }
  464. }
  465. }
  466. /// Performs addition that returns `None` instead of wrapping around on
  467. /// overflow.
  468. pub trait CheckedAdd: Sized + Add<Self, Output = Self> {
  469. /// Adds two numbers, checking for overflow. If overflow happens, `None` is
  470. /// returned.
  471. fn checked_add(&self, v: &Self) -> Option<Self>;
  472. }
  473. macro_rules! checked_impl {
  474. ($trait_name:ident, $method:ident, $t:ty) => {
  475. impl $trait_name for $t {
  476. #[inline]
  477. fn $method(&self, v: &$t) -> Option<$t> {
  478. <$t>::$method(*self, *v)
  479. }
  480. }
  481. }
  482. }
  483. checked_impl!(CheckedAdd, checked_add, u8);
  484. checked_impl!(CheckedAdd, checked_add, u16);
  485. checked_impl!(CheckedAdd, checked_add, u32);
  486. checked_impl!(CheckedAdd, checked_add, u64);
  487. checked_impl!(CheckedAdd, checked_add, usize);
  488. checked_impl!(CheckedAdd, checked_add, i8);
  489. checked_impl!(CheckedAdd, checked_add, i16);
  490. checked_impl!(CheckedAdd, checked_add, i32);
  491. checked_impl!(CheckedAdd, checked_add, i64);
  492. checked_impl!(CheckedAdd, checked_add, isize);
  493. /// Performs subtraction that returns `None` instead of wrapping around on underflow.
  494. pub trait CheckedSub: Sized + Sub<Self, Output = Self> {
  495. /// Subtracts two numbers, checking for underflow. If underflow happens,
  496. /// `None` is returned.
  497. fn checked_sub(&self, v: &Self) -> Option<Self>;
  498. }
  499. checked_impl!(CheckedSub, checked_sub, u8);
  500. checked_impl!(CheckedSub, checked_sub, u16);
  501. checked_impl!(CheckedSub, checked_sub, u32);
  502. checked_impl!(CheckedSub, checked_sub, u64);
  503. checked_impl!(CheckedSub, checked_sub, usize);
  504. checked_impl!(CheckedSub, checked_sub, i8);
  505. checked_impl!(CheckedSub, checked_sub, i16);
  506. checked_impl!(CheckedSub, checked_sub, i32);
  507. checked_impl!(CheckedSub, checked_sub, i64);
  508. checked_impl!(CheckedSub, checked_sub, isize);
  509. /// Performs multiplication that returns `None` instead of wrapping around on underflow or
  510. /// overflow.
  511. pub trait CheckedMul: Sized + Mul<Self, Output = Self> {
  512. /// Multiplies two numbers, checking for underflow or overflow. If underflow
  513. /// or overflow happens, `None` is returned.
  514. fn checked_mul(&self, v: &Self) -> Option<Self>;
  515. }
  516. checked_impl!(CheckedMul, checked_mul, u8);
  517. checked_impl!(CheckedMul, checked_mul, u16);
  518. checked_impl!(CheckedMul, checked_mul, u32);
  519. checked_impl!(CheckedMul, checked_mul, u64);
  520. checked_impl!(CheckedMul, checked_mul, usize);
  521. checked_impl!(CheckedMul, checked_mul, i8);
  522. checked_impl!(CheckedMul, checked_mul, i16);
  523. checked_impl!(CheckedMul, checked_mul, i32);
  524. checked_impl!(CheckedMul, checked_mul, i64);
  525. checked_impl!(CheckedMul, checked_mul, isize);
  526. /// Performs division that returns `None` instead of panicking on division by zero and instead of
  527. /// wrapping around on underflow and overflow.
  528. pub trait CheckedDiv: Sized + Div<Self, Output = Self> {
  529. /// Divides two numbers, checking for underflow, overflow and division by
  530. /// zero. If any of that happens, `None` is returned.
  531. fn checked_div(&self, v: &Self) -> Option<Self>;
  532. }
  533. macro_rules! checkeddiv_int_impl {
  534. ($t:ty, $min:expr) => {
  535. impl CheckedDiv for $t {
  536. #[inline]
  537. fn checked_div(&self, v: &$t) -> Option<$t> {
  538. if *v == 0 || (*self == $min && *v == -1) {
  539. None
  540. } else {
  541. Some(*self / *v)
  542. }
  543. }
  544. }
  545. }
  546. }
  547. checkeddiv_int_impl!(isize, isize::MIN);
  548. checkeddiv_int_impl!(i8, i8::MIN);
  549. checkeddiv_int_impl!(i16, i16::MIN);
  550. checkeddiv_int_impl!(i32, i32::MIN);
  551. checkeddiv_int_impl!(i64, i64::MIN);
  552. macro_rules! checkeddiv_uint_impl {
  553. ($($t:ty)*) => ($(
  554. impl CheckedDiv for $t {
  555. #[inline]
  556. fn checked_div(&self, v: &$t) -> Option<$t> {
  557. if *v == 0 {
  558. None
  559. } else {
  560. Some(*self / *v)
  561. }
  562. }
  563. }
  564. )*)
  565. }
  566. checkeddiv_uint_impl!(usize u8 u16 u32 u64);
  567. pub trait PrimInt
  568. : Sized
  569. + Copy
  570. + Num + NumCast
  571. + Bounded
  572. + PartialOrd + Ord + Eq
  573. + Not<Output=Self>
  574. + BitAnd<Output=Self>
  575. + BitOr<Output=Self>
  576. + BitXor<Output=Self>
  577. + Shl<usize, Output=Self>
  578. + Shr<usize, Output=Self>
  579. + CheckedAdd<Output=Self>
  580. + CheckedSub<Output=Self>
  581. + CheckedMul<Output=Self>
  582. + CheckedDiv<Output=Self>
  583. + Saturating
  584. {
  585. /// Returns the number of ones in the binary representation of `self`.
  586. ///
  587. /// # Examples
  588. ///
  589. /// ```
  590. /// use num::traits::PrimInt;
  591. ///
  592. /// let n = 0b01001100u8;
  593. ///
  594. /// assert_eq!(n.count_ones(), 3);
  595. /// ```
  596. fn count_ones(self) -> u32;
  597. /// Returns the number of zeros in the binary representation of `self`.
  598. ///
  599. /// # Examples
  600. ///
  601. /// ```
  602. /// use num::traits::PrimInt;
  603. ///
  604. /// let n = 0b01001100u8;
  605. ///
  606. /// assert_eq!(n.count_zeros(), 5);
  607. /// ```
  608. fn count_zeros(self) -> u32;
  609. /// Returns the number of leading zeros in the binary representation
  610. /// of `self`.
  611. ///
  612. /// # Examples
  613. ///
  614. /// ```
  615. /// use num::traits::PrimInt;
  616. ///
  617. /// let n = 0b0101000u16;
  618. ///
  619. /// assert_eq!(n.leading_zeros(), 10);
  620. /// ```
  621. fn leading_zeros(self) -> u32;
  622. /// Returns the number of trailing zeros in the binary representation
  623. /// of `self`.
  624. ///
  625. /// # Examples
  626. ///
  627. /// ```
  628. /// use num::traits::PrimInt;
  629. ///
  630. /// let n = 0b0101000u16;
  631. ///
  632. /// assert_eq!(n.trailing_zeros(), 3);
  633. /// ```
  634. fn trailing_zeros(self) -> u32;
  635. /// Shifts the bits to the left by a specified amount amount, `n`, wrapping
  636. /// the truncated bits to the end of the resulting integer.
  637. ///
  638. /// # Examples
  639. ///
  640. /// ```
  641. /// use num::traits::PrimInt;
  642. ///
  643. /// let n = 0x0123456789ABCDEFu64;
  644. /// let m = 0x3456789ABCDEF012u64;
  645. ///
  646. /// assert_eq!(n.rotate_left(12), m);
  647. /// ```
  648. fn rotate_left(self, n: u32) -> Self;
  649. /// Shifts the bits to the right by a specified amount amount, `n`, wrapping
  650. /// the truncated bits to the beginning of the resulting integer.
  651. ///
  652. /// # Examples
  653. ///
  654. /// ```
  655. /// use num::traits::PrimInt;
  656. ///
  657. /// let n = 0x0123456789ABCDEFu64;
  658. /// let m = 0xDEF0123456789ABCu64;
  659. ///
  660. /// assert_eq!(n.rotate_right(12), m);
  661. /// ```
  662. fn rotate_right(self, n: u32) -> Self;
  663. /// Reverses the byte order of the integer.
  664. ///
  665. /// # Examples
  666. ///
  667. /// ```
  668. /// use num::traits::PrimInt;
  669. ///
  670. /// let n = 0x0123456789ABCDEFu64;
  671. /// let m = 0xEFCDAB8967452301u64;
  672. ///
  673. /// assert_eq!(n.swap_bytes(), m);
  674. /// ```
  675. fn swap_bytes(self) -> Self;
  676. /// Convert an integer from big endian to the target's endianness.
  677. ///
  678. /// On big endian this is a no-op. On little endian the bytes are swapped.
  679. ///
  680. /// # Examples
  681. ///
  682. /// ```
  683. /// use num::traits::PrimInt;
  684. ///
  685. /// let n = 0x0123456789ABCDEFu64;
  686. ///
  687. /// if cfg!(target_endian = "big") {
  688. /// assert_eq!(u64::from_be(n), n)
  689. /// } else {
  690. /// assert_eq!(u64::from_be(n), n.swap_bytes())
  691. /// }
  692. /// ```
  693. fn from_be(x: Self) -> Self;
  694. /// Convert an integer from little endian to the target's endianness.
  695. ///
  696. /// On little endian this is a no-op. On big endian the bytes are swapped.
  697. ///
  698. /// # Examples
  699. ///
  700. /// ```
  701. /// use num::traits::PrimInt;
  702. ///
  703. /// let n = 0x0123456789ABCDEFu64;
  704. ///
  705. /// if cfg!(target_endian = "little") {
  706. /// assert_eq!(u64::from_le(n), n)
  707. /// } else {
  708. /// assert_eq!(u64::from_le(n), n.swap_bytes())
  709. /// }
  710. /// ```
  711. fn from_le(x: Self) -> Self;
  712. /// Convert `self` to big endian from the target's endianness.
  713. ///
  714. /// On big endian this is a no-op. On little endian the bytes are swapped.
  715. ///
  716. /// # Examples
  717. ///
  718. /// ```
  719. /// use num::traits::PrimInt;
  720. ///
  721. /// let n = 0x0123456789ABCDEFu64;
  722. ///
  723. /// if cfg!(target_endian = "big") {
  724. /// assert_eq!(n.to_be(), n)
  725. /// } else {
  726. /// assert_eq!(n.to_be(), n.swap_bytes())
  727. /// }
  728. /// ```
  729. fn to_be(self) -> Self;
  730. /// Convert `self` to little endian from the target's endianness.
  731. ///
  732. /// On little endian this is a no-op. On big endian the bytes are swapped.
  733. ///
  734. /// # Examples
  735. ///
  736. /// ```
  737. /// use num::traits::PrimInt;
  738. ///
  739. /// let n = 0x0123456789ABCDEFu64;
  740. ///
  741. /// if cfg!(target_endian = "little") {
  742. /// assert_eq!(n.to_le(), n)
  743. /// } else {
  744. /// assert_eq!(n.to_le(), n.swap_bytes())
  745. /// }
  746. /// ```
  747. fn to_le(self) -> Self;
  748. /// Raises self to the power of `exp`, using exponentiation by squaring.
  749. ///
  750. /// # Examples
  751. ///
  752. /// ```
  753. /// use num::traits::PrimInt;
  754. ///
  755. /// assert_eq!(2i32.pow(4), 16);
  756. /// ```
  757. fn pow(self, mut exp: u32) -> Self;
  758. }
  759. macro_rules! prim_int_impl {
  760. ($($T:ty)*) => ($(
  761. impl PrimInt for $T {
  762. fn count_ones(self) -> u32 {
  763. <$T>::count_ones(self)
  764. }
  765. fn count_zeros(self) -> u32 {
  766. <$T>::count_zeros(self)
  767. }
  768. fn leading_zeros(self) -> u32 {
  769. <$T>::leading_zeros(self)
  770. }
  771. fn trailing_zeros(self) -> u32 {
  772. <$T>::trailing_zeros(self)
  773. }
  774. fn rotate_left(self, n: u32) -> Self {
  775. <$T>::rotate_left(self, n)
  776. }
  777. fn rotate_right(self, n: u32) -> Self {
  778. <$T>::rotate_right(self, n)
  779. }
  780. fn swap_bytes(self) -> Self {
  781. <$T>::swap_bytes(self)
  782. }
  783. fn from_be(x: Self) -> Self {
  784. <$T>::from_be(x)
  785. }
  786. fn from_le(x: Self) -> Self {
  787. <$T>::from_le(x)
  788. }
  789. fn to_be(self) -> Self {
  790. <$T>::to_be(self)
  791. }
  792. fn to_le(self) -> Self {
  793. <$T>::to_le(self)
  794. }
  795. fn pow(self, exp: u32) -> Self {
  796. <$T>::pow(self, exp)
  797. }
  798. }
  799. )*)
  800. }
  801. prim_int_impl!(u8 u16 u32 u64 usize i8 i16 i32 i64 isize);
  802. /// A generic trait for converting a value to a number.
  803. pub trait ToPrimitive {
  804. /// Converts the value of `self` to an `isize`.
  805. #[inline]
  806. fn to_isize(&self) -> Option<isize> {
  807. self.to_i64().and_then(|x| x.to_isize())
  808. }
  809. /// Converts the value of `self` to an `i8`.
  810. #[inline]
  811. fn to_i8(&self) -> Option<i8> {
  812. self.to_i64().and_then(|x| x.to_i8())
  813. }
  814. /// Converts the value of `self` to an `i16`.
  815. #[inline]
  816. fn to_i16(&self) -> Option<i16> {
  817. self.to_i64().and_then(|x| x.to_i16())
  818. }
  819. /// Converts the value of `self` to an `i32`.
  820. #[inline]
  821. fn to_i32(&self) -> Option<i32> {
  822. self.to_i64().and_then(|x| x.to_i32())
  823. }
  824. /// Converts the value of `self` to an `i64`.
  825. fn to_i64(&self) -> Option<i64>;
  826. /// Converts the value of `self` to a `usize`.
  827. #[inline]
  828. fn to_usize(&self) -> Option<usize> {
  829. self.to_u64().and_then(|x| x.to_usize())
  830. }
  831. /// Converts the value of `self` to an `u8`.
  832. #[inline]
  833. fn to_u8(&self) -> Option<u8> {
  834. self.to_u64().and_then(|x| x.to_u8())
  835. }
  836. /// Converts the value of `self` to an `u16`.
  837. #[inline]
  838. fn to_u16(&self) -> Option<u16> {
  839. self.to_u64().and_then(|x| x.to_u16())
  840. }
  841. /// Converts the value of `self` to an `u32`.
  842. #[inline]
  843. fn to_u32(&self) -> Option<u32> {
  844. self.to_u64().and_then(|x| x.to_u32())
  845. }
  846. /// Converts the value of `self` to an `u64`.
  847. #[inline]
  848. fn to_u64(&self) -> Option<u64>;
  849. /// Converts the value of `self` to an `f32`.
  850. #[inline]
  851. fn to_f32(&self) -> Option<f32> {
  852. self.to_f64().and_then(|x| x.to_f32())
  853. }
  854. /// Converts the value of `self` to an `f64`.
  855. #[inline]
  856. fn to_f64(&self) -> Option<f64> {
  857. self.to_i64().and_then(|x| x.to_f64())
  858. }
  859. }
  860. macro_rules! impl_to_primitive_int_to_int {
  861. ($SrcT:ty, $DstT:ty, $slf:expr) => (
  862. {
  863. if size_of::<$SrcT>() <= size_of::<$DstT>() {
  864. Some($slf as $DstT)
  865. } else {
  866. let n = $slf as i64;
  867. let min_value: $DstT = Bounded::min_value();
  868. let max_value: $DstT = Bounded::max_value();
  869. if min_value as i64 <= n && n <= max_value as i64 {
  870. Some($slf as $DstT)
  871. } else {
  872. None
  873. }
  874. }
  875. }
  876. )
  877. }
  878. macro_rules! impl_to_primitive_int_to_uint {
  879. ($SrcT:ty, $DstT:ty, $slf:expr) => (
  880. {
  881. let zero: $SrcT = Zero::zero();
  882. let max_value: $DstT = Bounded::max_value();
  883. if zero <= $slf && $slf as u64 <= max_value as u64 {
  884. Some($slf as $DstT)
  885. } else {
  886. None
  887. }
  888. }
  889. )
  890. }
  891. macro_rules! impl_to_primitive_int {
  892. ($T:ty) => (
  893. impl ToPrimitive for $T {
  894. #[inline]
  895. fn to_isize(&self) -> Option<isize> { impl_to_primitive_int_to_int!($T, isize, *self) }
  896. #[inline]
  897. fn to_i8(&self) -> Option<i8> { impl_to_primitive_int_to_int!($T, i8, *self) }
  898. #[inline]
  899. fn to_i16(&self) -> Option<i16> { impl_to_primitive_int_to_int!($T, i16, *self) }
  900. #[inline]
  901. fn to_i32(&self) -> Option<i32> { impl_to_primitive_int_to_int!($T, i32, *self) }
  902. #[inline]
  903. fn to_i64(&self) -> Option<i64> { impl_to_primitive_int_to_int!($T, i64, *self) }
  904. #[inline]
  905. fn to_usize(&self) -> Option<usize> { impl_to_primitive_int_to_uint!($T, usize, *self) }
  906. #[inline]
  907. fn to_u8(&self) -> Option<u8> { impl_to_primitive_int_to_uint!($T, u8, *self) }
  908. #[inline]
  909. fn to_u16(&self) -> Option<u16> { impl_to_primitive_int_to_uint!($T, u16, *self) }
  910. #[inline]
  911. fn to_u32(&self) -> Option<u32> { impl_to_primitive_int_to_uint!($T, u32, *self) }
  912. #[inline]
  913. fn to_u64(&self) -> Option<u64> { impl_to_primitive_int_to_uint!($T, u64, *self) }
  914. #[inline]
  915. fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
  916. #[inline]
  917. fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
  918. }
  919. )
  920. }
  921. impl_to_primitive_int! { isize }
  922. impl_to_primitive_int! { i8 }
  923. impl_to_primitive_int! { i16 }
  924. impl_to_primitive_int! { i32 }
  925. impl_to_primitive_int! { i64 }
  926. macro_rules! impl_to_primitive_uint_to_int {
  927. ($DstT:ty, $slf:expr) => (
  928. {
  929. let max_value: $DstT = Bounded::max_value();
  930. if $slf as u64 <= max_value as u64 {
  931. Some($slf as $DstT)
  932. } else {
  933. None
  934. }
  935. }
  936. )
  937. }
  938. macro_rules! impl_to_primitive_uint_to_uint {
  939. ($SrcT:ty, $DstT:ty, $slf:expr) => (
  940. {
  941. if size_of::<$SrcT>() <= size_of::<$DstT>() {
  942. Some($slf as $DstT)
  943. } else {
  944. let zero: $SrcT = Zero::zero();
  945. let max_value: $DstT = Bounded::max_value();
  946. if zero <= $slf && $slf as u64 <= max_value as u64 {
  947. Some($slf as $DstT)
  948. } else {
  949. None
  950. }
  951. }
  952. }
  953. )
  954. }
  955. macro_rules! impl_to_primitive_uint {
  956. ($T:ty) => (
  957. impl ToPrimitive for $T {
  958. #[inline]
  959. fn to_isize(&self) -> Option<isize> { impl_to_primitive_uint_to_int!(isize, *self) }
  960. #[inline]
  961. fn to_i8(&self) -> Option<i8> { impl_to_primitive_uint_to_int!(i8, *self) }
  962. #[inline]
  963. fn to_i16(&self) -> Option<i16> { impl_to_primitive_uint_to_int!(i16, *self) }
  964. #[inline]
  965. fn to_i32(&self) -> Option<i32> { impl_to_primitive_uint_to_int!(i32, *self) }
  966. #[inline]
  967. fn to_i64(&self) -> Option<i64> { impl_to_primitive_uint_to_int!(i64, *self) }
  968. #[inline]
  969. fn to_usize(&self) -> Option<usize> {
  970. impl_to_primitive_uint_to_uint!($T, usize, *self)
  971. }
  972. #[inline]
  973. fn to_u8(&self) -> Option<u8> { impl_to_primitive_uint_to_uint!($T, u8, *self) }
  974. #[inline]
  975. fn to_u16(&self) -> Option<u16> { impl_to_primitive_uint_to_uint!($T, u16, *self) }
  976. #[inline]
  977. fn to_u32(&self) -> Option<u32> { impl_to_primitive_uint_to_uint!($T, u32, *self) }
  978. #[inline]
  979. fn to_u64(&self) -> Option<u64> { impl_to_primitive_uint_to_uint!($T, u64, *self) }
  980. #[inline]
  981. fn to_f32(&self) -> Option<f32> { Some(*self as f32) }
  982. #[inline]
  983. fn to_f64(&self) -> Option<f64> { Some(*self as f64) }
  984. }
  985. )
  986. }
  987. impl_to_primitive_uint! { usize }
  988. impl_to_primitive_uint! { u8 }
  989. impl_to_primitive_uint! { u16 }
  990. impl_to_primitive_uint! { u32 }
  991. impl_to_primitive_uint! { u64 }
  992. macro_rules! impl_to_primitive_float_to_float {
  993. ($SrcT:ident, $DstT:ident, $slf:expr) => (
  994. if size_of::<$SrcT>() <= size_of::<$DstT>() {
  995. Some($slf as $DstT)
  996. } else {
  997. let n = $slf as f64;
  998. let max_value: $SrcT = ::std::$SrcT::MAX;
  999. if -max_value as f64 <= n && n <= max_value as f64 {
  1000. Some($slf as $DstT)
  1001. } else {
  1002. None
  1003. }
  1004. }
  1005. )
  1006. }
  1007. macro_rules! impl_to_primitive_float {
  1008. ($T:ident) => (
  1009. impl ToPrimitive for $T {
  1010. #[inline]
  1011. fn to_isize(&self) -> Option<isize> { Some(*self as isize) }
  1012. #[inline]
  1013. fn to_i8(&self) -> Option<i8> { Some(*self as i8) }
  1014. #[inline]
  1015. fn to_i16(&self) -> Option<i16> { Some(*self as i16) }
  1016. #[inline]
  1017. fn to_i32(&self) -> Option<i32> { Some(*self as i32) }
  1018. #[inline]
  1019. fn to_i64(&self) -> Option<i64> { Some(*self as i64) }
  1020. #[inline]
  1021. fn to_usize(&self) -> Option<usize> { Some(*self as usize) }
  1022. #[inline]
  1023. fn to_u8(&self) -> Option<u8> { Some(*self as u8) }
  1024. #[inline]
  1025. fn to_u16(&self) -> Option<u16> { Some(*self as u16) }
  1026. #[inline]
  1027. fn to_u32(&self) -> Option<u32> { Some(*self as u32) }
  1028. #[inline]
  1029. fn to_u64(&self) -> Option<u64> { Some(*self as u64) }
  1030. #[inline]
  1031. fn to_f32(&self) -> Option<f32> { impl_to_primitive_float_to_float!($T, f32, *self) }
  1032. #[inline]
  1033. fn to_f64(&self) -> Option<f64> { impl_to_primitive_float_to_float!($T, f64, *self) }
  1034. }
  1035. )
  1036. }
  1037. impl_to_primitive_float! { f32 }
  1038. impl_to_primitive_float! { f64 }
  1039. /// A generic trait for converting a number to a value.
  1040. pub trait FromPrimitive: Sized {
  1041. /// Convert an `isize` to return an optional value of this type. If the
  1042. /// value cannot be represented by this value, the `None` is returned.
  1043. #[inline]
  1044. fn from_isize(n: isize) -> Option<Self> {
  1045. FromPrimitive::from_i64(n as i64)
  1046. }
  1047. /// Convert an `i8` to return an optional value of this type. If the
  1048. /// type cannot be represented by this value, the `None` is returned.
  1049. #[inline]
  1050. fn from_i8(n: i8) -> Option<Self> {
  1051. FromPrimitive::from_i64(n as i64)
  1052. }
  1053. /// Convert an `i16` to return an optional value of this type. If the
  1054. /// type cannot be represented by this value, the `None` is returned.
  1055. #[inline]
  1056. fn from_i16(n: i16) -> Option<Self> {
  1057. FromPrimitive::from_i64(n as i64)
  1058. }
  1059. /// Convert an `i32` to return an optional value of this type. If the
  1060. /// type cannot be represented by this value, the `None` is returned.
  1061. #[inline]
  1062. fn from_i32(n: i32) -> Option<Self> {
  1063. FromPrimitive::from_i64(n as i64)
  1064. }
  1065. /// Convert an `i64` to return an optional value of this type. If the
  1066. /// type cannot be represented by this value, the `None` is returned.
  1067. fn from_i64(n: i64) -> Option<Self>;
  1068. /// Convert a `usize` to return an optional value of this type. If the
  1069. /// type cannot be represented by this value, the `None` is returned.
  1070. #[inline]
  1071. fn from_usize(n: usize) -> Option<Self> {
  1072. FromPrimitive::from_u64(n as u64)
  1073. }
  1074. /// Convert an `u8` to return an optional value of this type. If the
  1075. /// type cannot be represented by this value, the `None` is returned.
  1076. #[inline]
  1077. fn from_u8(n: u8) -> Option<Self> {
  1078. FromPrimitive::from_u64(n as u64)
  1079. }
  1080. /// Convert an `u16` to return an optional value of this type. If the
  1081. /// type cannot be represented by this value, the `None` is returned.
  1082. #[inline]
  1083. fn from_u16(n: u16) -> Option<Self> {
  1084. FromPrimitive::from_u64(n as u64)
  1085. }
  1086. /// Convert an `u32` to return an optional value of this type. If the
  1087. /// type cannot be represented by this value, the `None` is returned.
  1088. #[inline]
  1089. fn from_u32(n: u32) -> Option<Self> {
  1090. FromPrimitive::from_u64(n as u64)
  1091. }
  1092. /// Convert an `u64` to return an optional value of this type. If the
  1093. /// type cannot be represented by this value, the `None` is returned.
  1094. fn from_u64(n: u64) -> Option<Self>;
  1095. /// Convert a `f32` to return an optional value of this type. If the
  1096. /// type cannot be represented by this value, the `None` is returned.
  1097. #[inline]
  1098. fn from_f32(n: f32) -> Option<Self> {
  1099. FromPrimitive::from_f64(n as f64)
  1100. }
  1101. /// Convert a `f64` to return an optional value of this type. If the
  1102. /// type cannot be represented by this value, the `None` is returned.
  1103. #[inline]
  1104. fn from_f64(n: f64) -> Option<Self> {
  1105. FromPrimitive::from_i64(n as i64)
  1106. }
  1107. }
  1108. macro_rules! impl_from_primitive {
  1109. ($T:ty, $to_ty:ident) => (
  1110. #[allow(deprecated)]
  1111. impl FromPrimitive for $T {
  1112. #[inline] fn from_i8(n: i8) -> Option<$T> { n.$to_ty() }
  1113. #[inline] fn from_i16(n: i16) -> Option<$T> { n.$to_ty() }
  1114. #[inline] fn from_i32(n: i32) -> Option<$T> { n.$to_ty() }
  1115. #[inline] fn from_i64(n: i64) -> Option<$T> { n.$to_ty() }
  1116. #[inline] fn from_u8(n: u8) -> Option<$T> { n.$to_ty() }
  1117. #[inline] fn from_u16(n: u16) -> Option<$T> { n.$to_ty() }
  1118. #[inline] fn from_u32(n: u32) -> Option<$T> { n.$to_ty() }
  1119. #[inline] fn from_u64(n: u64) -> Option<$T> { n.$to_ty() }
  1120. #[inline] fn from_f32(n: f32) -> Option<$T> { n.$to_ty() }
  1121. #[inline] fn from_f64(n: f64) -> Option<$T> { n.$to_ty() }
  1122. }
  1123. )
  1124. }
  1125. impl_from_primitive! { isize, to_isize }
  1126. impl_from_primitive! { i8, to_i8 }
  1127. impl_from_primitive! { i16, to_i16 }
  1128. impl_from_primitive! { i32, to_i32 }
  1129. impl_from_primitive! { i64, to_i64 }
  1130. impl_from_primitive! { usize, to_usize }
  1131. impl_from_primitive! { u8, to_u8 }
  1132. impl_from_primitive! { u16, to_u16 }
  1133. impl_from_primitive! { u32, to_u32 }
  1134. impl_from_primitive! { u64, to_u64 }
  1135. impl_from_primitive! { f32, to_f32 }
  1136. impl_from_primitive! { f64, to_f64 }
  1137. /// Cast from one machine scalar to another.
  1138. ///
  1139. /// # Examples
  1140. ///
  1141. /// ```
  1142. /// use num;
  1143. ///
  1144. /// let twenty: f32 = num::cast(0x14).unwrap();
  1145. /// assert_eq!(twenty, 20f32);
  1146. /// ```
  1147. ///
  1148. #[inline]
  1149. pub fn cast<T: NumCast,U: NumCast>(n: T) -> Option<U> {
  1150. NumCast::from(n)
  1151. }
  1152. /// An interface for casting between machine scalars.
  1153. pub trait NumCast: Sized + ToPrimitive {
  1154. /// Creates a number from another value that can be converted into
  1155. /// a primitive via the `ToPrimitive` trait.
  1156. fn from<T: ToPrimitive>(n: T) -> Option<Self>;
  1157. }
  1158. macro_rules! impl_num_cast {
  1159. ($T:ty, $conv:ident) => (
  1160. impl NumCast for $T {
  1161. #[inline]
  1162. #[allow(deprecated)]
  1163. fn from<N: ToPrimitive>(n: N) -> Option<$T> {
  1164. // `$conv` could be generated using `concat_idents!`, but that
  1165. // macro seems to be broken at the moment
  1166. n.$conv()
  1167. }
  1168. }
  1169. )
  1170. }
  1171. impl_num_cast! { u8, to_u8 }
  1172. impl_num_cast! { u16, to_u16 }
  1173. impl_num_cast! { u32, to_u32 }
  1174. impl_num_cast! { u64, to_u64 }
  1175. impl_num_cast! { usize, to_usize }
  1176. impl_num_cast! { i8, to_i8 }
  1177. impl_num_cast! { i16, to_i16 }
  1178. impl_num_cast! { i32, to_i32 }
  1179. impl_num_cast! { i64, to_i64 }
  1180. impl_num_cast! { isize, to_isize }
  1181. impl_num_cast! { f32, to_f32 }
  1182. impl_num_cast! { f64, to_f64 }
  1183. pub trait Float
  1184. : Num
  1185. + Copy
  1186. + NumCast
  1187. + PartialOrd
  1188. + Neg<Output = Self>
  1189. {
  1190. /// Returns the `NaN` value.
  1191. ///
  1192. /// ```
  1193. /// use num::traits::Float;
  1194. ///
  1195. /// let nan: f32 = Float::nan();
  1196. ///
  1197. /// assert!(nan.is_nan());
  1198. /// ```
  1199. fn nan() -> Self;
  1200. /// Returns the infinite value.
  1201. ///
  1202. /// ```
  1203. /// use num::traits::Float;
  1204. /// use std::f32;
  1205. ///
  1206. /// let infinity: f32 = Float::infinity();
  1207. ///
  1208. /// assert!(infinity.is_infinite());
  1209. /// assert!(!infinity.is_finite());
  1210. /// assert!(infinity > f32::MAX);
  1211. /// ```
  1212. fn infinity() -> Self;
  1213. /// Returns the negative infinite value.
  1214. ///
  1215. /// ```
  1216. /// use num::traits::Float;
  1217. /// use std::f32;
  1218. ///
  1219. /// let neg_infinity: f32 = Float::neg_infinity();
  1220. ///
  1221. /// assert!(neg_infinity.is_infinite());
  1222. /// assert!(!neg_infinity.is_finite());
  1223. /// assert!(neg_infinity < f32::MIN);
  1224. /// ```
  1225. fn neg_infinity() -> Self;
  1226. /// Returns `-0.0`.
  1227. ///
  1228. /// ```
  1229. /// use num::traits::{Zero, Float};
  1230. ///
  1231. /// let inf: f32 = Float::infinity();
  1232. /// let zero: f32 = Zero::zero();
  1233. /// let neg_zero: f32 = Float::neg_zero();
  1234. ///
  1235. /// assert_eq!(zero, neg_zero);
  1236. /// assert_eq!(7.0f32/inf, zero);
  1237. /// assert_eq!(zero * 10.0, zero);
  1238. /// ```
  1239. fn neg_zero() -> Self;
  1240. /// Returns the smallest finite value that this type can represent.
  1241. ///
  1242. /// ```
  1243. /// use num::traits::Float;
  1244. /// use std::f64;
  1245. ///
  1246. /// let x: f64 = Float::min_value();
  1247. ///
  1248. /// assert_eq!(x, f64::MIN);
  1249. /// ```
  1250. fn min_value() -> Self;
  1251. /// Returns the smallest positive, normalized value that this type can represent.
  1252. ///
  1253. /// ```
  1254. /// use num::traits::Float;
  1255. /// use std::f64;
  1256. ///
  1257. /// let x: f64 = Float::min_positive_value();
  1258. ///
  1259. /// assert_eq!(x, f64::MIN_POSITIVE);
  1260. /// ```
  1261. fn min_positive_value() -> Self;
  1262. /// Returns the largest finite value that this type can represent.
  1263. ///
  1264. /// ```
  1265. /// use num::traits::Float;
  1266. /// use std::f64;
  1267. ///
  1268. /// let x: f64 = Float::max_value();
  1269. /// assert_eq!(x, f64::MAX);
  1270. /// ```
  1271. fn max_value() -> Self;
  1272. /// Returns `true` if this value is `NaN` and false otherwise.
  1273. ///
  1274. /// ```
  1275. /// use num::traits::Float;
  1276. /// use std::f64;
  1277. ///
  1278. /// let nan = f64::NAN;
  1279. /// let f = 7.0;
  1280. ///
  1281. /// assert!(nan.is_nan());
  1282. /// assert!(!f.is_nan());
  1283. /// ```
  1284. fn is_nan(self) -> bool;
  1285. /// Returns `true` if this value is positive infinity or negative infinity and
  1286. /// false otherwise.
  1287. ///
  1288. /// ```
  1289. /// use num::traits::Float;
  1290. /// use std::f32;
  1291. ///
  1292. /// let f = 7.0f32;
  1293. /// let inf: f32 = Float::infinity();
  1294. /// let neg_inf: f32 = Float::neg_infinity();
  1295. /// let nan: f32 = f32::NAN;
  1296. ///
  1297. /// assert!(!f.is_infinite());
  1298. /// assert!(!nan.is_infinite());
  1299. ///
  1300. /// assert!(inf.is_infinite());
  1301. /// assert!(neg_inf.is_infinite());
  1302. /// ```
  1303. fn is_infinite(self) -> bool;
  1304. /// Returns `true` if this number is neither infinite nor `NaN`.
  1305. ///
  1306. /// ```
  1307. /// use num::traits::Float;
  1308. /// use std::f32;
  1309. ///
  1310. /// let f = 7.0f32;
  1311. /// let inf: f32 = Float::infinity();
  1312. /// let neg_inf: f32 = Float::neg_infinity();
  1313. /// let nan: f32 = f32::NAN;
  1314. ///
  1315. /// assert!(f.is_finite());
  1316. ///
  1317. /// assert!(!nan.is_finite());
  1318. /// assert!(!inf.is_finite());
  1319. /// assert!(!neg_inf.is_finite());
  1320. /// ```
  1321. fn is_finite(self) -> bool;
  1322. /// Returns `true` if the number is neither zero, infinite,
  1323. /// [subnormal][subnormal], or `NaN`.
  1324. ///
  1325. /// ```
  1326. /// use num::traits::Float;
  1327. /// use std::f32;
  1328. ///
  1329. /// let min = f32::MIN_POSITIVE; // 1.17549435e-38f32
  1330. /// let max = f32::MAX;
  1331. /// let lower_than_min = 1.0e-40_f32;
  1332. /// let zero = 0.0f32;
  1333. ///
  1334. /// assert!(min.is_normal());
  1335. /// assert!(max.is_normal());
  1336. ///
  1337. /// assert!(!zero.is_normal());
  1338. /// assert!(!f32::NAN.is_normal());
  1339. /// assert!(!f32::INFINITY.is_normal());
  1340. /// // Values between `0` and `min` are Subnormal.
  1341. /// assert!(!lower_than_min.is_normal());
  1342. /// ```
  1343. /// [subnormal]: http://en.wikipedia.org/wiki/Denormal_number
  1344. fn is_normal(self) -> bool;
  1345. /// Returns the floating point category of the number. If only one property
  1346. /// is going to be tested, it is generally faster to use the specific
  1347. /// predicate instead.
  1348. ///
  1349. /// ```
  1350. /// use num::traits::Float;
  1351. /// use std::num::FpCategory;
  1352. /// use std::f32;
  1353. ///
  1354. /// let num = 12.4f32;
  1355. /// let inf = f32::INFINITY;
  1356. ///
  1357. /// assert_eq!(num.classify(), FpCategory::Normal);
  1358. /// assert_eq!(inf.classify(), FpCategory::Infinite);
  1359. /// ```
  1360. fn classify(self) -> FpCategory;
  1361. /// Returns the largest integer less than or equal to a number.
  1362. ///
  1363. /// ```
  1364. /// use num::traits::Float;
  1365. ///
  1366. /// let f = 3.99;
  1367. /// let g = 3.0;
  1368. ///
  1369. /// assert_eq!(f.floor(), 3.0);
  1370. /// assert_eq!(g.floor(), 3.0);
  1371. /// ```
  1372. fn floor(self) -> Self;
  1373. /// Returns the smallest integer greater than or equal to a number.
  1374. ///
  1375. /// ```
  1376. /// use num::traits::Float;
  1377. ///
  1378. /// let f = 3.01;
  1379. /// let g = 4.0;
  1380. ///
  1381. /// assert_eq!(f.ceil(), 4.0);
  1382. /// assert_eq!(g.ceil(), 4.0);
  1383. /// ```
  1384. fn ceil(self) -> Self;
  1385. /// Returns the nearest integer to a number. Round half-way cases away from
  1386. /// `0.0`.
  1387. ///
  1388. /// ```
  1389. /// use num::traits::Float;
  1390. ///
  1391. /// let f = 3.3;
  1392. /// let g = -3.3;
  1393. ///
  1394. /// assert_eq!(f.round(), 3.0);
  1395. /// assert_eq!(g.round(), -3.0);
  1396. /// ```
  1397. fn round(self) -> Self;
  1398. /// Return the integer part of a number.
  1399. ///
  1400. /// ```
  1401. /// use num::traits::Float;
  1402. ///
  1403. /// let f = 3.3;
  1404. /// let g = -3.7;
  1405. ///
  1406. /// assert_eq!(f.trunc(), 3.0);
  1407. /// assert_eq!(g.trunc(), -3.0);
  1408. /// ```
  1409. fn trunc(self) -> Self;
  1410. /// Returns the fractional part of a number.
  1411. ///
  1412. /// ```
  1413. /// use num::traits::Float;
  1414. ///
  1415. /// let x = 3.5;
  1416. /// let y = -3.5;
  1417. /// let abs_difference_x = (x.fract() - 0.5).abs();
  1418. /// let abs_difference_y = (y.fract() - (-0.5)).abs();
  1419. ///
  1420. /// assert!(abs_difference_x < 1e-10);
  1421. /// assert!(abs_difference_y < 1e-10);
  1422. /// ```
  1423. fn fract(self) -> Self;
  1424. /// Computes the absolute value of `self`. Returns `Float::nan()` if the
  1425. /// number is `Float::nan()`.
  1426. ///
  1427. /// ```
  1428. /// use num::traits::Float;
  1429. /// use std::f64;
  1430. ///
  1431. /// let x = 3.5;
  1432. /// let y = -3.5;
  1433. ///
  1434. /// let abs_difference_x = (x.abs() - x).abs();
  1435. /// let abs_difference_y = (y.abs() - (-y)).abs();
  1436. ///
  1437. /// assert!(abs_difference_x < 1e-10);
  1438. /// assert!(abs_difference_y < 1e-10);
  1439. ///
  1440. /// assert!(f64::NAN.abs().is_nan());
  1441. /// ```
  1442. fn abs(self) -> Self;
  1443. /// Returns a number that represents the sign of `self`.
  1444. ///
  1445. /// - `1.0` if the number is positive, `+0.0` or `Float::infinity()`
  1446. /// - `-1.0` if the number is negative, `-0.0` or `Float::neg_infinity()`
  1447. /// - `Float::nan()` if the number is `Float::nan()`
  1448. ///
  1449. /// ```
  1450. /// use num::traits::Float;
  1451. /// use std::f64;
  1452. ///
  1453. /// let f = 3.5;
  1454. ///
  1455. /// assert_eq!(f.signum(), 1.0);
  1456. /// assert_eq!(f64::NEG_INFINITY.signum(), -1.0);
  1457. ///
  1458. /// assert!(f64::NAN.signum().is_nan());
  1459. /// ```
  1460. fn signum(self) -> Self;
  1461. /// Returns `true` if `self` is positive, including `+0.0` and
  1462. /// `Float::infinity()`.
  1463. ///
  1464. /// ```
  1465. /// use num::traits::Float;
  1466. /// use std::f64;
  1467. ///
  1468. /// let nan: f64 = f64::NAN;
  1469. ///
  1470. /// let f = 7.0;
  1471. /// let g = -7.0;
  1472. ///
  1473. /// assert!(f.is_sign_positive());
  1474. /// assert!(!g.is_sign_positive());
  1475. /// // Requires both tests to determine if is `NaN`
  1476. /// assert!(!nan.is_sign_positive() && !nan.is_sign_negative());
  1477. /// ```
  1478. fn is_sign_positive(self) -> bool;
  1479. /// Returns `true` if `self` is negative, including `-0.0` and
  1480. /// `Float::neg_infinity()`.
  1481. ///
  1482. /// ```
  1483. /// use num::traits::Float;
  1484. /// use std::f64;
  1485. ///
  1486. /// let nan = f64::NAN;
  1487. ///
  1488. /// let f = 7.0;
  1489. /// let g = -7.0;
  1490. ///
  1491. /// assert!(!f.is_sign_negative());
  1492. /// assert!(g.is_sign_negative());
  1493. /// // Requires both tests to determine if is `NaN`.
  1494. /// assert!(!nan.is_sign_positive() && !nan.is_sign_negative());
  1495. /// ```
  1496. fn is_sign_negative(self) -> bool;
  1497. /// Fused multiply-add. Computes `(self * a) + b` with only one rounding
  1498. /// error. This produces a more accurate result with better performance than
  1499. /// a separate multiplication operation followed by an add.
  1500. ///
  1501. /// ```
  1502. /// use num::traits::Float;
  1503. ///
  1504. /// let m = 10.0;
  1505. /// let x = 4.0;
  1506. /// let b = 60.0;
  1507. ///
  1508. /// // 100.0
  1509. /// let abs_difference = (m.mul_add(x, b) - (m*x + b)).abs();
  1510. ///
  1511. /// assert!(abs_difference < 1e-10);
  1512. /// ```
  1513. fn mul_add(self, a: Self, b: Self) -> Self;
  1514. /// Take the reciprocal (inverse) of a number, `1/x`.
  1515. ///
  1516. /// ```
  1517. /// use num::traits::Float;
  1518. ///
  1519. /// let x = 2.0;
  1520. /// let abs_difference = (x.recip() - (1.0/x)).abs();
  1521. ///
  1522. /// assert!(abs_difference < 1e-10);
  1523. /// ```
  1524. fn recip(self) -> Self;
  1525. /// Raise a number to an integer power.
  1526. ///
  1527. /// Using this function is generally faster than using `powf`
  1528. ///
  1529. /// ```
  1530. /// use num::traits::Float;
  1531. ///
  1532. /// let x = 2.0;
  1533. /// let abs_difference = (x.powi(2) - x*x).abs();
  1534. ///
  1535. /// assert!(abs_difference < 1e-10);
  1536. /// ```
  1537. fn powi(self, n: i32) -> Self;
  1538. /// Raise a number to a floating point power.
  1539. ///
  1540. /// ```
  1541. /// use num::traits::Float;
  1542. ///
  1543. /// let x = 2.0;
  1544. /// let abs_difference = (x.powf(2.0) - x*x).abs();
  1545. ///
  1546. /// assert!(abs_difference < 1e-10);
  1547. /// ```
  1548. fn powf(self, n: Self) -> Self;
  1549. /// Take the square root of a number.
  1550. ///
  1551. /// Returns NaN if `self` is a negative number.
  1552. ///
  1553. /// ```
  1554. /// use num::traits::Float;
  1555. ///
  1556. /// let positive = 4.0;
  1557. /// let negative = -4.0;
  1558. ///
  1559. /// let abs_difference = (positive.sqrt() - 2.0).abs();
  1560. ///
  1561. /// assert!(abs_difference < 1e-10);
  1562. /// assert!(negative.sqrt().is_nan());
  1563. /// ```
  1564. fn sqrt(self) -> Self;
  1565. /// Returns `e^(self)`, (the exponential function).
  1566. ///
  1567. /// ```
  1568. /// use num::traits::Float;
  1569. ///
  1570. /// let one = 1.0;
  1571. /// // e^1
  1572. /// let e = one.exp();
  1573. ///
  1574. /// // ln(e) - 1 == 0
  1575. /// let abs_difference = (e.ln() - 1.0).abs();
  1576. ///
  1577. /// assert!(abs_difference < 1e-10);
  1578. /// ```
  1579. fn exp(self) -> Self;
  1580. /// Returns `2^(self)`.
  1581. ///
  1582. /// ```
  1583. /// use num::traits::Float;
  1584. ///
  1585. /// let f = 2.0;
  1586. ///
  1587. /// // 2^2 - 4 == 0
  1588. /// let abs_difference = (f.exp2() - 4.0).abs();
  1589. ///
  1590. /// assert!(abs_difference < 1e-10);
  1591. /// ```
  1592. fn exp2(self) -> Self;
  1593. /// Returns the natural logarithm of the number.
  1594. ///
  1595. /// ```
  1596. /// use num::traits::Float;
  1597. ///
  1598. /// let one = 1.0;
  1599. /// // e^1
  1600. /// let e = one.exp();
  1601. ///
  1602. /// // ln(e) - 1 == 0
  1603. /// let abs_difference = (e.ln() - 1.0).abs();
  1604. ///
  1605. /// assert!(abs_difference < 1e-10);
  1606. /// ```
  1607. fn ln(self) -> Self;
  1608. /// Returns the logarithm of the number with respect to an arbitrary base.
  1609. ///
  1610. /// ```
  1611. /// use num::traits::Float;
  1612. ///
  1613. /// let ten = 10.0;
  1614. /// let two = 2.0;
  1615. ///
  1616. /// // log10(10) - 1 == 0
  1617. /// let abs_difference_10 = (ten.log(10.0) - 1.0).abs();
  1618. ///
  1619. /// // log2(2) - 1 == 0
  1620. /// let abs_difference_2 = (two.log(2.0) - 1.0).abs();
  1621. ///
  1622. /// assert!(abs_difference_10 < 1e-10);
  1623. /// assert!(abs_difference_2 < 1e-10);
  1624. /// ```
  1625. fn log(self, base: Self) -> Self;
  1626. /// Returns the base 2 logarithm of the number.
  1627. ///
  1628. /// ```
  1629. /// use num::traits::Float;
  1630. ///
  1631. /// let two = 2.0;
  1632. ///
  1633. /// // log2(2) - 1 == 0
  1634. /// let abs_difference = (two.log2() - 1.0).abs();
  1635. ///
  1636. /// assert!(abs_difference < 1e-10);
  1637. /// ```
  1638. fn log2(self) -> Self;
  1639. /// Returns the base 10 logarithm of the number.
  1640. ///
  1641. /// ```
  1642. /// use num::traits::Float;
  1643. ///
  1644. /// let ten = 10.0;
  1645. ///
  1646. /// // log10(10) - 1 == 0
  1647. /// let abs_difference = (ten.log10() - 1.0).abs();
  1648. ///
  1649. /// assert!(abs_difference < 1e-10);
  1650. /// ```
  1651. fn log10(self) -> Self;
  1652. /// Returns the maximum of the two numbers.
  1653. ///
  1654. /// ```
  1655. /// use num::traits::Float;
  1656. ///
  1657. /// let x = 1.0;
  1658. /// let y = 2.0;
  1659. ///
  1660. /// assert_eq!(x.max(y), y);
  1661. /// ```
  1662. fn max(self, other: Self) -> Self;
  1663. /// Returns the minimum of the two numbers.
  1664. ///
  1665. /// ```
  1666. /// use num::traits::Float;
  1667. ///
  1668. /// let x = 1.0;
  1669. /// let y = 2.0;
  1670. ///
  1671. /// assert_eq!(x.min(y), x);
  1672. /// ```
  1673. fn min(self, other: Self) -> Self;
  1674. /// The positive difference of two numbers.
  1675. ///
  1676. /// * If `self <= other`: `0:0`
  1677. /// * Else: `self - other`
  1678. ///
  1679. /// ```
  1680. /// use num::traits::Float;
  1681. ///
  1682. /// let x = 3.0;
  1683. /// let y = -3.0;
  1684. ///
  1685. /// let abs_difference_x = (x.abs_sub(1.0) - 2.0).abs();
  1686. /// let abs_difference_y = (y.abs_sub(1.0) - 0.0).abs();
  1687. ///
  1688. /// assert!(abs_difference_x < 1e-10);
  1689. /// assert!(abs_difference_y < 1e-10);
  1690. /// ```
  1691. fn abs_sub(self, other: Self) -> Self;
  1692. /// Take the cubic root of a number.
  1693. ///
  1694. /// ```
  1695. /// use num::traits::Float;
  1696. ///
  1697. /// let x = 8.0;
  1698. ///
  1699. /// // x^(1/3) - 2 == 0
  1700. /// let abs_difference = (x.cbrt() - 2.0).abs();
  1701. ///
  1702. /// assert!(abs_difference < 1e-10);
  1703. /// ```
  1704. fn cbrt(self) -> Self;
  1705. /// Calculate the length of the hypotenuse of a right-angle triangle given
  1706. /// legs of length `x` and `y`.
  1707. ///
  1708. /// ```
  1709. /// use num::traits::Float;
  1710. ///
  1711. /// let x = 2.0;
  1712. /// let y = 3.0;
  1713. ///
  1714. /// // sqrt(x^2 + y^2)
  1715. /// let abs_difference = (x.hypot(y) - (x.powi(2) + y.powi(2)).sqrt()).abs();
  1716. ///
  1717. /// assert!(abs_difference < 1e-10);
  1718. /// ```
  1719. fn hypot(self, other: Self) -> Self;
  1720. /// Computes the sine of a number (in radians).
  1721. ///
  1722. /// ```
  1723. /// use num::traits::Float;
  1724. /// use std::f64;
  1725. ///
  1726. /// let x = f64::consts::PI/2.0;
  1727. ///
  1728. /// let abs_difference = (x.sin() - 1.0).abs();
  1729. ///
  1730. /// assert!(abs_difference < 1e-10);
  1731. /// ```
  1732. fn sin(self) -> Self;
  1733. /// Computes the cosine of a number (in radians).
  1734. ///
  1735. /// ```
  1736. /// use num::traits::Float;
  1737. /// use std::f64;
  1738. ///
  1739. /// let x = 2.0*f64::consts::PI;
  1740. ///
  1741. /// let abs_difference = (x.cos() - 1.0).abs();
  1742. ///
  1743. /// assert!(abs_difference < 1e-10);
  1744. /// ```
  1745. fn cos(self) -> Self;
  1746. /// Computes the tangent of a number (in radians).
  1747. ///
  1748. /// ```
  1749. /// use num::traits::Float;
  1750. /// use std::f64;
  1751. ///
  1752. /// let x = f64::consts::PI/4.0;
  1753. /// let abs_difference = (x.tan() - 1.0).abs();
  1754. ///
  1755. /// assert!(abs_difference < 1e-14);
  1756. /// ```
  1757. fn tan(self) -> Self;
  1758. /// Computes the arcsine of a number. Return value is in radians in
  1759. /// the range [-pi/2, pi/2] or NaN if the number is outside the range
  1760. /// [-1, 1].
  1761. ///
  1762. /// ```
  1763. /// use num::traits::Float;
  1764. /// use std::f64;
  1765. ///
  1766. /// let f = f64::consts::PI / 2.0;
  1767. ///
  1768. /// // asin(sin(pi/2))
  1769. /// let abs_difference = (f.sin().asin() - f64::consts::PI / 2.0).abs();
  1770. ///
  1771. /// assert!(abs_difference < 1e-10);
  1772. /// ```
  1773. fn asin(self) -> Self;
  1774. /// Computes the arccosine of a number. Return value is in radians in
  1775. /// the range [0, pi] or NaN if the number is outside the range
  1776. /// [-1, 1].
  1777. ///
  1778. /// ```
  1779. /// use num::traits::Float;
  1780. /// use std::f64;
  1781. ///
  1782. /// let f = f64::consts::PI / 4.0;
  1783. ///
  1784. /// // acos(cos(pi/4))
  1785. /// let abs_difference = (f.cos().acos() - f64::consts::PI / 4.0).abs();
  1786. ///
  1787. /// assert!(abs_difference < 1e-10);
  1788. /// ```
  1789. fn acos(self) -> Self;
  1790. /// Computes the arctangent of a number. Return value is in radians in the
  1791. /// range [-pi/2, pi/2];
  1792. ///
  1793. /// ```
  1794. /// use num::traits::Float;
  1795. ///
  1796. /// let f = 1.0;
  1797. ///
  1798. /// // atan(tan(1))
  1799. /// let abs_difference = (f.tan().atan() - 1.0).abs();
  1800. ///
  1801. /// assert!(abs_difference < 1e-10);
  1802. /// ```
  1803. fn atan(self) -> Self;
  1804. /// Computes the four quadrant arctangent of `self` (`y`) and `other` (`x`).
  1805. ///
  1806. /// * `x = 0`, `y = 0`: `0`
  1807. /// * `x >= 0`: `arctan(y/x)` -> `[-pi/2, pi/2]`
  1808. /// * `y >= 0`: `arctan(y/x) + pi` -> `(pi/2, pi]`
  1809. /// * `y < 0`: `arctan(y/x) - pi` -> `(-pi, -pi/2)`
  1810. ///
  1811. /// ```
  1812. /// use num::traits::Float;
  1813. /// use std::f64;
  1814. ///
  1815. /// let pi = f64::consts::PI;
  1816. /// // All angles from horizontal right (+x)
  1817. /// // 45 deg counter-clockwise
  1818. /// let x1 = 3.0;
  1819. /// let y1 = -3.0;
  1820. ///
  1821. /// // 135 deg clockwise
  1822. /// let x2 = -3.0;
  1823. /// let y2 = 3.0;
  1824. ///
  1825. /// let abs_difference_1 = (y1.atan2(x1) - (-pi/4.0)).abs();
  1826. /// let abs_difference_2 = (y2.atan2(x2) - 3.0*pi/4.0).abs();
  1827. ///
  1828. /// assert!(abs_difference_1 < 1e-10);
  1829. /// assert!(abs_difference_2 < 1e-10);
  1830. /// ```
  1831. fn atan2(self, other: Self) -> Self;
  1832. /// Simultaneously computes the sine and cosine of the number, `x`. Returns
  1833. /// `(sin(x), cos(x))`.
  1834. ///
  1835. /// ```
  1836. /// use num::traits::Float;
  1837. /// use std::f64;
  1838. ///
  1839. /// let x = f64::consts::PI/4.0;
  1840. /// let f = x.sin_cos();
  1841. ///
  1842. /// let abs_difference_0 = (f.0 - x.sin()).abs();
  1843. /// let abs_difference_1 = (f.1 - x.cos()).abs();
  1844. ///
  1845. /// assert!(abs_difference_0 < 1e-10);
  1846. /// assert!(abs_difference_0 < 1e-10);
  1847. /// ```
  1848. fn sin_cos(self) -> (Self, Self);
  1849. /// Returns `e^(self) - 1` in a way that is accurate even if the
  1850. /// number is close to zero.
  1851. ///
  1852. /// ```
  1853. /// use num::traits::Float;
  1854. ///
  1855. /// let x = 7.0;
  1856. ///
  1857. /// // e^(ln(7)) - 1
  1858. /// let abs_difference = (x.ln().exp_m1() - 6.0).abs();
  1859. ///
  1860. /// assert!(abs_difference < 1e-10);
  1861. /// ```
  1862. fn exp_m1(self) -> Self;
  1863. /// Returns `ln(1+n)` (natural logarithm) more accurately than if
  1864. /// the operations were performed separately.
  1865. ///
  1866. /// ```
  1867. /// use num::traits::Float;
  1868. /// use std::f64;
  1869. ///
  1870. /// let x = f64::consts::E - 1.0;
  1871. ///
  1872. /// // ln(1 + (e - 1)) == ln(e) == 1
  1873. /// let abs_difference = (x.ln_1p() - 1.0).abs();
  1874. ///
  1875. /// assert!(abs_difference < 1e-10);
  1876. /// ```
  1877. fn ln_1p(self) -> Self;
  1878. /// Hyperbolic sine function.
  1879. ///
  1880. /// ```
  1881. /// use num::traits::Float;
  1882. /// use std::f64;
  1883. ///
  1884. /// let e = f64::consts::E;
  1885. /// let x = 1.0;
  1886. ///
  1887. /// let f = x.sinh();
  1888. /// // Solving sinh() at 1 gives `(e^2-1)/(2e)`
  1889. /// let g = (e*e - 1.0)/(2.0*e);
  1890. /// let abs_difference = (f - g).abs();
  1891. ///
  1892. /// assert!(abs_difference < 1e-10);
  1893. /// ```
  1894. fn sinh(self) -> Self;
  1895. /// Hyperbolic cosine function.
  1896. ///
  1897. /// ```
  1898. /// use num::traits::Float;
  1899. /// use std::f64;
  1900. ///
  1901. /// let e = f64::consts::E;
  1902. /// let x = 1.0;
  1903. /// let f = x.cosh();
  1904. /// // Solving cosh() at 1 gives this result
  1905. /// let g = (e*e + 1.0)/(2.0*e);
  1906. /// let abs_difference = (f - g).abs();
  1907. ///
  1908. /// // Same result
  1909. /// assert!(abs_difference < 1.0e-10);
  1910. /// ```
  1911. fn cosh(self) -> Self;
  1912. /// Hyperbolic tangent function.
  1913. ///
  1914. /// ```
  1915. /// use num::traits::Float;
  1916. /// use std::f64;
  1917. ///
  1918. /// let e = f64::consts::E;
  1919. /// let x = 1.0;
  1920. ///
  1921. /// let f = x.tanh();
  1922. /// // Solving tanh() at 1 gives `(1 - e^(-2))/(1 + e^(-2))`
  1923. /// let g = (1.0 - e.powi(-2))/(1.0 + e.powi(-2));
  1924. /// let abs_difference = (f - g).abs();
  1925. ///
  1926. /// assert!(abs_difference < 1.0e-10);
  1927. /// ```
  1928. fn tanh(self) -> Self;
  1929. /// Inverse hyperbolic sine function.
  1930. ///
  1931. /// ```
  1932. /// use num::traits::Float;
  1933. ///
  1934. /// let x = 1.0;
  1935. /// let f = x.sinh().asinh();
  1936. ///
  1937. /// let abs_difference = (f - x).abs();
  1938. ///
  1939. /// assert!(abs_difference < 1.0e-10);
  1940. /// ```
  1941. fn asinh(self) -> Self;
  1942. /// Inverse hyperbolic cosine function.
  1943. ///
  1944. /// ```
  1945. /// use num::traits::Float;
  1946. ///
  1947. /// let x = 1.0;
  1948. /// let f = x.cosh().acosh();
  1949. ///
  1950. /// let abs_difference = (f - x).abs();
  1951. ///
  1952. /// assert!(abs_difference < 1.0e-10);
  1953. /// ```
  1954. fn acosh(self) -> Self;
  1955. /// Inverse hyperbolic tangent function.
  1956. ///
  1957. /// ```
  1958. /// use num::traits::Float;
  1959. /// use std::f64;
  1960. ///
  1961. /// let e = f64::consts::E;
  1962. /// let f = e.tanh().atanh();
  1963. ///
  1964. /// let abs_difference = (f - e).abs();
  1965. ///
  1966. /// assert!(abs_difference < 1.0e-10);
  1967. /// ```
  1968. fn atanh(self) -> Self;
  1969. /// Returns the mantissa, base 2 exponent, and sign as integers, respectively.
  1970. /// The original number can be recovered by `sign * mantissa * 2 ^ exponent`.
  1971. /// The floating point encoding is documented in the [Reference][floating-point].
  1972. ///
  1973. /// ```
  1974. /// use num::traits::Float;
  1975. ///
  1976. /// let num = 2.0f32;
  1977. ///
  1978. /// // (8388608, -22, 1)
  1979. /// let (mantissa, exponent, sign) = Float::integer_decode(num);
  1980. /// let sign_f = sign as f32;
  1981. /// let mantissa_f = mantissa as f32;
  1982. /// let exponent_f = num.powf(exponent as f32);
  1983. ///
  1984. /// // 1 * 8388608 * 2^(-22) == 2
  1985. /// let abs_difference = (sign_f * mantissa_f * exponent_f - num).abs();
  1986. ///
  1987. /// assert!(abs_difference < 1e-10);
  1988. /// ```
  1989. /// [floating-point]: ../../../../../reference.html#machine-types
  1990. fn integer_decode(self) -> (u64, i16, i8);
  1991. }
  1992. macro_rules! float_impl {
  1993. ($T:ident $decode:ident) => (
  1994. impl Float for $T {
  1995. fn nan() -> Self {
  1996. ::std::$T::NAN
  1997. }
  1998. fn infinity() -> Self {
  1999. ::std::$T::INFINITY
  2000. }
  2001. fn neg_infinity() -> Self {
  2002. ::std::$T::NEG_INFINITY
  2003. }
  2004. fn neg_zero() -> Self {
  2005. -0.0
  2006. }
  2007. fn min_value() -> Self {
  2008. ::std::$T::MIN
  2009. }
  2010. fn min_positive_value() -> Self {
  2011. ::std::$T::MIN_POSITIVE
  2012. }
  2013. fn max_value() -> Self {
  2014. ::std::$T::MAX
  2015. }
  2016. fn is_nan(self) -> bool {
  2017. <$T>::is_nan(self)
  2018. }
  2019. fn is_infinite(self) -> bool {
  2020. <$T>::is_infinite(self)
  2021. }
  2022. fn is_finite(self) -> bool {
  2023. <$T>::is_finite(self)
  2024. }
  2025. fn is_normal(self) -> bool {
  2026. <$T>::is_normal(self)
  2027. }
  2028. fn classify(self) -> FpCategory {
  2029. <$T>::classify(self)
  2030. }
  2031. fn floor(self) -> Self {
  2032. <$T>::floor(self)
  2033. }
  2034. fn ceil(self) -> Self {
  2035. <$T>::ceil(self)
  2036. }
  2037. fn round(self) -> Self {
  2038. <$T>::round(self)
  2039. }
  2040. fn trunc(self) -> Self {
  2041. <$T>::trunc(self)
  2042. }
  2043. fn fract(self) -> Self {
  2044. <$T>::fract(self)
  2045. }
  2046. fn abs(self) -> Self {
  2047. <$T>::abs(self)
  2048. }
  2049. fn signum(self) -> Self {
  2050. <$T>::signum(self)
  2051. }
  2052. fn is_sign_positive(self) -> bool {
  2053. <$T>::is_sign_positive(self)
  2054. }
  2055. fn is_sign_negative(self) -> bool {
  2056. <$T>::is_sign_negative(self)
  2057. }
  2058. fn mul_add(self, a: Self, b: Self) -> Self {
  2059. <$T>::mul_add(self, a, b)
  2060. }
  2061. fn recip(self) -> Self {
  2062. <$T>::recip(self)
  2063. }
  2064. fn powi(self, n: i32) -> Self {
  2065. <$T>::powi(self, n)
  2066. }
  2067. fn powf(self, n: Self) -> Self {
  2068. <$T>::powf(self, n)
  2069. }
  2070. fn sqrt(self) -> Self {
  2071. <$T>::sqrt(self)
  2072. }
  2073. fn exp(self) -> Self {
  2074. <$T>::exp(self)
  2075. }
  2076. fn exp2(self) -> Self {
  2077. <$T>::exp2(self)
  2078. }
  2079. fn ln(self) -> Self {
  2080. <$T>::ln(self)
  2081. }
  2082. fn log(self, base: Self) -> Self {
  2083. <$T>::log(self, base)
  2084. }
  2085. fn log2(self) -> Self {
  2086. <$T>::log2(self)
  2087. }
  2088. fn log10(self) -> Self {
  2089. <$T>::log10(self)
  2090. }
  2091. fn max(self, other: Self) -> Self {
  2092. <$T>::max(self, other)
  2093. }
  2094. fn min(self, other: Self) -> Self {
  2095. <$T>::min(self, other)
  2096. }
  2097. fn abs_sub(self, other: Self) -> Self {
  2098. <$T>::abs_sub(self, other)
  2099. }
  2100. fn cbrt(self) -> Self {
  2101. <$T>::cbrt(self)
  2102. }
  2103. fn hypot(self, other: Self) -> Self {
  2104. <$T>::hypot(self, other)
  2105. }
  2106. fn sin(self) -> Self {
  2107. <$T>::sin(self)
  2108. }
  2109. fn cos(self) -> Self {
  2110. <$T>::cos(self)
  2111. }
  2112. fn tan(self) -> Self {
  2113. <$T>::tan(self)
  2114. }
  2115. fn asin(self) -> Self {
  2116. <$T>::asin(self)
  2117. }
  2118. fn acos(self) -> Self {
  2119. <$T>::acos(self)
  2120. }
  2121. fn atan(self) -> Self {
  2122. <$T>::atan(self)
  2123. }
  2124. fn atan2(self, other: Self) -> Self {
  2125. <$T>::atan2(self, other)
  2126. }
  2127. fn sin_cos(self) -> (Self, Self) {
  2128. <$T>::sin_cos(self)
  2129. }
  2130. fn exp_m1(self) -> Self {
  2131. <$T>::exp_m1(self)
  2132. }
  2133. fn ln_1p(self) -> Self {
  2134. <$T>::ln_1p(self)
  2135. }
  2136. fn sinh(self) -> Self {
  2137. <$T>::sinh(self)
  2138. }
  2139. fn cosh(self) -> Self {
  2140. <$T>::cosh(self)
  2141. }
  2142. fn tanh(self) -> Self {
  2143. <$T>::tanh(self)
  2144. }
  2145. fn asinh(self) -> Self {
  2146. <$T>::asinh(self)
  2147. }
  2148. fn acosh(self) -> Self {
  2149. <$T>::acosh(self)
  2150. }
  2151. fn atanh(self) -> Self {
  2152. <$T>::atanh(self)
  2153. }
  2154. fn integer_decode(self) -> (u64, i16, i8) {
  2155. $decode(self)
  2156. }
  2157. }
  2158. )
  2159. }
  2160. fn integer_decode_f32(f: f32) -> (u64, i16, i8) {
  2161. let bits: u32 = unsafe { mem::transmute(f) };
  2162. let sign: i8 = if bits >> 31 == 0 { 1 } else { -1 };
  2163. let mut exponent: i16 = ((bits >> 23) & 0xff) as i16;
  2164. let mantissa = if exponent == 0 {
  2165. (bits & 0x7fffff) << 1
  2166. } else {
  2167. (bits & 0x7fffff) | 0x800000
  2168. };
  2169. // Exponent bias + mantissa shift
  2170. exponent -= 127 + 23;
  2171. (mantissa as u64, exponent, sign)
  2172. }
  2173. fn integer_decode_f64(f: f64) -> (u64, i16, i8) {
  2174. let bits: u64 = unsafe { mem::transmute(f) };
  2175. let sign: i8 = if bits >> 63 == 0 { 1 } else { -1 };
  2176. let mut exponent: i16 = ((bits >> 52) & 0x7ff) as i16;
  2177. let mantissa = if exponent == 0 {
  2178. (bits & 0xfffffffffffff) << 1
  2179. } else {
  2180. (bits & 0xfffffffffffff) | 0x10000000000000
  2181. };
  2182. // Exponent bias + mantissa shift
  2183. exponent -= 1023 + 52;
  2184. (mantissa, exponent, sign)
  2185. }
  2186. float_impl!(f32 integer_decode_f32);
  2187. float_impl!(f64 integer_decode_f64);