add Vec2 to lib.rs

This commit is contained in:
Joseph Montanaro 2021-12-14 11:26:24 -08:00
parent 5bcc40b030
commit 6cc7cb8752

View File

@ -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<I: Iterator> 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<T> {
data: Vec<T>,
columns: usize,
}
impl<T> Vec2<T> {
fn new(columns: usize) -> Vec2<T> {
Vec2 {data: Vec::<T>::new(), columns}
}
fn push<S: IntoIterator<Item=T>>(&mut self, row: S) {
self.data.extend(row.into_iter());
}
// This works just fine, for some reason
fn rows(&self) -> impl Iterator<Item=&[T]> {
self.data.chunks_exact(self.columns)
}
// But this doesn't?
fn rows_mut(&mut self) -> impl Iterator<Item=&mut [T]> {
self.data.chunks_exact_mut(self.columns)
}
fn values(&self) -> impl Iterator<Item=&T> {
self.data.iter()
}
}
impl<T> Index<usize> for Vec2<T> {
type Output = [T];
fn index(&self, index: usize) -> &Self::Output {
let start = self.columns * index;
&self.data[start..(start + self.columns)]
}
}
impl<T> IndexMut<usize> for Vec2<T> {
fn index_mut(&mut self, index: usize) -> &mut Self::Output {
let start = self.columns * index;
&mut self.data[start..(start + self.columns)]
}
}