zmij/
traits.rs

1use core::fmt::Display;
2use core::ops::{Add, BitAnd, BitOr, BitOrAssign, BitXorAssign, Div, Mul, Shl, Shr, Sub};
3
4pub trait Float: Copy {
5    type UInt: UInt;
6    const MANTISSA_DIGITS: u32;
7    const MAX_DIGITS10: u32;
8    fn to_bits(self) -> Self::UInt;
9}
10
11impl Float for f32 {
12    type UInt = u32;
13    const MANTISSA_DIGITS: u32 = Self::MANTISSA_DIGITS;
14    const MAX_DIGITS10: u32 = 9;
15    fn to_bits(self) -> Self::UInt {
16        self.to_bits()
17    }
18}
19
20impl Float for f64 {
21    type UInt = u64;
22    const MANTISSA_DIGITS: u32 = Self::MANTISSA_DIGITS;
23    const MAX_DIGITS10: u32 = 17;
24    fn to_bits(self) -> Self::UInt {
25        self.to_bits()
26    }
27}
28
29pub trait UInt:
30    Copy
31    + From<u8>
32    + From<bool>
33    + Add<Output = Self>
34    + Sub<Output = Self>
35    + Mul<Output = Self>
36    + Div<Output = Self>
37    + BitAnd<Output = Self>
38    + BitOr<Output = Self>
39    + Shl<i32, Output = Self>
40    + Shl<u32, Output = Self>
41    + Shr<i32, Output = Self>
42    + Shr<u32, Output = Self>
43    + BitOrAssign
44    + BitXorAssign
45    + PartialOrd
46    + Into<u64>
47    + Display
48{
49    type Signed: Ord;
50    fn wrapping_sub(self, other: Self) -> Self;
51    fn truncate(big: u64) -> Self;
52    fn enlarge(small: u32) -> Self;
53    fn to_signed(self) -> Self::Signed;
54}
55
56impl UInt for u32 {
57    type Signed = i32;
58    fn wrapping_sub(self, other: Self) -> Self {
59        self.wrapping_sub(other)
60    }
61    fn truncate(big: u64) -> Self {
62        big as u32
63    }
64    fn enlarge(small: u32) -> Self {
65        small
66    }
67    fn to_signed(self) -> Self::Signed {
68        self as i32
69    }
70}
71
72impl UInt for u64 {
73    type Signed = i64;
74    fn wrapping_sub(self, other: Self) -> Self {
75        self.wrapping_sub(other)
76    }
77    fn truncate(big: u64) -> Self {
78        big
79    }
80    fn enlarge(small: u32) -> Self {
81        u64::from(small)
82    }
83    fn to_signed(self) -> Self::Signed {
84        self as i64
85    }
86}