mod.rs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. use core::mem;
  2. pub mod add;
  3. /// Trait for some basic operations on floats
  4. pub trait Float: Sized {
  5. /// A uint of the same with as the float
  6. type Int;
  7. /// Returns the bitwidth of the float type
  8. fn bits() -> u32;
  9. /// Returns the bitwidth of the significand
  10. fn significand_bits() -> u32;
  11. /// Returns `self` transmuted to `Self::Int`
  12. fn repr(self) -> Self::Int;
  13. /// Returns a `Self::Int` transmuted back to `Self`
  14. fn from_repr(a: Self::Int) -> Self;
  15. /// Returns (normalized exponent, normalized significand)
  16. fn normalize(significand: Self::Int) -> (i32, Self::Int);
  17. }
  18. impl Float for f32 {
  19. type Int = u32;
  20. fn bits() -> u32 {
  21. 32
  22. }
  23. fn significand_bits() -> u32 {
  24. 23
  25. }
  26. fn repr(self) -> Self::Int {
  27. unsafe { mem::transmute(self) }
  28. }
  29. fn from_repr(a: Self::Int) -> Self {
  30. unsafe { mem::transmute(a) }
  31. }
  32. fn normalize(significand: Self::Int) -> (i32, Self::Int) {
  33. let shift = significand.leading_zeros()
  34. .wrapping_sub((1u32 << Self::significand_bits()).leading_zeros());
  35. (1i32.wrapping_sub(shift as i32), significand << shift as Self::Int)
  36. }
  37. }
  38. impl Float for f64 {
  39. type Int = u64;
  40. fn bits() -> u32 {
  41. 64
  42. }
  43. fn significand_bits() -> u32 {
  44. 52
  45. }
  46. fn repr(self) -> Self::Int {
  47. unsafe { mem::transmute(self) }
  48. }
  49. fn from_repr(a: Self::Int) -> Self {
  50. unsafe { mem::transmute(a) }
  51. }
  52. fn normalize(significand: Self::Int) -> (i32, Self::Int) {
  53. let shift = significand.leading_zeros()
  54. .wrapping_sub((1u64 << Self::significand_bits()).leading_zeros());
  55. (1i32.wrapping_sub(shift as i32), significand << shift as Self::Int)
  56. }
  57. }