1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
extern crate byteorder;
use byteorder::{BigEndian, ReadBytesExt};
use std::io::Cursor;
use std::result::Result;
use std::vec::Vec;
use crate::error::ProtocolError;
use crate::{deserialize::*, serialize::*};
impl Serialize for bool {
fn serialize(&self) -> Result<Vec<u8>, ProtocolError> {
Ok({
let i = *self as i8;
Vec::from(i.to_be_bytes())
})
}
}
impl Deserialize for bool {
fn parse(b: &[u8]) -> Result<(usize, Self), ProtocolError> {
if b[0] == 0 {
Ok((1, false))
} else if b[0] == 1 {
Ok((1, true))
} else {
Err(ProtocolError::BoolOutOfRange)
}
}
}
impl Serialize for u64 {
fn serialize(&self) -> Result<Vec<u8>, ProtocolError> {
Ok(Vec::from(self.to_be_bytes()))
}
}
impl Deserialize for u64 {
fn parse(b: &[u8]) -> Result<(usize, Self), ProtocolError> {
let mut rdr = Cursor::new(&b[0..8]);
return Ok((8, rdr.read_u64::<BigEndian>()?));
}
}
impl Serialize for u32 {
fn serialize(&self) -> Result<Vec<u8>, ProtocolError> {
Ok(Vec::from(self.to_be_bytes()))
}
}
impl Deserialize for u32 {
fn parse(b: &[u8]) -> Result<(usize, Self), ProtocolError> {
let mut rdr = Cursor::new(&b[0..4]);
return Ok((4, rdr.read_u32::<BigEndian>()?));
}
}
impl Serialize for u16 {
fn serialize(&self) -> Result<Vec<u8>, ProtocolError> {
Ok(Vec::from(self.to_be_bytes()))
}
}
impl Deserialize for u16 {
fn parse(b: &[u8]) -> Result<(usize, Self), ProtocolError> {
let mut rdr = Cursor::new(&b[0..2]);
return Ok((2, rdr.read_u16::<BigEndian>()?));
}
}
impl Serialize for u8 {
fn serialize(&self) -> Result<Vec<u8>, ProtocolError> {
Ok(Vec::from(self.to_be_bytes()))
}
}
impl Deserialize for u8 {
fn parse(b: &[u8]) -> Result<(usize, Self), ProtocolError> {
return Ok((1, b[0]));
}
}
|