Skip to main content

ruxla_ir/
host.rs

1//! Arrays in host memory.
2
3use std::fmt;
4
5use ruxla_kernels::{Buffer, DType, Element, Value, with_buffer, with_dtype};
6
7use crate::error::{Error, Result};
8use crate::shape::{AVal, Shape};
9
10/// An array in host memory: a typed buffer and a shape.
11#[derive(Clone, PartialEq)]
12pub struct HostArray {
13    shape: Shape,
14    buffer: Buffer,
15}
16
17impl HostArray {
18    /// Creates an array from its elements in row-major order.
19    ///
20    /// # Panics
21    ///
22    /// Panics if the number of elements does not match the shape.
23    #[track_caller]
24    pub fn from_vec<T: Element>(data: Vec<T>, shape: impl Into<Shape>) -> Self {
25        Self::from_buffer(Buffer::from_vec(data), shape)
26    }
27
28    /// Creates an array from a buffer.
29    ///
30    /// # Panics
31    ///
32    /// Panics if the number of elements does not match the shape.
33    #[track_caller]
34    pub fn from_buffer(buffer: Buffer, shape: impl Into<Shape>) -> Self {
35        let shape = shape.into();
36        assert_eq!(
37            buffer.len(),
38            shape.size(),
39            "{} elements for shape [{shape}]",
40            buffer.len()
41        );
42        Self { shape, buffer }
43    }
44
45    /// Creates a scalar.
46    pub fn scalar<T: Element>(v: T) -> Self {
47        Self::from_vec(vec![v], Shape::scalar())
48    }
49
50    /// An array filled with `value`, converted to `dtype`.
51    pub fn full(shape: impl Into<Shape>, dtype: DType, value: Value) -> Self {
52        let shape = shape.into();
53        let n = shape.size();
54        with_dtype!(dtype, |T| Self::from_vec(
55            vec![T::from_value(value); n],
56            shape
57        ))
58    }
59
60    /// An array of zeros.
61    pub fn zeros(shape: impl Into<Shape>, dtype: DType) -> Self {
62        Self::full(shape, dtype, Value::Int(0))
63    }
64
65    /// Returns the element type.
66    pub fn dtype(&self) -> DType {
67        self.buffer.dtype()
68    }
69
70    /// Returns the shape.
71    pub fn shape(&self) -> &Shape {
72        &self.shape
73    }
74
75    /// Returns the abstract value.
76    pub fn aval(&self) -> AVal {
77        AVal::new(self.shape.clone(), self.dtype())
78    }
79
80    /// Returns the number of elements.
81    pub fn size(&self) -> usize {
82        self.shape.size()
83    }
84
85    /// Returns the buffer.
86    pub fn buffer(&self) -> &Buffer {
87        &self.buffer
88    }
89
90    /// Returns the buffer, consuming the array.
91    pub fn into_buffer(self) -> Buffer {
92        self.buffer
93    }
94
95    /// Views the elements as `T`.
96    ///
97    /// # Errors
98    ///
99    /// Returns an error if the elements have another type.
100    pub fn as_slice<T: Element>(&self) -> Result<&[T]> {
101        self.buffer.as_slice().ok_or_else(|| {
102            Error::Malformed(format!(
103                "cannot read {} elements as {}",
104                self.dtype(),
105                T::DTYPE
106            ))
107        })
108    }
109
110    /// Copies the elements as `T`.
111    ///
112    /// # Errors
113    ///
114    /// Returns an error if the elements have another type.
115    pub fn to_vec<T: Element>(&self) -> Result<Vec<T>> {
116        self.as_slice().map(<[T]>::to_vec)
117    }
118
119    /// Returns element `i` (in row-major order), widened.
120    pub fn get(&self, i: usize) -> Value {
121        with_buffer!(&self.buffer, |v| v[i].to_value())
122    }
123
124    /// Returns the array with its elements converted to `dtype`.
125    pub fn convert(&self, dtype: DType) -> Self {
126        Self {
127            shape: self.shape.clone(),
128            buffer: self.buffer.convert(dtype),
129        }
130    }
131
132    /// Returns the array with another shape of the same size.
133    ///
134    /// # Panics
135    ///
136    /// Panics if the sizes differ.
137    #[track_caller]
138    pub fn reshape(self, shape: impl Into<Shape>) -> Self {
139        Self::from_buffer(self.buffer, shape)
140    }
141
142    /// Returns the native-endian bytes of the elements.
143    pub fn to_bytes(&self) -> Vec<u8> {
144        let mut out = Vec::with_capacity(self.size() * self.dtype().size_in_bytes());
145        with_buffer!(&self.buffer, |v| v
146            .iter()
147            .for_each(|x| x.write_bytes(&mut out)));
148        out
149    }
150
151    /// Creates an array from native-endian bytes.
152    ///
153    /// # Errors
154    ///
155    /// Returns an error if the number of bytes does not match.
156    pub fn from_bytes(bytes: &[u8], shape: impl Into<Shape>, dtype: DType) -> Result<Self> {
157        let shape = shape.into();
158        let size = dtype.size_in_bytes();
159        let n = shape
160            .checked_size()
161            .ok_or_else(|| Error::Malformed(format!("shape [{shape}] is too large")))?;
162        if bytes.len() != n * size {
163            return Err(Error::Malformed(format!(
164                "{} bytes for {dtype}[{shape}]",
165                bytes.len()
166            )));
167        }
168        Ok(with_dtype!(dtype, |T| Self::from_vec(
169            bytes
170                .chunks_exact(size)
171                .map(T::read_bytes)
172                .collect::<Vec<T>>(),
173            shape
174        )))
175    }
176}
177
178impl fmt::Debug for HostArray {
179    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180        write!(f, "{}[{}] ", self.dtype(), self.shape)?;
181        with_buffer!(&self.buffer, |v| write!(f, "{v:?}"))
182    }
183}