tesap_std/
bytes.rs

1use crate::Vector;
2use std::fmt;
3use std::mem;
4
5// === Formats ===
6// bytes: (&[u8]) [x01, xf3, x7d, x19]
7//   This serve as a common ground for all conversions
8// int: (i64) 3485392
9// bin: (str) "01010101010100110"
10// hex: (str) "3bed02d1d149e5336349707ce47d6c90"
11
12
13fn u8_to_bin(n: &u8) -> Bin {
14    format!("{:08b}", n)
15}
16
17fn bin_to_u8(b: &Bin) -> u8 {
18    u8::from_str_radix(b, 2).expect("Invalid binary string")
19}
20
21fn u8_to_hex(n: &u8) -> String {
22    format!("{:02x}", n)
23}
24
25fn hex_to_u8(h: &str) -> u8 {
26    u8::from_str_radix(h, 16).expect("Invalid hex string")
27}
28
29type Byte = u8;
30
31#[derive(Debug)]
32pub struct Bytes<const BIG_ENDIAN: bool = true>{
33    // TODO Switch to Vector<Byte>
34    pub vec: Vector<Byte>
35}
36
37#[derive(Clone, Debug)]
38pub struct Hex(pub String);
39
40pub type Bin = String;
41
42#[derive(Debug)]
43pub struct Bins(pub Vector<Bin>);
44
45impl Into<String> for &Bins {
46    fn into(self) -> String {
47        self.0.join(" ")
48    }
49}
50
51pub trait DebugBytes {
52    fn print(&self);
53}
54
55impl fmt::Display for Hex {
56    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
57        write!(f, "{:}", self.0)
58    }
59}
60
61impl DebugBytes for Bytes<true> {
62    fn print(&self) {
63        println!("\n----> Bytes: {:?}", self);
64        self.as_slice().print();
65        self.to_int128().unwrap().print();
66        self.to_bin().print();
67        self.to_hex().print();
68        println!();
69    }
70}
71
72impl DebugBytes for i128 {
73    fn print(&self) {
74        let p: *const i128 = &*self;
75
76        let view: Vector<Byte> = Vector {
77            ptr: p as *mut Byte,
78            cap: 16,
79            len: 16,
80        };
81        println!("-> i128: {:?}; {:?}", self, view);
82        std::mem::forget(view);
83    }
84}
85
86impl DebugBytes for &[Byte] {
87    fn print(&self) {
88        println!("-> &[u8]: {:?}", self);
89    }
90}
91
92impl DebugBytes for Hex {
93    fn print(&self) {
94        println!("-> Hex: {:?}", self.0);
95    }
96}
97
98impl DebugBytes for Bins {
99    fn print(&self) {
100        let s: String = self.into();
101        println!("-> Bins: [{:}]", s);
102    }
103}
104
105impl<const BE: bool> Bytes<BE> {
106    pub fn as_slice(&self) -> &[Byte] {
107        self.vec.as_slice()
108    }
109
110    pub fn to_int128(&self) -> Result<i128, String> {
111        let s1 = size_of::<i128>();
112        let s2 = self.vec.len_bytes();
113
114        if s2 > s1 {
115            return Err("Bytes length is too big".to_string());
116        }
117
118        unsafe {
119            let ptr: *const i128 = self.vec.as_ptr() as *const i128;
120            Ok(ptr.read())
121        }
122    }
123
124    pub fn to_bin(&self) -> Bins {
125        let v: Vector<Bin> = self.vec.iter().map(u8_to_bin).collect();
126        let a = Bins(v);
127        a
128    }
129
130    pub fn to_hex(&self) -> Hex {
131        let hex_string = self.vec.iter()
132            .map(u8_to_hex)
133            .collect::<String>();
134        Hex(hex_string)
135    }
136
137    pub fn from_bytes(from: &[Byte]) -> Self {
138        Self {
139            vec: Vector::from_slice_copy(from)
140        }
141    }
142
143    // WHAT? If we pass 'from' by value, further from_slice fails with error referencing
144    // i.e. value is dropped (right?)
145    pub fn from_int(from: &i128) -> Self {
146        // Direct cast doesn't work, but intermediate does
147        let ptr: *const i128 = from;
148        // Casting from const to mut is legal
149        let ptr_u8: *mut u8 = ptr as *mut u8;
150
151        // Why *mut type is needed?
152        let size: usize = mem::size_of::<i128>() / mem::size_of::<Byte>();
153
154        // --> Doesnt work
155        // let slice: *const [Byte] = ptr as *const [Byte];
156
157        // --> Is it prefferred option over direct slice constructor?
158        // Constructing wide pointer
159        // let nn_ptr = ptr::NonNull::new(ptr_u8).unwrap();
160        //let slice = unsafe {
161        //    ptr::NonNull::slice_from_raw_parts(nn_ptr, size).as_mut()
162        //};
163
164        // --> Manually create slice
165        let slice = unsafe {
166            std::slice::from_raw_parts(ptr_u8, size)
167        };
168
169        Self {
170            vec: Vector::from_slice_copy(slice)
171        }
172    }
173
174    pub fn from_bins(from: &Bins) -> Self {
175        let bytes: Vector<Byte> = from.0.iter().map(bin_to_u8).collect();
176        Self {
177            vec: bytes
178        }
179    }
180
181    pub fn from_hex(from: &Hex) -> Self {
182        let mut v: Vector<Byte> = Vector::new(0);
183        for i in (0..from.0.len()).step_by(2) {
184            // What is &x[..] expression?
185            let b: u8 = hex_to_u8(&from.0[i..i+2]);
186            v.push(b);
187        }
188
189        Self {
190            vec: v
191        }
192    }
193}
194
195impl From<Vector<u8>> for Bytes {
196    fn from(value: Vector<u8>) -> Self {
197        Self {
198            vec: value
199        }
200    }
201}
202
203impl Into<Vector<u8>> for Bytes {
204    fn into(self) -> Vector<u8> {
205        self.vec
206    }
207}
208
209impl From<Vec<u8>> for Bytes {
210    fn from(value: Vec<u8>) -> Self {
211        Self {
212            vec: Vector::from(value)
213        }
214    }
215}
216
217impl Into<Vec<u8>> for Bytes {
218    fn into(self) -> Vec<u8> {
219        self.vec.into()
220    }
221}
222
223impl Default for Bytes {
224    fn default() -> Self {
225        Self {
226            vec: Vector::new(0),
227        }
228    }
229}