fast_posit/posit/
traits.rs

1use super::*;
2
3// The `Int` trait has bounds indirectly, via `Sealed`. For example, we don't have `Int:
4// PartialEq`, we have `Int: Sealed` and `Sealed: PartialEq`, so the derive macro derives
5//
6//   impl<const N: u32, const ES: u32, Int: PartialEq + Int> PartialEq for Posit<N, ES, Int>
7//
8// but of course we know we can just have
9//
10//   impl<const N: u32, const ES: u32, Int: Int> PartialEq for Posit<N, ES, Int>
11//
12// Because of that we just implement explicitly here.
13
14impl<const N: u32, const ES: u32, Int: crate::Int>
15Clone for Posit<N, ES, Int> {
16  #[inline]
17  fn clone(&self) -> Self {
18    Self(self.0)
19  }
20}
21
22impl<const N: u32, const ES: u32, Int: crate::Int>
23Copy for Posit<N, ES, Int> {}
24
25/// Note that, **unlike IEEE floats**, [NaR](Self::NAR) is equal to itself (and different from any
26/// other value).
27///
28/// # Example
29///
30/// ```
31/// # use fast_posit::*;
32/// assert!(p32::NAR == p32::NAR);
33/// assert!(f32::NAN != f32::NAN);
34///
35/// assert!(p32::NAR != 3.round_into());
36/// assert!(f32::NAN != 3.);
37/// ```
38impl<const N: u32, const ES: u32, Int: crate::Int>
39PartialEq for Posit<N, ES, Int> {
40  #[inline]
41  fn eq(&self, other: &Self) -> bool {
42    self.0 == other.0
43  }
44}
45
46impl<const N: u32, const ES: u32, Int: crate::Int>
47Eq for Posit<N, ES, Int> {}
48
49/// Note that, **unlike IEEE floats**, posits have a total order (i.e. implement [`Ord`]).
50/// [NaR](Self::NAR) is always smaller than any other value, and equal to itself.
51///
52/// # Example
53///
54/// ```
55/// # use fast_posit::*;
56/// # use core::cmp::Ordering;
57/// assert_eq!(p32::NAR.partial_cmp(&p32::NAR), Some(Ordering::Equal));
58/// assert_eq!(f32::NAN.partial_cmp(&f32::NAN), None);
59///
60/// assert!(p32::NAR < p32::round_from(-3));
61/// assert!(!(f32::NAN < -3.) && !(f32::NAN >= -3.));
62/// ```
63impl<const N: u32, const ES: u32, Int: crate::Int>
64PartialOrd for Posit<N, ES, Int> {
65  #[inline]
66  fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
67    self.0.partial_cmp(&other.0)
68  }
69}
70
71impl<const N: u32, const ES: u32, Int: crate::Int>
72Ord for Posit<N, ES, Int> {
73  #[inline]
74  fn cmp(&self, other: &Self) -> core::cmp::Ordering {
75    self.0.cmp(&other.0)
76  }
77}
78
79impl<const N: u32, const ES: u32, Int: crate::Int>
80core::hash::Hash for Posit<N, ES, Int> {
81  #[inline]
82  fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
83    self.0.hash(state);
84  }
85}
86
87impl<const N: u32, const ES: u32, Int: crate::Int>
88Default for Posit<N, ES, Int> {
89  #[inline]
90  fn default() -> Self {
91    Self(Default::default())
92  }
93}