identities.rs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. use std::ops::{Add, Mul};
  2. /// Defines an additive identity element for `Self`.
  3. pub trait Zero: Sized + Add<Self, Output = Self> {
  4. /// Returns the additive identity element of `Self`, `0`.
  5. ///
  6. /// # Laws
  7. ///
  8. /// ```{.text}
  9. /// a + 0 = a ∀ a ∈ Self
  10. /// 0 + a = a ∀ a ∈ Self
  11. /// ```
  12. ///
  13. /// # Purity
  14. ///
  15. /// This function should return the same result at all times regardless of
  16. /// external mutable state, for example values stored in TLS or in
  17. /// `static mut`s.
  18. // FIXME (#5527): This should be an associated constant
  19. fn zero() -> Self;
  20. /// Returns `true` if `self` is equal to the additive identity.
  21. #[inline]
  22. fn is_zero(&self) -> bool;
  23. }
  24. macro_rules! zero_impl {
  25. ($t:ty, $v:expr) => {
  26. impl Zero for $t {
  27. #[inline]
  28. fn zero() -> $t { $v }
  29. #[inline]
  30. fn is_zero(&self) -> bool { *self == $v }
  31. }
  32. }
  33. }
  34. zero_impl!(usize, 0usize);
  35. zero_impl!(u8, 0u8);
  36. zero_impl!(u16, 0u16);
  37. zero_impl!(u32, 0u32);
  38. zero_impl!(u64, 0u64);
  39. zero_impl!(isize, 0isize);
  40. zero_impl!(i8, 0i8);
  41. zero_impl!(i16, 0i16);
  42. zero_impl!(i32, 0i32);
  43. zero_impl!(i64, 0i64);
  44. zero_impl!(f32, 0.0f32);
  45. zero_impl!(f64, 0.0f64);
  46. /// Defines a multiplicative identity element for `Self`.
  47. pub trait One: Sized + Mul<Self, Output = Self> {
  48. /// Returns the multiplicative identity element of `Self`, `1`.
  49. ///
  50. /// # Laws
  51. ///
  52. /// ```{.text}
  53. /// a * 1 = a ∀ a ∈ Self
  54. /// 1 * a = a ∀ a ∈ Self
  55. /// ```
  56. ///
  57. /// # Purity
  58. ///
  59. /// This function should return the same result at all times regardless of
  60. /// external mutable state, for example values stored in TLS or in
  61. /// `static mut`s.
  62. // FIXME (#5527): This should be an associated constant
  63. fn one() -> Self;
  64. }
  65. macro_rules! one_impl {
  66. ($t:ty, $v:expr) => {
  67. impl One for $t {
  68. #[inline]
  69. fn one() -> $t { $v }
  70. }
  71. }
  72. }
  73. one_impl!(usize, 1usize);
  74. one_impl!(u8, 1u8);
  75. one_impl!(u16, 1u16);
  76. one_impl!(u32, 1u32);
  77. one_impl!(u64, 1u64);
  78. one_impl!(isize, 1isize);
  79. one_impl!(i8, 1i8);
  80. one_impl!(i16, 1i16);
  81. one_impl!(i32, 1i32);
  82. one_impl!(i64, 1i64);
  83. one_impl!(f32, 1.0f32);
  84. one_impl!(f64, 1.0f64);