From ee0c9dceab6bd083f5e58b828caaaa30f7527746 Mon Sep 17 00:00:00 2001 From: Vinzenz Schroeter Date: Sun, 2 Jun 2024 14:03:40 +0200 Subject: [PATCH] add some iterators --- crates/servicepoint/src/bit_vec.rs | 27 +++++++++++++++++++++++++++ crates/servicepoint/src/byte_grid.rs | 26 ++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/crates/servicepoint/src/bit_vec.rs b/crates/servicepoint/src/bit_vec.rs index 7b2d5c1..5af9da8 100644 --- a/crates/servicepoint/src/bit_vec.rs +++ b/crates/servicepoint/src/bit_vec.rs @@ -101,6 +101,14 @@ impl BitVec { self.data.is_empty() } + /// Get an iterator over every bit in the vector + pub fn iter(&self) -> Iter { + Iter { + bit_vec: self, + index: 0, + } + } + /// Calculates the byte index and bitmask for a specific bit in the vector fn get_indexes(&self, bit_index: usize) -> (usize, u8) { assert!( @@ -143,6 +151,25 @@ impl From<&[u8]> for BitVec { } } +pub struct Iter<'t> { + bit_vec: &'t BitVec, + index: usize, +} + +impl<'t> Iterator for Iter<'t> { + type Item = bool; + + fn next(&mut self) -> Option { + if self.index >= self.bit_vec.size { + return None; + } + + let result = Some(self.bit_vec.get(self.index)); + self.index += 1; + result + } +} + #[cfg(test)] mod tests { use crate::{BitVec, DataRef}; diff --git a/crates/servicepoint/src/byte_grid.rs b/crates/servicepoint/src/byte_grid.rs index d6d5759..7b3f78b 100644 --- a/crates/servicepoint/src/byte_grid.rs +++ b/crates/servicepoint/src/byte_grid.rs @@ -43,6 +43,13 @@ impl ByteGrid { } } + pub fn iter(&self) -> Iter { + Iter { + byte_grid: self, + index: 0, + } + } + fn check_indexes(&self, x: usize, y: usize) { assert!( x < self.width, @@ -152,6 +159,25 @@ impl RefGrid for ByteGrid { } } +pub struct Iter<'t> { + byte_grid: &'t ByteGrid, + index: usize, +} + +impl<'t> Iterator for Iter<'t> { + type Item = u8; + + fn next(&mut self) -> Option { + if self.index >= self.byte_grid.data.len() { + return None; + } + + let result = self.byte_grid.data[self.index]; + self.index += 1; + Some(result) + } +} + #[cfg(test)] mod tests { use crate::{ByteGrid, DataRef, Grid};