1use crate::io::Source;
2
3use super::Token;
4
5const BYTE_LEN_FOR_8: usize = 1;
6const BYTE_LEN_FOR_16: usize = 2;
7const BYTE_LEN_FOR_32: usize = 4;
8const BYTE_LEN_FOR_64: usize = 8;
9
10pub trait Encode {
11 fn to_le_vec(&self) -> Vec<u8>;
12}
13
14impl Encode for u16 {
15 fn to_le_vec(&self) -> Vec<u8> {
16 self.to_le_bytes().to_vec()
17 }
18}
19
20impl Encode for u32 {
21 fn to_le_vec(&self) -> Vec<u8> {
22 self.to_le_bytes().to_vec()
23 }
24}
25
26impl Encode for Vec<Token> {
27 fn to_le_vec(&self) -> Vec<u8> {
28 self.iter().flat_map(|token| token.to_le_vec()).collect()
29 }
30}
31
32pub trait Decode {
33 fn from_le_vec(source: &mut Source) -> Result<Self, String>
34 where
35 Self: Sized;
36}
37
38impl Decode for u8 {
39 fn from_le_vec(source: &mut Source) -> Result<Self, String> {
40 let mut temp: [u8; BYTE_LEN_FOR_8] = [0; BYTE_LEN_FOR_8];
41 temp.copy_from_slice(&source.get_vec(BYTE_LEN_FOR_8)?[..]);
42 Ok(u8::from_le_bytes(temp))
43 }
44}
45
46impl Decode for u16 {
47 fn from_le_vec(source: &mut Source) -> Result<Self, String> {
48 let mut temp: [u8; BYTE_LEN_FOR_16] = [0; BYTE_LEN_FOR_16];
49 temp.copy_from_slice(&source.get_vec(BYTE_LEN_FOR_16)?[..]);
50 Ok(u16::from_le_bytes(temp))
51 }
52}
53
54impl Decode for u32 {
55 fn from_le_vec(source: &mut Source) -> Result<Self, String> {
56 let mut temp: [u8; BYTE_LEN_FOR_32] = [0; BYTE_LEN_FOR_32];
57 temp.copy_from_slice(&source.get_vec(BYTE_LEN_FOR_32)?[..]);
58 Ok(u32::from_le_bytes(temp))
59 }
60}
61
62impl Decode for i8 {
63 fn from_le_vec(source: &mut Source) -> Result<Self, String> {
64 let mut temp: [u8; BYTE_LEN_FOR_8] = [0; BYTE_LEN_FOR_8];
65 temp.copy_from_slice(&source.get_vec(BYTE_LEN_FOR_8)?[..]);
66 Ok(i8::from_le_bytes(temp))
67 }
68}
69
70impl Decode for i16 {
71 fn from_le_vec(source: &mut Source) -> Result<Self, String> {
72 let mut temp: [u8; BYTE_LEN_FOR_16] = [0; BYTE_LEN_FOR_16];
73 temp.copy_from_slice(&source.get_vec(BYTE_LEN_FOR_16)?[..]);
74 Ok(i16::from_le_bytes(temp))
75 }
76}
77
78impl Decode for i32 {
79 fn from_le_vec(source: &mut Source) -> Result<Self, String> {
80 let mut temp: [u8; BYTE_LEN_FOR_32] = [0; BYTE_LEN_FOR_32];
81 temp.copy_from_slice(&source.get_vec(BYTE_LEN_FOR_32)?[..]);
82 Ok(i32::from_le_bytes(temp))
83 }
84}
85
86impl Decode for f32 {
87 fn from_le_vec(source: &mut Source) -> Result<Self, String> {
88 let mut temp: [u8; BYTE_LEN_FOR_32] = [0; BYTE_LEN_FOR_32];
89 temp.copy_from_slice(&source.get_vec(BYTE_LEN_FOR_32)?[..]);
90 Ok(f32::from_le_bytes(temp))
91 }
92}
93
94impl Decode for f64 {
95 fn from_le_vec(source: &mut Source) -> Result<Self, String> {
96 let mut temp: [u8; BYTE_LEN_FOR_64] = [0; BYTE_LEN_FOR_64];
97 temp.copy_from_slice(&source.get_vec(BYTE_LEN_FOR_64)?[..]);
98 Ok(f64::from_le_bytes(temp))
99 }
100}