Skip to content

Instantly share code, notes, and snippets.

@didicodethat
Last active March 24, 2023 17:20
Show Gist options
  • Save didicodethat/c82bd2e8415af505adf45a4e9502bfbf to your computer and use it in GitHub Desktop.
Save didicodethat/c82bd2e8415af505adf45a4e9502bfbf to your computer and use it in GitHub Desktop.
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