1use std::collections::HashMap;
6use std::sync::Arc;
7
8use arrow_array::{Array, ArrayRef, StructArray};
9use arrow_buffer::NullBufferBuilder;
10use arrow_schema::{ArrowError, DataType, Fields};
11
12use crate::reader::tape::{Tape, TapeElement};
13use crate::reader::{ArrayDecoder, DecoderContext, StructMode};
14
15struct FieldTapePositions {
18 data: Vec<u32>,
19 row_count: usize,
20}
21
22impl FieldTapePositions {
23 fn new() -> Self {
24 Self {
25 data: Vec::new(),
26 row_count: 0,
27 }
28 }
29
30 fn resize(&mut self, field_count: usize, row_count: usize) -> Result<(), ArrowError> {
31 let total_len = field_count.checked_mul(row_count).ok_or_else(|| {
32 ArrowError::JsonError(format!(
33 "FieldTapePositions buffer size overflow for rows={row_count} fields={field_count}"
34 ))
35 })?;
36 self.data.clear();
37 self.data.resize(total_len, 0);
38 self.row_count = row_count;
39 Ok(())
40 }
41
42 fn try_set(&mut self, field_idx: usize, row_idx: usize, pos: u32) -> Option<()> {
43 let idx = field_idx
44 .checked_mul(self.row_count)?
45 .checked_add(row_idx)?;
46 *self.data.get_mut(idx)? = pos;
47 Some(())
48 }
49
50 fn set(&mut self, field_idx: usize, row_idx: usize, pos: u32) {
51 self.data[field_idx * self.row_count + row_idx] = pos;
52 }
53
54 fn field_positions(&self, field_idx: usize) -> &[u32] {
55 let start = field_idx * self.row_count;
56 &self.data[start..start + self.row_count]
57 }
58}
59
60pub struct StructArrayDecoder {
61 data_type: DataType,
62 decoders: Vec<Box<dyn ArrayDecoder>>,
63 strict_mode: bool,
64 ignore_type_conflicts: bool,
65 is_nullable: bool,
66 struct_mode: StructMode,
67 field_name_to_index: Option<HashMap<String, usize>>,
68 field_tape_positions: FieldTapePositions,
69}
70
71impl StructArrayDecoder {
72 pub fn new(
73 ctx: &DecoderContext,
74 data_type: &DataType,
75 is_nullable: bool,
76 ) -> Result<Self, ArrowError> {
77 let fields = struct_fields(data_type);
78 let decoders = fields
79 .iter()
80 .map(|f| {
81 let nullable = f.is_nullable() || is_nullable;
85 ctx.make_decoder(f, nullable)
86 })
87 .collect::<Result<Vec<_>, ArrowError>>()?;
88
89 let struct_mode = ctx.struct_mode();
90 let field_name_to_index = if struct_mode == StructMode::ObjectOnly {
91 build_field_index(fields)
92 } else {
93 None
94 };
95
96 Ok(Self {
97 data_type: data_type.clone(),
98 decoders,
99 strict_mode: ctx.strict_mode(),
100 ignore_type_conflicts: ctx.ignore_type_conflicts(),
101 is_nullable,
102 struct_mode,
103 field_name_to_index,
104 field_tape_positions: FieldTapePositions::new(),
105 })
106 }
107}
108
109impl ArrayDecoder for StructArrayDecoder {
110 fn decode(&mut self, tape: &Tape<'_>, pos: &[u32]) -> Result<ArrayRef, ArrowError> {
111 let fields = struct_fields(&self.data_type);
112 let row_count = pos.len();
113 let field_count = fields.len();
114 self.field_tape_positions.resize(field_count, row_count)?;
115 let mut nulls = self.is_nullable.then(|| NullBufferBuilder::new(pos.len()));
116
117 {
118 match self.struct_mode {
121 StructMode::ObjectOnly => {
122 for (row, p) in pos.iter().enumerate() {
123 let end_idx = match (tape.get(*p), nulls.as_mut()) {
124 (TapeElement::StartObject(end_idx), None) => end_idx,
125 (TapeElement::StartObject(end_idx), Some(nulls)) => {
126 nulls.append_non_null();
127 end_idx
128 }
129 (TapeElement::Null, Some(nulls)) => {
130 nulls.append_null();
131 continue;
132 }
133 (_, Some(nulls)) if self.ignore_type_conflicts => {
134 nulls.append_null();
135 continue;
136 }
137 (_, _) => return Err(tape.error(*p, "{")),
138 };
139
140 let mut cur_idx = *p + 1;
141 while cur_idx < end_idx {
142 let field_name = match tape.get(cur_idx) {
144 TapeElement::String(s) => tape.get_string(s),
145 _ => return Err(tape.error(cur_idx, "field name")),
146 };
147
148 let field_idx = match &self.field_name_to_index {
150 Some(map) => map.get(field_name).copied(),
151 None => fields.iter().position(|x| x.name() == field_name),
152 };
153 match field_idx {
154 Some(field_idx) => {
155 self.field_tape_positions.set(field_idx, row, cur_idx + 1);
156 }
157 None => {
158 if self.strict_mode {
159 return Err(ArrowError::JsonError(format!(
160 "column '{field_name}' missing from schema",
161 )));
162 }
163 }
164 }
165 cur_idx = tape.next(cur_idx + 1, "field value")?;
167 }
168 }
169 }
170 StructMode::ListOnly => {
171 for (row, p) in pos.iter().enumerate() {
172 let end_idx = match (tape.get(*p), nulls.as_mut()) {
173 (TapeElement::StartList(end_idx), None) => end_idx,
174 (TapeElement::StartList(end_idx), Some(nulls)) => {
175 nulls.append_non_null();
176 end_idx
177 }
178 (TapeElement::Null, Some(nulls)) => {
179 nulls.append_null();
180 continue;
181 }
182 (_, Some(nulls)) if self.ignore_type_conflicts => {
183 nulls.append_null();
184 continue;
185 }
186 (_, _) => return Err(tape.error(*p, "[")),
187 };
188
189 let mut cur_idx = *p + 1;
190 let mut entry_idx = 0;
191 while cur_idx < end_idx {
192 self.field_tape_positions
193 .try_set(entry_idx, row, cur_idx)
194 .ok_or_else(|| {
195 ArrowError::JsonError(format!(
196 "found extra columns for {} fields",
197 fields.len()
198 ))
199 })?;
200 entry_idx += 1;
201 cur_idx = tape.next(cur_idx, "field value")?;
203 }
204 if entry_idx != fields.len() {
205 return Err(ArrowError::JsonError(format!(
206 "found {} columns for {} fields",
207 entry_idx,
208 fields.len()
209 )));
210 }
211 }
212 }
213 }
214 }
215
216 let child_arrays = self
217 .decoders
218 .iter_mut()
219 .enumerate()
220 .zip(fields)
221 .map(|((field_idx, d), f)| {
222 let pos = self.field_tape_positions.field_positions(field_idx);
223 d.decode(tape, pos).map_err(|e| match e {
224 ArrowError::JsonError(s) => {
225 ArrowError::JsonError(format!("whilst decoding field '{}': {s}", f.name()))
226 }
227 e => e,
228 })
229 })
230 .collect::<Result<Vec<_>, ArrowError>>()?;
231
232 let nulls = nulls.as_mut().and_then(|x| x.finish());
233
234 for (c, f) in child_arrays.iter().zip(fields) {
235 assert_eq!(c.len(), pos.len());
237 if let Some(a) = c.nulls() {
238 let nulls_valid = f.is_nullable() || nulls.as_ref().is_some_and(|n| n.contains(a));
239
240 if !nulls_valid {
241 return Err(ArrowError::JsonError(format!(
242 "Encountered unmasked nulls in non-nullable StructArray child: {f}"
243 )));
244 }
245 }
246 }
247
248 let array = unsafe {
250 StructArray::new_unchecked_with_length(fields.clone(), child_arrays, nulls, row_count)
251 };
252 Ok(Arc::new(array))
253 }
254}
255
256fn struct_fields(data_type: &DataType) -> &Fields {
257 match &data_type {
258 DataType::Struct(f) => f,
259 _ => unreachable!(),
260 }
261}
262
263fn build_field_index(fields: &Fields) -> Option<HashMap<String, usize>> {
264 const FIELD_INDEX_LINEAR_THRESHOLD: usize = 16;
266 if fields.len() < FIELD_INDEX_LINEAR_THRESHOLD {
267 return None;
268 }
269
270 let mut map = HashMap::with_capacity(fields.len());
271 for (idx, field) in fields.iter().enumerate() {
272 let name = field.name();
273 if !map.contains_key(name) {
274 map.insert(name.clone(), idx);
275 }
276 }
277 Some(map)
278}