diff --git a/2021/src/lib.rs b/2021/src/lib.rs index f991069..8b658ce 100644 --- a/2021/src/lib.rs +++ b/2021/src/lib.rs @@ -1,6 +1,7 @@ use std::io::Read; use std::str::FromStr; use std::fs::File; +use std::ops::{Index, IndexMut}; use color_eyre::{eyre}; use eyre::eyre; @@ -69,3 +70,52 @@ pub trait IterExt: Iterator { } impl IterExt for I {} + + +// 2d container, functions kind of like a "vec of vecs" but all data is stored in a single vec for memory contiguity +pub struct Vec2 { + data: Vec, + columns: usize, +} + + +impl Vec2 { + fn new(columns: usize) -> Vec2 { + Vec2 {data: Vec::::new(), columns} + } + + fn push>(&mut self, row: S) { + self.data.extend(row.into_iter()); + } + + // This works just fine, for some reason + fn rows(&self) -> impl Iterator { + self.data.chunks_exact(self.columns) + } + + // But this doesn't? + fn rows_mut(&mut self) -> impl Iterator { + self.data.chunks_exact_mut(self.columns) + } + + fn values(&self) -> impl Iterator { + self.data.iter() + } +} + + +impl Index for Vec2 { + type Output = [T]; + fn index(&self, index: usize) -> &Self::Output { + let start = self.columns * index; + &self.data[start..(start + self.columns)] + } +} + + +impl IndexMut for Vec2 { + fn index_mut(&mut self, index: usize) -> &mut Self::Output { + let start = self.columns * index; + &mut self.data[start..(start + self.columns)] + } +}