protocol_v3/
protocol.rs

1use std::collections::VecDeque;
2
3
4#[derive(Debug)]
5pub struct DecodeError {}
6
7
8impl std::error::Error for DecodeError {
9    fn description(&self) -> &str {
10        "Bad WS frame received from a client!"
11    }
12}
13
14
15impl std::fmt::Display for DecodeError {
16    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
17        write!(f, "Protocol Decode Error")
18    }
19}
20
21
22pub trait ProtocolFrame : Sized {
23    fn encode(&self) -> Vec<u8>;
24    fn decode(data : VecDeque<u8>) -> Result<Self, DecodeError>;
25    fn manifest() -> &'static str; // manifest of this protocol frame type.
26}
27
28pub trait ProtocolSegment : Sized {
29    fn encode(self) -> Vec<u8>;
30    fn decode(data : &mut VecDeque<u8>) -> Result<Self, DecodeError>;
31}
32
33impl ProtocolSegment for u8 {
34    fn encode(self) -> Vec<u8> {
35        let mut v = Vec::with_capacity(1);
36        v.push(self);
37        v
38    }
39
40    fn decode(data : &mut VecDeque<u8>) -> Result<Self, DecodeError> {
41        data.pop_front().ok_or(DecodeError {})
42    }
43}
44
45
46impl ProtocolSegment for bool {
47    fn encode(self) -> Vec<u8> {
48        let mut v = Vec::with_capacity(1);
49        v.push(if self { 1 } else { 0 });
50        v
51    }
52
53    fn decode(data : &mut VecDeque<u8>) -> Result<Self, DecodeError> {
54        Ok(if data.pop_front().ok_or(DecodeError {})? == 1 { true } else { false })
55    }
56}
57
58impl ProtocolSegment for u16 {
59    fn encode(self) -> Vec<u8> {
60        let mut v : Vec<u8> = Vec::with_capacity(2);
61        let bytes = self.to_be_bytes();
62        v.push(bytes[0]); // flip the byte order so it pops in properly
63        v.push(bytes[1]);
64        v
65    }
66
67    fn decode(data : &mut VecDeque<u8>) -> Result<Self, DecodeError> {
68        let r = [data.pop_front().ok_or(DecodeError {})?, data.pop_front().ok_or(DecodeError {})?];
69        Ok(Self::from_be_bytes(r))
70    }
71}
72
73
74impl ProtocolSegment for u32 {
75    fn encode(self) -> Vec<u8> {
76        let mut v : Vec<u8> = Vec::with_capacity(4);
77        let bytes = self.to_be_bytes();
78        v.push(bytes[0]); // flip the byte order so it pops in properly
79        v.push(bytes[1]);
80        v.push(bytes[2]);
81        v.push(bytes[3]);
82        v
83    }
84
85    fn decode(data : &mut VecDeque<u8>) -> Result<Self, DecodeError> {
86        let r = [data.pop_front().ok_or(DecodeError {})?, data.pop_front().ok_or(DecodeError {})?, data.pop_front().ok_or(DecodeError {})?, data.pop_front().ok_or(DecodeError {})?];
87        Ok(Self::from_be_bytes(r))
88    }
89}
90
91
92impl ProtocolSegment for u64 {
93    fn encode(self) -> Vec<u8> {
94        let mut v : Vec<u8> = Vec::with_capacity(8);
95        let bytes = self.to_be_bytes();
96        v.push(bytes[0]);
97        v.push(bytes[1]);
98        v.push(bytes[2]);
99        v.push(bytes[3]);
100        v.push(bytes[4]);
101        v.push(bytes[5]);
102        v.push(bytes[6]);
103        v.push(bytes[7]);
104        v
105    }
106
107    fn decode(data : &mut VecDeque<u8>) -> Result<Self, DecodeError> {
108        let r = [data.pop_front().ok_or(DecodeError {})?, data.pop_front().ok_or(DecodeError {})?, data.pop_front().ok_or(DecodeError {})?, data.pop_front().ok_or(DecodeError {})?, data.pop_front().ok_or(DecodeError {})?, data.pop_front().ok_or(DecodeError {})?, data.pop_front().ok_or(DecodeError {})?, data.pop_front().ok_or(DecodeError {})?];
109        Ok(Self::from_be_bytes(r))
110    }
111}
112
113
114impl ProtocolSegment for i32 {
115    fn encode(self) -> Vec<u8> {
116        let mut v : Vec<u8> = Vec::with_capacity(4);
117        let bytes = self.to_be_bytes();
118        v.push(bytes[0]); // flip the byte order so it pops in properly
119        v.push(bytes[1]);
120        v.push(bytes[2]);
121        v.push(bytes[3]);
122        v
123    }
124
125    fn decode(data : &mut VecDeque<u8>) -> Result<Self, DecodeError> {
126        let r = [data.pop_front().ok_or(DecodeError {})?, data.pop_front().ok_or(DecodeError {})?, data.pop_front().ok_or(DecodeError {})?, data.pop_front().ok_or(DecodeError {})?];
127        Ok(Self::from_be_bytes(r))
128    }
129}
130
131
132
133impl ProtocolSegment for f32 {
134    fn encode(self) -> Vec<u8> {
135        let mut v : Vec<u8> = Vec::with_capacity(4);
136        let bytes = self.to_be_bytes();
137        v.push(bytes[0]); // flip the byte order so it pops in properly
138        v.push(bytes[1]);
139        v.push(bytes[2]);
140        v.push(bytes[3]);
141        v
142    }
143
144    fn decode(data : &mut VecDeque<u8>) -> Result<Self, DecodeError> {
145        let r = [data.pop_front().ok_or(DecodeError {})?, data.pop_front().ok_or(DecodeError {})?, data.pop_front().ok_or(DecodeError {})?, data.pop_front().ok_or(DecodeError {})?];
146        Ok(Self::from_be_bytes(r))
147    }
148}
149
150impl ProtocolSegment for String {
151    fn encode(self) -> Vec<u8> {
152        let mut v = Vec::with_capacity(self.len() + 2); // space enough for me and my size information
153        v.append(&mut Vec::from((self.len() as u16).to_be_bytes()));
154        v.append(&mut Vec::from(self.clone().into_bytes()));
155        v
156    }
157
158    fn decode(data : &mut VecDeque<u8>) -> Result<Self, DecodeError> {
159        let len : [u8; 2] = [data.pop_front().ok_or(DecodeError {})?, data.pop_front().ok_or(DecodeError {})?];
160        let len = u16::from_be_bytes(len);
161        if data.len() >= len.into() {
162            let dat = data.drain(0..len.into()).collect();
163            match String::from_utf8(dat) {
164                Ok(str) => Ok(str),
165                Err(_) => {Err(DecodeError{})}
166            }
167        }
168        else {
169            Err(DecodeError{})
170        }
171    }
172}
173
174pub fn protocol_encode<T : ProtocolSegment>(e : T) -> Vec<u8> { // enforces the trait bounds
175    e.encode()
176}
177
178pub fn protocol_decode<T : ProtocolSegment>(d : &mut VecDeque<u8>) -> Result<T, DecodeError> {
179    T::decode(d)
180}