perspective_client/
typed_array.rs1use std::io::Cursor;
14
15use arrow_array::cast::AsArray;
16use arrow_array::types::*;
17use arrow_array::{Array, ArrowPrimitiveType, PrimitiveArray};
18use arrow_buffer::{ArrowNativeType, Buffer, ScalarBuffer};
19use arrow_ipc::reader::StreamReader;
20use arrow_schema::{DataType, TimeUnit};
21use serde::Deserialize;
22use ts_rs::TS;
23
24#[cfg(doc)]
25use crate::View;
26use crate::utils::{ClientError, ClientResult};
27use crate::view::ViewWindow;
28
29#[derive(Clone, Debug, Default, Deserialize, TS)]
32pub struct TypedArrayWindow {
33 #[serde(flatten)]
34 pub view_window: ViewWindow,
35
36 #[serde(default)]
39 pub float32: bool,
40}
41
42impl From<TypedArrayWindow> for ViewWindow {
43 fn from(w: TypedArrayWindow) -> Self {
44 w.view_window
45 }
46}
47
48#[derive(Clone, Debug)]
50pub enum TypedArrayValues {
51 Int32(ScalarBuffer<i32>),
52 UInt32(ScalarBuffer<u32>),
53 Float32(ScalarBuffer<f32>),
54 Float64(ScalarBuffer<f64>),
55 Dictionary {
56 keys: ScalarBuffer<i32>,
57 values: Vec<String>,
58 },
59}
60
61#[derive(Clone, Debug)]
64pub struct TypedArrayColumn {
65 pub name: String,
66 pub values: TypedArrayValues,
67
68 pub validity: Option<Buffer>,
71}
72
73pub(crate) fn decode_typed_arrays(
74 arrow: &[u8],
75 float32: bool,
76) -> ClientResult<Vec<TypedArrayColumn>> {
77 let reader = StreamReader::try_new(Cursor::new(arrow), None)
78 .map_err(|e| ClientError::TypedArrayError(format!("Arrow decode error: {e}")))?;
79
80 let batch = reader
81 .into_iter()
82 .next()
83 .ok_or_else(|| {
84 ClientError::TypedArrayError("Arrow IPC contained no record batches".to_owned())
85 })?
86 .map_err(|e| ClientError::TypedArrayError(format!("Arrow batch error: {e}")))?;
87
88 batch
89 .schema()
90 .fields()
91 .iter()
92 .zip(batch.columns())
93 .map(|(field, column)| {
94 unsafe { zero_invalid_slots(column.as_ref()) };
97 Ok(TypedArrayColumn {
98 name: field.name().clone(),
99 values: decode_values(column.as_ref(), float32)?,
100 validity: column.nulls().map(|nulls| nulls.inner().sliced()),
101 })
102 })
103 .collect()
104}
105
106fn decode_values(column: &dyn Array, float32: bool) -> ClientResult<TypedArrayValues> {
107 Ok(match column.data_type() {
108 DataType::Int8 => {
109 TypedArrayValues::Int32(map_values(column.as_primitive::<Int8Type>(), i32::from))
110 },
111 DataType::UInt8 => {
112 TypedArrayValues::Int32(map_values(column.as_primitive::<UInt8Type>(), i32::from))
113 },
114 DataType::Int16 => {
115 TypedArrayValues::Int32(map_values(column.as_primitive::<Int16Type>(), i32::from))
116 },
117 DataType::UInt16 => {
118 TypedArrayValues::Int32(map_values(column.as_primitive::<UInt16Type>(), i32::from))
119 },
120 DataType::Int32 => {
121 TypedArrayValues::Int32(column.as_primitive::<Int32Type>().values().clone())
122 },
123 DataType::UInt32 => {
124 TypedArrayValues::UInt32(column.as_primitive::<UInt32Type>().values().clone())
125 },
126 DataType::Float32 => {
127 TypedArrayValues::Float32(column.as_primitive::<Float32Type>().values().clone())
128 },
129 DataType::Float64 if float32 => {
130 TypedArrayValues::Float32(map_values(column.as_primitive::<Float64Type>(), |v| {
131 v as f32
132 }))
133 },
134 DataType::Float64 => {
135 TypedArrayValues::Float64(column.as_primitive::<Float64Type>().values().clone())
136 },
137 DataType::Int64 if float32 => {
138 TypedArrayValues::Float32(map_values(column.as_primitive::<Int64Type>(), |v| v as f32))
139 },
140 DataType::Int64 => {
141 TypedArrayValues::Float64(map_values(column.as_primitive::<Int64Type>(), |v| v as f64))
142 },
143 DataType::UInt64 if float32 => {
144 TypedArrayValues::Float32(map_values(column.as_primitive::<UInt64Type>(), |v| {
145 v as f32
146 }))
147 },
148 DataType::UInt64 => {
149 TypedArrayValues::Float64(map_values(column.as_primitive::<UInt64Type>(), |v| {
150 v as f64
151 }))
152 },
153 DataType::Date32 => {
154 TypedArrayValues::Float64(map_values(column.as_primitive::<Date32Type>(), |v| {
155 v as f64 * 86_400_000.0
156 }))
157 },
158 DataType::Timestamp(TimeUnit::Millisecond, _) => TypedArrayValues::Float64(map_values(
159 column.as_primitive::<TimestampMillisecondType>(),
160 |v| v as f64,
161 )),
162 DataType::Boolean => {
163 let typed = column.as_boolean();
164 TypedArrayValues::Int32(
165 (0..typed.len())
166 .map(|i| i32::from(typed.is_valid(i) && typed.value(i)))
167 .collect(),
168 )
169 },
170 DataType::Dictionary(..) => decode_dictionary(column)?,
171 dt => {
172 return Err(ClientError::TypedArrayError(format!(
173 "Unsupported column type for typed array: {dt}"
174 )));
175 },
176 })
177}
178
179fn decode_dictionary(column: &dyn Array) -> ClientResult<TypedArrayValues> {
180 let dict = column.as_dictionary_opt::<Int32Type>().ok_or_else(|| {
181 ClientError::TypedArrayError(format!(
182 "Unsupported dictionary key type for typed array: {}",
183 column.data_type()
184 ))
185 })?;
186
187 let values = dict.values().as_string_opt::<i32>().ok_or_else(|| {
188 ClientError::TypedArrayError(format!(
189 "Unsupported dictionary value type for typed array: {}",
190 dict.values().data_type()
191 ))
192 })?;
193
194 Ok(TypedArrayValues::Dictionary {
195 keys: dict.keys().values().clone(),
196 values: (0..values.len())
197 .map(|i| values.value(i).to_owned())
198 .collect(),
199 })
200}
201
202unsafe fn zero_invalid_slots(column: &dyn Array) {
205 let Some(nulls) = column.nulls() else {
206 return;
207 };
208
209 let data = column.to_data();
210 let width = match data.data_type() {
211 DataType::Dictionary(key, _) => key.primitive_width(),
212 dt => dt.primitive_width(),
213 };
214
215 let Some(width) = width else {
216 return;
217 };
218
219 let bytes = unsafe {
220 std::slice::from_raw_parts_mut(
221 (data.buffers()[0].as_ptr() as *mut u8).add(data.offset() * width),
222 data.len() * width,
223 )
224 };
225
226 let mut next = 0;
227 for (start, end) in nulls.valid_slices() {
228 bytes[next * width..start * width].fill(0);
229 next = end;
230 }
231
232 bytes[next * width..].fill(0);
233}
234
235fn map_values<T, U>(array: &PrimitiveArray<T>, f: impl Fn(T::Native) -> U) -> ScalarBuffer<U>
236where
237 T: ArrowPrimitiveType,
238 U: ArrowNativeType,
239{
240 array.values().iter().map(|&v| f(v)).collect()
241}