Last active
March 24, 2023 17:20
-
-
Save didicodethat/c82bd2e8415af505adf45a4e9502bfbf 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
struct TwoWayRange{ | |
start: i32, | |
end: i32, | |
step: i32, | |
current: i32 | |
} | |
enum TwoWayRangeError { | |
ZeroStep | |
} | |
impl TwoWayRange { | |
fn new(start: i32, end: i32, step: i32) -> Result<Self,TwoWayRangeError> { | |
if step == 0 { | |
return Err(TwoWayRangeError::ZeroStep); | |
} | |
Ok(Self { | |
start, | |
end, | |
step, | |
current: start | |
}) | |
} | |
#[inline] | |
fn do_step(&mut self) -> i32 { | |
let before = self.current; | |
self.current += self.step; | |
return before; | |
} | |
} | |
impl Iterator for TwoWayRange { | |
type Item = i32; | |
fn next(&mut self) -> Option<Self::Item> { | |
if self.start > self.end { | |
if self.current > self.end { | |
Some(self.do_step()) | |
} else { | |
None | |
} | |
} else { | |
if self.current < self.end { | |
Some(self.do_step()) | |
} else { | |
None | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment