Created
January 15, 2018 21:43
-
-
Save hashmap/4edfaabd7db8d031403526e3df672de4 to your computer and use it in GitHub Desktop.
lib.rs
This file contains hidden or 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
const SIZE: usize = 2; | |
struct Message(Vec<u8>); | |
impl Message { | |
pub fn new() -> Message { | |
Message (vec![1,2,3,4,5,6,7,8]) | |
} | |
} | |
impl<'a> IntoIterator for &'a Message { | |
type Item = &'a [u8]; | |
type IntoIter = MessageIterator<'a>; | |
fn into_iter(self) -> Self::IntoIter { | |
MessageIterator::new(&self.0) | |
} | |
} | |
struct MessageIterator<'a> { | |
data: &'a [u8], | |
cur : usize, | |
} | |
impl<'a> MessageIterator<'a> { | |
pub fn new(data: &'a [u8]) -> MessageIterator { | |
MessageIterator{data: data, cur : 0} | |
} | |
} | |
impl<'a> Iterator for MessageIterator<'a> { | |
type Item = &'a [u8]; | |
fn next(&mut self) -> Option<Self::Item> { | |
if self.cur >= self.data.len() { | |
return None; | |
} | |
self.cur += SIZE; | |
Some(&self.data[self.cur - SIZE..self.cur]) | |
} | |
} | |
#[cfg(test)] | |
mod test { | |
use super::*; | |
#[test] | |
fn iterator_test() { | |
let msg = Message::new(); | |
let mut cnt = 1; | |
for bl in msg.into_iter() { | |
assert_eq!(cnt, bl[0]); | |
cnt += SIZE as u8; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment