aboutsummaryrefslogtreecommitdiff
path: root/src/protocol/primitive/unsignedint.rs
diff options
context:
space:
mode:
authorMax Audron <audron@cocaine.farm>2020-04-25 19:35:29 +0200
committerMax Audron <audron@cocaine.farm>2020-04-25 19:35:29 +0200
commitc546e2ef6c69bb1c6a86093f3cc7b2dab20d6ac4 (patch)
tree5f761765863f39405a3ae6e27cb865ead6be2e38 /src/protocol/primitive/unsignedint.rs
parentfinish FramedCodec (diff)
finish parsing of primitive types
Diffstat (limited to '')
-rw-r--r--src/protocol/primitive/unsignedint.rs81
1 files changed, 81 insertions, 0 deletions
diff --git a/src/protocol/primitive/unsignedint.rs b/src/protocol/primitive/unsignedint.rs
new file mode 100644
index 0000000..5b42e3c
--- /dev/null
+++ b/src/protocol/primitive/unsignedint.rs
@@ -0,0 +1,81 @@
+extern crate byteorder;
+use byteorder::{BigEndian, ReadBytesExt};
+use std::io::Cursor;
+
+use std::result::Result;
+use std::vec::Vec;
+
+use failure::Error;
+
+use crate::protocol::error::ProtocolError;
+use crate::protocol::primitive::{deserialize, serialize};
+
+impl serialize::Serialize for bool {
+ fn serialize(&self) -> Result<Vec<u8>, Error> {
+ Ok({
+ let i = *self as i8;
+ Vec::from(i.to_be_bytes())
+ })
+ }
+}
+impl deserialize::Deserialize for bool {
+ fn parse(b: &[u8]) -> Result<(usize, Self), Error> {
+ if b[0] == 0 {
+ return Ok((1, false));
+ } else if b[0] == 1 {
+ return Ok((1, true));
+ } else {
+ bail!(ProtocolError::BoolOutOfRange);
+ };
+ }
+}
+impl serialize::Serialize for u64 {
+ fn serialize(&self) -> Result<Vec<u8>, Error> {
+ Ok(Vec::from(self.to_be_bytes()))
+ }
+}
+
+impl deserialize::Deserialize for u64 {
+ fn parse(b: &[u8]) -> Result<(usize, Self), Error> {
+ let mut rdr = Cursor::new(&b[0..8]);
+ return Ok((8, rdr.read_u64::<BigEndian>()?));
+ }
+}
+
+impl serialize::Serialize for u32 {
+ fn serialize(&self) -> Result<Vec<u8>, Error> {
+ Ok(Vec::from(self.to_be_bytes()))
+ }
+}
+
+impl deserialize::Deserialize for u32 {
+ fn parse(b: &[u8]) -> Result<(usize, Self), Error> {
+ let mut rdr = Cursor::new(&b[0..4]);
+ return Ok((4, rdr.read_u32::<BigEndian>()?));
+ }
+}
+
+impl serialize::Serialize for u16 {
+ fn serialize(&self) -> Result<Vec<u8>, Error> {
+ Ok(Vec::from(self.to_be_bytes()))
+ }
+}
+
+impl deserialize::Deserialize for u16 {
+ fn parse(b: &[u8]) -> Result<(usize, Self), Error> {
+ let mut rdr = Cursor::new(&b[0..2]);
+ return Ok((2, rdr.read_u16::<BigEndian>()?));
+ }
+}
+
+impl serialize::Serialize for u8 {
+ fn serialize(&self) -> Result<Vec<u8>, Error> {
+ Ok(Vec::from(self.to_be_bytes()))
+ }
+}
+
+impl deserialize::Deserialize for u8 {
+ fn parse(b: &[u8]) -> Result<(usize, Self), Error> {
+ return Ok((1, b[0]));
+ }
+}