concision_linear/model/layout/
layout.rs

1/*
2   Appellation: layout <module>
3   Contrib: FL03 <jo3mccain@icloud.com>
4*/
5use crate::model::layout::{features, Features};
6use core::borrow::Borrow;
7use nd::{Dimension, RemoveAxis, ShapeBuilder, ShapeError};
8
9#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
10#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
11
12pub struct Layout<D = nd::Ix2> {
13    pub(crate) dim: D,
14    pub(crate) features: Features,
15}
16
17impl<D> Layout<D>
18where
19    D: Dimension,
20{
21    pub fn new(dim: D) -> Self
22    where
23        D: RemoveAxis,
24    {
25        Self::from_dim(dim).expect("Invalid dimension")
26    }
27
28    pub fn from_dim(dim: D) -> Result<Self, ShapeError> {
29        let features = features(dim.clone())?;
30        Ok(Self { dim, features })
31    }
32
33    pub fn from_shape<Sh>(shape: Sh) -> Self
34    where
35        D: RemoveAxis,
36        Sh: ShapeBuilder<Dim = D>,
37    {
38        let shape = shape.into_shape();
39        let dim = shape.raw_dim().clone();
40        let features = Features::from_shape(shape);
41        Self { dim, features }
42    }
43
44    pub fn with_shape<E, Sh>(self, shape: Sh) -> Layout<E>
45    where
46        E: RemoveAxis,
47        Sh: ShapeBuilder<Dim = E>,
48    {
49        let shape = shape.into_shape();
50        let dim = shape.raw_dim().clone();
51        let features = Features::from_shape(dim.clone());
52        Layout { dim, features }
53    }
54
55    pub fn as_slice(&self) -> &[usize] {
56        self.dim.slice()
57    }
58
59    pub fn as_mut_slice(&mut self) -> &mut [usize] {
60        self.dim.slice_mut()
61    }
62
63    pub fn dim(&self) -> D {
64        self.dim.clone()
65    }
66
67    pub fn features(&self) -> Features {
68        self.features
69    }
70
71    pub fn into_dimensionality<E>(self, dim: E) -> Result<Layout<E>, ShapeError>
72    where
73        E: Dimension,
74    {
75        Layout::from_dim(dim)
76    }
77
78    pub fn ndim(&self) -> usize {
79        self.dim.ndim()
80    }
81
82    pub fn pattern(&self) -> D::Pattern
83    where
84        D: Copy,
85    {
86        self.dim.into_pattern()
87    }
88}
89
90impl<D> Borrow<D> for Layout<D>
91where
92    D: Dimension,
93{
94    fn borrow(&self) -> &D {
95        &self.dim
96    }
97}
98
99impl<D> Borrow<Features> for Layout<D>
100where
101    D: Dimension,
102{
103    fn borrow(&self) -> &Features {
104        &self.features
105    }
106}
107
108impl<D> PartialEq<D> for Layout<D>
109where
110    D: Dimension,
111{
112    fn eq(&self, other: &D) -> bool {
113        self.dim.eq(other)
114    }
115}
116
117impl<D> PartialEq<Features> for Layout<D>
118where
119    D: Dimension,
120{
121    fn eq(&self, other: &Features) -> bool {
122        self.features.eq(other)
123    }
124}