Last active
July 29, 2020 18:23
-
-
Save BoxyUwU/a7861d2bf7d201d5ede5d2b8d6378f23 to your computer and use it in GitHub Desktop.
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
fn main() { | |
let mut my_vec = vec![0, 1, 2, 3, 4, 5]; | |
let mut my_iter = MyIterator::new(&mut my_vec); | |
// this prints out (0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, None), None | |
while let Some((ref mut left, ref mut right)) = my_iter.next() { | |
println!("{:?}, {:?}", left, right); | |
} | |
} | |
pub struct MyIterator<'vector, T> { | |
data: &'vector mut [T], | |
count: usize, | |
} | |
impl<'vector, T> MyIterator<'vector, T> { | |
pub fn new(vec: &'vector mut Vec<T>) -> Self { | |
Self { | |
data: vec, | |
count: 0, | |
} | |
} | |
#[allow(clippy::should_implement_trait)] | |
pub fn next(&mut self) -> Option<(&mut T, Option<&mut T>)> { | |
if self.count + 1 > self.data.len() { | |
return None; | |
} | |
if self.data.len() == 1 { | |
self.count += 1; | |
return Some((self.data.first_mut().unwrap(), None)); | |
} | |
let (left, right) = self.data.split_at_mut(self.count + 1); | |
let first = left.last_mut(); | |
let second = right.first_mut(); | |
self.count += 1; | |
Some((first.unwrap(), second)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment