use crate::strategies::*;
use crate::{ MatrixExt, MatrixMutExt };
use crate::req::MatrixExtFromIter;
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Hash, Clone, Debug)]
pub struct Access<'a, M: MatrixExt, S: AccessStrategy<M>>{
matrix: &'a M,
pub strategy: S,
}
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Hash, Debug)]
pub struct AccessMut<'a, M: MatrixExt, S: AccessStrategy<M>>{
matrix: &'a mut M,
strategy: S,
}
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Default, Hash, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug)]
pub struct Observer {
rows: usize,
cols: usize
}
impl<'a, M: MatrixExt, S: AccessStrategy<M>> Access<'a, M, S> {
pub(crate) fn new(matrix: &'a M, strategy: S) -> Self {
Self { matrix, strategy }
}
pub fn clone_into2(&self) -> M
where M: for<'b> MatrixExtFromIter<&'b M::Element> {
MatrixExtFromIter::from_iter(self.iter(), self.num_cols())
}
}
impl<'a, M: MatrixMutExt, S: AccessStrategy<M>> Access<'a, M, S> {
pub fn clone_into(&self) -> M
where
M: Clone,
<M as MatrixExt>::Element: Clone
{
self.matrix.duplicate()
}
}
impl<'a, M: MatrixMutExt, S: AccessStrategy<M>> AccessMut<'a, M, S> {
pub(crate) fn new(matrix: &'a mut M, strategy: S) -> Self {
Self { matrix, strategy }
}
pub fn clone_into(&self) -> M
where
M: Clone,
<M as MatrixExt>::Element: Clone
{
self.matrix.duplicate()
}
}
impl Observer {
pub fn new(dimensions: (usize, usize)) -> Self {
Self {
rows: dimensions.0,
cols: dimensions.1
}
}
pub fn update_dimensions(&mut self, s: &dyn AccessStrategy<Self>) {
self.rows = s.nrows(&self);
self.cols = s.ncols(&self);
}
}
impl MatrixExt for Observer {
type Element = ();
fn num_rows(&self) -> usize { self.rows }
fn num_cols(&self) -> usize { self.cols }
fn get(&self, i: usize, j: usize) -> Option<&()> {
if self.check(i, j) {
return Some(&())
}
None
}
}
impl<'a, M: MatrixExt, S: AccessStrategy<M>> MatrixExt for Access<'a, M, S> {
type Element = <M as MatrixExt>::Element;
fn num_rows(&self) -> usize { self.strategy.nrows(&self.matrix) }
fn num_cols(&self) -> usize { self.strategy.ncols(&self.matrix) }
fn get(&self, row: usize, column: usize) -> Option<&Self::Element> {
let (i, j) = self.strategy.access(&self.matrix, row, column)?;
self.matrix.get(i, j)
}
}
impl<'a, M: MatrixMutExt, S: AccessStrategy<M>> MatrixExt for AccessMut<'a, M, S> {
type Element = M::Element;
fn num_rows(&self) -> usize { self.strategy.nrows(&self.matrix) }
fn num_cols(&self) -> usize { self.strategy.ncols(&self.matrix) }
fn get(&self, row: usize, column: usize) -> Option<&Self::Element> {
let (i, j) = self.strategy.access(&self.matrix, row, column)?;
self.matrix.get(i, j)
}
}
impl<'a, M: MatrixMutExt, S: AccessStrategy<M>> MatrixMutExt for AccessMut<'a, M, S> {
fn get_mut(&mut self, row: usize, column: usize) -> Option<&mut Self::Element> {
let (i, j) = self.strategy.access(&self.matrix, row, column)?;
self.matrix.get_mut(i, j)
}
}