Skip to main content

nucleide/parse/
num.rs

1// Copyright © 2022-2023 The Nucleide Contributors.
2//
3// Licensed under any of:
4// - Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0)
5// - Boost Software License, Version 1.0 (https://www.boost.org/LICENSE_1_0.txt)
6// - MIT License (https://mit-license.org/)
7// At your choosing (See accompanying files LICENSE_APACHE_2_0.txt,
8// LICENSE_MIT.txt and LICENSE_BOOST_1_0.txt).
9
10use core::ops::{
11    Add, AddAssign, Div, DivAssign, Mul, MulAssign, Not, Shl, ShlAssign, Shr,
12    ShrAssign, Sub, SubAssign,
13};
14
15/// Trait implemented for integer primitives
16pub trait Number:
17    Not
18    + Add
19    + AddAssign
20    + Sub
21    + SubAssign
22    + Mul
23    + MulAssign
24    + Div
25    + DivAssign
26    + Shr<u8>
27    + ShrAssign<u8>
28    + Shl<u8>
29    + ShlAssign<u8>
30    + Eq
31    + PartialEq
32    + Sized
33{
34}
35
36impl<T> Number for T where
37    T: Not
38        + Add
39        + AddAssign
40        + Sub
41        + SubAssign
42        + Mul
43        + MulAssign
44        + Div
45        + DivAssign
46        + Shr<u8>
47        + ShrAssign<u8>
48        + Shl<u8>
49        + ShlAssign<u8>
50        + Eq
51        + PartialEq
52        + Sized
53{
54}
55
56/// Trait implemented for unsigned integers
57pub trait UInt: Number + From<u8> + Copy + Clone {
58    /// The minimum value of an unsigned integer, 0
59    const ZERO: Self;
60    /// Size of the primitive, in bits
61    const BITS: u8;
62
63    /// Grab the little byte.
64    fn little(&self) -> u8;
65}
66
67impl UInt for u8 {
68    const BITS: u8 = 8;
69    const ZERO: u8 = u8::MIN;
70
71    fn little(&self) -> u8 {
72        *self
73    }
74}
75
76impl UInt for u16 {
77    const BITS: u8 = 16;
78    const ZERO: u16 = u16::MIN;
79
80    fn little(&self) -> u8 {
81        let [byte, _] = self.to_le_bytes();
82
83        byte
84    }
85}
86
87impl UInt for u32 {
88    const BITS: u8 = 32;
89    const ZERO: u32 = u32::MIN;
90
91    fn little(&self) -> u8 {
92        let [byte, _, _, _] = self.to_le_bytes();
93
94        byte
95    }
96}
97
98impl UInt for u64 {
99    const BITS: u8 = 64;
100    const ZERO: u64 = u64::MIN;
101
102    fn little(&self) -> u8 {
103        let [byte, _, _, _, _, _, _, _] = self.to_le_bytes();
104
105        byte
106    }
107}
108
109impl UInt for u128 {
110    const BITS: u8 = 128;
111    const ZERO: u128 = u128::MIN;
112
113    fn little(&self) -> u8 {
114        let [byte, _, _, _, _, _, _, _, _, _, _, _, _, _, _, _] =
115            self.to_le_bytes();
116
117        byte
118    }
119}