1use crate::address_bound::{AddressBound, AddressIterator};
2use crate::addressable::Addressable;
3use std::io::Error;
4
5pub trait Tensor<T, A: Addressable> {
7    fn new<F>(bounds: AddressBound<A>, address_value_converter: F) -> Self
9    where
10        F: Fn(A) -> T;
11    fn get(&self, address: &A) -> Option<&T>;
14    fn get_mut(&mut self, address: &A) -> Option<&mut T>;
15    fn set(&mut self, address: &A, value: T) -> Result<(), Error>;
17    fn bounds(&self) -> &AddressBound<A>;
19    fn address_iterator<'a>(&'a self) -> AddressIterator<A>
22    where
23        T: 'a,
24    {
25        self.bounds().iter()
26    }
27    fn transform<F, TNew, TENew>(&self, mapping_function: F) -> TENew
29    where
30        F: Fn(&T) -> TNew,
31        TENew: Tensor<TNew, A>,
32    {
33        Tensor::new(self.bounds().clone(), |address| {
34            mapping_function(self.get(&address).unwrap())
35        })
36    }
37    fn transform_by_address<F, TNew, TENew>(&self, mapping_function: F) -> TENew
39    where
40        F: Fn(&A, &T) -> TNew,
41        TENew: Tensor<TNew, A>,
42    {
43        Tensor::new(self.bounds().clone(), |address| {
44            mapping_function(&address, self.get(&address).unwrap())
45        })
46    }
47    fn transform_in_place<F>(&mut self, mapping_function: F)
50    where
51        F: Fn(&mut T),
52    {
53        self.bounds().iter().for_each(|address| {
54            mapping_function(self.get_mut(&address).unwrap());
55        });
56    }
57
58    fn transform_by_address_in_place<F>(&mut self, mapping_function: F)
61    where
62        F: Fn(&A, &mut T),
63    {
64        self.bounds().iter().for_each(|address| {
65            mapping_function(&address, self.get_mut(&address).unwrap());
66        });
67    }
68
69    #[allow(unused)]
72    fn eq(&self, other: &Self) -> bool
73    where
74        T: PartialEq,
75    {
76        if self.bounds() != other.bounds() {
77            return false;
78        }
79        self.address_iterator()
80            .all(|address| self.get(&address).unwrap() == other.get(&address).unwrap())
81    }
82}