diff options
| author | Max Audron <audron@cocaine.farm> | 2020-04-29 00:00:44 +0200 |
|---|---|---|
| committer | Max Audron <audron@cocaine.farm> | 2020-04-29 00:00:44 +0200 |
| commit | fc64e11cdd35051a2ea87237f548ae0497a2f7f9 (patch) | |
| tree | c57937731898b0ffd66d1d95bb0f181cae568c37 /src/primitive/signedint.rs | |
| parent | finish parsing of primitive types (diff) | |
refactor everything
Diffstat (limited to 'src/primitive/signedint.rs')
| -rw-r--r-- | src/primitive/signedint.rs | 62 |
1 files changed, 62 insertions, 0 deletions
diff --git a/src/primitive/signedint.rs b/src/primitive/signedint.rs new file mode 100644 index 0000000..4c21a69 --- /dev/null +++ b/src/primitive/signedint.rs @@ -0,0 +1,62 @@ +extern crate byteorder; +use byteorder::{BigEndian, ReadBytesExt}; +use std::io::Cursor; + +use std::convert::TryInto; +use std::result::Result; +use std::vec::Vec; + +use failure::Error; + +use crate::{Deserialize, Serialize}; + +impl Serialize for i64 { + fn serialize(&self) -> Result<Vec<u8>, Error> { + Ok(Vec::from(self.to_be_bytes())) + } +} + +impl Deserialize for i64 { + fn parse(b: &[u8]) -> Result<(usize, Self), Error> { + let mut rdr = Cursor::new(&b[0..8]); + return Ok((8, rdr.read_i64::<BigEndian>()?)); + } +} + +impl Serialize for i32 { + fn serialize(&self) -> Result<Vec<u8>, Error> { + Ok(Vec::from(self.to_be_bytes())) + } +} + +impl Deserialize for i32 { + fn parse(b: &[u8]) -> Result<(usize, Self), Error> { + let mut rdr = Cursor::new(&b[0..4]); + return Ok((4, rdr.read_i32::<BigEndian>()?)); + } +} + +impl Serialize for i16 { + fn serialize(&self) -> Result<Vec<u8>, Error> { + Ok(Vec::from(self.to_be_bytes())) + } +} + +impl Deserialize for i16 { + fn parse(b: &[u8]) -> Result<(usize, Self), Error> { + let mut rdr = Cursor::new(&b[0..2]); + return Ok((2, rdr.read_i16::<BigEndian>()?)); + } +} + +impl Serialize for i8 { + fn serialize(&self) -> Result<Vec<u8>, Error> { + Ok(Vec::from(self.to_be_bytes())) + } +} + +impl Deserialize for i8 { + fn parse(b: &[u8]) -> Result<(usize, Self), Error> { + return Ok((1, b[0].try_into()?)); + } +} |
