From a187719d7df3401598aebdbd979797be2e42f83d Mon Sep 17 00:00:00 2001 From: Maciej Jur Date: Sat, 10 Dec 2022 01:16:56 +0100 Subject: [PATCH] 2022 rust WIP matrix thing --- 2022/rust/src/utils.rs | 3 ++ 2022/rust/src/utils/matrix.rs | 71 +++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 2022/rust/src/utils/matrix.rs diff --git a/2022/rust/src/utils.rs b/2022/rust/src/utils.rs index 4f9aa8a..4b5b02e 100644 --- a/2022/rust/src/utils.rs +++ b/2022/rust/src/utils.rs @@ -1,7 +1,10 @@ +pub mod matrix; + use std::fs::File; use std::io::{BufRead, BufReader}; use std::path::Path; + #[allow(dead_code)] pub enum Source { Scratch, Day(i32) } diff --git a/2022/rust/src/utils/matrix.rs b/2022/rust/src/utils/matrix.rs new file mode 100644 index 0000000..4414102 --- /dev/null +++ b/2022/rust/src/utils/matrix.rs @@ -0,0 +1,71 @@ +#![allow(dead_code)] +use std::ops::{Deref, Index, IndexMut}; + + +pub struct Matrix { + array: Vec, + rows: usize, + cols: usize, +} + +impl Matrix { + pub fn new(rows: usize, cols: usize) -> Self { + Self { rows, cols, array: vec![Default::default(); rows * cols] } + } +} + +impl Matrix { + pub fn reshape(mut self, rows: usize, cols: usize) -> Matrix { + assert_eq!(self.rows * self.cols, rows * cols); + self.rows = rows; + self.cols = cols; + self + } + + #[inline(always)] + fn get_at(&self, row: usize, col: usize) -> &T { + let offset = self.get_offset(row, col); + &self.array[offset] + } + + #[inline(always)] + fn get_mut_at(&mut self, row: usize, col: usize) -> &mut T { + let offset = self.get_offset(row, col); + &mut self.array[offset] + } + + #[inline(always)] + fn set_at(&mut self, row: usize, col: usize, value: T) { + let offset = self.get_offset(row, col); + self.array[offset] = value; + } + + #[inline(always)] + fn get_offset(&self, row: usize, col: usize) -> usize { + row * self.cols + col + } +} + +impl Index for Matrix { + type Output = T; + + #[inline(always)] + fn index(&self, index: usize) -> &Self::Output { + &self.array[index] + } +} + +impl IndexMut for Matrix { + #[inline(always)] + fn index_mut(&mut self, index: usize) -> &mut Self::Output { + &mut self.array[index] + } +} + +impl Deref for Matrix { + type Target = Vec; + + fn deref(&self) -> &Self::Target { + &self.array + } +}