1use std::fmt;
4
5use ruxla_kernels::DType;
6
7const INLINE: usize = 6;
9
10#[derive(Clone)]
15pub struct Shape(Dims);
16
17#[derive(Clone)]
18enum Dims {
19 Inline { len: u8, dims: [usize; INLINE] },
20 Heap(Vec<usize>),
21}
22
23impl Shape {
24 #[inline]
26 pub fn scalar() -> Self {
27 Shape(Dims::Inline {
28 len: 0,
29 dims: [0; INLINE],
30 })
31 }
32
33 #[inline]
35 pub fn new(dims: impl AsRef<[usize]>) -> Self {
36 let dims = dims.as_ref();
37 if dims.len() <= INLINE {
38 let mut inline = [0; INLINE];
39 inline[..dims.len()].copy_from_slice(dims);
40 Shape(Dims::Inline {
41 len: dims.len() as u8,
42 dims: inline,
43 })
44 } else {
45 Shape(Dims::Heap(dims.to_vec()))
46 }
47 }
48
49 #[inline]
51 pub fn dims(&self) -> &[usize] {
52 match &self.0 {
53 Dims::Inline { len, dims } => &dims[..usize::from(*len)],
54 Dims::Heap(v) => v,
55 }
56 }
57
58 #[inline]
60 pub fn rank(&self) -> usize {
61 self.dims().len()
62 }
63
64 #[inline]
66 pub fn size(&self) -> usize {
67 self.dims().iter().product()
68 }
69
70 #[inline]
72 pub fn checked_size(&self) -> Option<usize> {
73 self.dims()
74 .iter()
75 .try_fold(1usize, |a, &d| a.checked_mul(d))
76 }
77
78 fn dims_mut(&mut self) -> &mut [usize] {
79 match &mut self.0 {
80 Dims::Inline { len, dims } => &mut dims[..usize::from(*len)],
81 Dims::Heap(v) => v,
82 }
83 }
84
85 #[inline]
91 pub fn set(&mut self, i: usize, d: usize) {
92 self.dims_mut()[i] = d;
93 }
94
95 #[inline]
101 pub fn insert(&mut self, i: usize, d: usize) {
102 if let Dims::Inline { len, dims } = &mut self.0 {
103 let n = usize::from(*len);
104 assert!(i <= n, "insertion index {i} is out of range for rank {n}");
105 if n < INLINE {
106 dims.copy_within(i..n, i + 1);
107 dims[i] = d;
108 *len += 1;
109 return;
110 }
111 }
112 let mut v = self.dims().to_vec();
113 v.insert(i, d);
114 *self = Shape(Dims::Heap(v));
115 }
116
117 #[inline]
119 pub fn push(&mut self, d: usize) {
120 let n = self.rank();
121 self.insert(n, d);
122 }
123
124 #[inline]
130 pub fn remove(&mut self, i: usize) -> usize {
131 match &mut self.0 {
132 Dims::Inline { len, dims } => {
133 let n = usize::from(*len);
134 assert!(i < n, "removal index {i} is out of range for rank {n}");
135 let d = dims[i];
136 dims.copy_within(i + 1..n, i);
137 dims[n - 1] = 0;
140 *len -= 1;
141 d
142 }
143 Dims::Heap(v) => {
144 let d = v.remove(i);
145 if v.len() <= INLINE {
146 *self = Shape::new(&v[..]);
147 }
148 d
149 }
150 }
151 }
152}
153
154impl Default for Shape {
155 #[inline]
156 fn default() -> Self {
157 Shape::scalar()
158 }
159}
160
161impl PartialEq for Shape {
162 #[inline]
163 fn eq(&self, other: &Self) -> bool {
164 match (&self.0, &other.0) {
165 (Dims::Inline { len: a, dims: x }, Dims::Inline { len: b, dims: y }) => {
169 a == b && x.iter().zip(y).fold(true, |eq, (p, q)| eq & (p == q))
170 }
171 _ => self.dims() == other.dims(),
172 }
173 }
174}
175
176impl Eq for Shape {}
177
178impl std::hash::Hash for Shape {
179 #[inline]
180 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
181 self.dims().hash(state);
182 }
183}
184
185impl PartialOrd for Shape {
186 #[inline]
187 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
188 Some(self.cmp(other))
189 }
190}
191
192impl Ord for Shape {
193 #[inline]
194 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
195 self.dims().cmp(other.dims())
196 }
197}
198
199impl fmt::Debug for Shape {
200 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
201 f.debug_tuple("Shape").field(&self.dims()).finish()
202 }
203}
204
205impl std::ops::Deref for Shape {
206 type Target = [usize];
207 #[inline]
208 fn deref(&self) -> &[usize] {
209 self.dims()
210 }
211}
212
213impl From<Vec<usize>> for Shape {
214 #[inline]
215 fn from(v: Vec<usize>) -> Self {
216 if v.len() <= INLINE {
217 Shape::new(v)
218 } else {
219 Shape(Dims::Heap(v))
220 }
221 }
222}
223
224impl From<&[usize]> for Shape {
225 #[inline]
226 fn from(v: &[usize]) -> Self {
227 Shape::new(v)
228 }
229}
230
231impl From<&Vec<usize>> for Shape {
232 #[inline]
233 fn from(v: &Vec<usize>) -> Self {
234 Shape::new(v)
235 }
236}
237
238impl<const N: usize> From<[usize; N]> for Shape {
239 #[inline]
240 fn from(v: [usize; N]) -> Self {
241 Shape::new(v)
242 }
243}
244
245impl<const N: usize> From<&[usize; N]> for Shape {
246 #[inline]
247 fn from(v: &[usize; N]) -> Self {
248 Shape::new(v)
249 }
250}
251
252impl FromIterator<usize> for Shape {
253 fn from_iter<I: IntoIterator<Item = usize>>(iter: I) -> Self {
254 let mut dims = [0; INLINE];
255 let mut len = 0;
256 let mut iter = iter.into_iter();
257 for d in iter.by_ref() {
258 if len == INLINE {
259 let mut v = dims.to_vec();
260 v.push(d);
261 v.extend(iter);
262 return Shape(Dims::Heap(v));
263 }
264 dims[len] = d;
265 len += 1;
266 }
267 Shape(Dims::Inline {
268 len: len as u8,
269 dims,
270 })
271 }
272}
273
274impl fmt::Display for Shape {
275 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276 let dims: Vec<String> = self.dims().iter().map(ToString::to_string).collect();
277 write!(f, "{}", dims.join(","))
278 }
279}
280
281#[derive(Clone, PartialEq, Eq, Hash, Debug)]
283pub struct AVal {
284 pub dtype: DType,
286 pub shape: Shape,
288}
289
290impl AVal {
291 #[inline]
293 pub fn new(shape: impl Into<Shape>, dtype: DType) -> Self {
294 Self {
295 dtype,
296 shape: shape.into(),
297 }
298 }
299
300 #[inline]
302 pub fn scalar(dtype: DType) -> Self {
303 Self::new(Shape::scalar(), dtype)
304 }
305}
306
307impl fmt::Display for AVal {
308 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
309 write!(f, "{}[{}]", self.dtype, self.shape)
310 }
311}
312
313#[cfg(test)]
314mod tests {
315 use super::*;
316
317 #[test]
318 fn editing() {
319 let mut s = Shape::from([2, 3]);
320 s.insert(1, 5);
321 assert_eq!(s.dims(), [2, 5, 3]);
322 s.push(7);
323 s.set(0, 1);
324 assert_eq!(s.dims(), [1, 5, 3, 7]);
325 assert_eq!(s.remove(1), 5);
326 assert_eq!(s.dims(), [1, 3, 7]);
327 let mut big = Shape::from(vec![1; 6]);
328 big.push(2);
329 assert_eq!(big.rank(), 7);
330 assert_eq!(big.remove(6), 2);
331 assert_eq!(big, Shape::from(vec![1; 6]));
332 }
333}