Skip to main content

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