Last active
November 2, 2018 19:59
-
-
Save aakilfernandes/7d6258ee18f91e5399f90239c6bf65b4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[derive(Debug, PartialEq)] | |
enum Error { | |
TooBig | |
} | |
type Bytes = [u8]; | |
struct Fixed { | |
length: u32 | |
} | |
impl<'a> Fixed { | |
pub fn new(length: u32) -> Fixed { | |
Fixed { | |
length: length | |
} | |
} | |
pub fn length(&self) -> u32 { | |
self.length | |
} | |
pub fn encode(&self, decoded: &'a Bytes) -> Result<&'a Bytes, Error> { | |
if decoded.len() > self.length() as usize { | |
Err(Error::TooBig) | |
} else { | |
Ok(&decoded) | |
} | |
} | |
pub fn decode(&self, decoded: &'a Bytes) -> Result<&'a Bytes, Error> { | |
if decoded.len() > self.length() as usize { | |
Err(Error::TooBig) | |
} else { | |
Ok(&decoded) | |
} | |
} | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::*; | |
#[test] | |
fn fixed_0() { | |
let length = 0; | |
let fixed = Fixed::new(length); | |
let encoded: [u8; 0] = []; | |
let decoded: [u8; 0] = []; | |
assert_eq!(fixed.length(), length); | |
assert_eq!(fixed.encode(&decoded).unwrap(), &encoded); | |
assert_eq!(fixed.decode(&encoded).unwrap(), &decoded); | |
assert_eq!(fixed.decode(&encoded).unwrap(), &decoded); | |
assert_eq!(fixed.encode(&[1]).unwrap(), &decoded); | |
assert_eq!(fixed.encode(&[1]).err(), Some(Error::TooBig)); //passes | |
assert_eq!(fixed.encode(&[1]), Error::TooBig); //fails | |
assert_eq!(fixed.encode(&[1]), Err(Error::TooBig)); //also fails | |
} | |
#[test] | |
fn fixed_1() { | |
let length = 1; | |
let fixed = Fixed::new(length); | |
let encoded: [u8; 1] = [1]; | |
let decoded: [u8; 1] = [1]; | |
assert_eq!(fixed.length(), length); | |
assert_eq!(fixed.encode(&decoded).unwrap(), &encoded); | |
assert_eq!(fixed.decode(&encoded).unwrap(), &decoded); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment