1use 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#[derive(Clone, PartialEq)]
12pub struct HostArray {
13 shape: Shape,
14 buffer: Buffer,
15}
16
17impl HostArray {
18 #[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 #[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 pub fn scalar<T: Element>(v: T) -> Self {
47 Self::from_vec(vec![v], Shape::scalar())
48 }
49
50 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 pub fn zeros(shape: impl Into<Shape>, dtype: DType) -> Self {
62 Self::full(shape, dtype, Value::Int(0))
63 }
64
65 pub fn dtype(&self) -> DType {
67 self.buffer.dtype()
68 }
69
70 pub fn shape(&self) -> &Shape {
72 &self.shape
73 }
74
75 pub fn aval(&self) -> AVal {
77 AVal::new(self.shape.clone(), self.dtype())
78 }
79
80 pub fn size(&self) -> usize {
82 self.shape.size()
83 }
84
85 pub fn buffer(&self) -> &Buffer {
87 &self.buffer
88 }
89
90 pub fn into_buffer(self) -> Buffer {
92 self.buffer
93 }
94
95 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 pub fn to_vec<T: Element>(&self) -> Result<Vec<T>> {
116 self.as_slice().map(<[T]>::to_vec)
117 }
118
119 pub fn get(&self, i: usize) -> Value {
121 with_buffer!(&self.buffer, |v| v[i].to_value())
122 }
123
124 pub fn convert(&self, dtype: DType) -> Self {
126 Self {
127 shape: self.shape.clone(),
128 buffer: self.buffer.convert(dtype),
129 }
130 }
131
132 #[track_caller]
138 pub fn reshape(self, shape: impl Into<Shape>) -> Self {
139 Self::from_buffer(self.buffer, shape)
140 }
141
142 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 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}