1use std::any::Any;
5
6use vortex_error::VortexExpect;
7use vortex_error::VortexResult;
8use vortex_error::vortex_bail;
9use vortex_error::vortex_ensure;
10
11use crate::ArrayRef;
12use crate::ExecutionCtx;
13use crate::IntoArray;
14use crate::arrays::ChunkedArray;
15use crate::arrays::ConstantArray;
16use crate::arrays::VariantArray;
17use crate::arrays::variant::VariantArraySlotsExt;
18use crate::builders::ArrayBuilder;
19use crate::builtins::ArrayBuiltins;
20use crate::canonical::Canonical;
21use crate::dtype::DType;
22use crate::dtype::Nullability;
23use crate::scalar::Scalar;
24
25pub trait VariantStorageBuilder: Send + 'static {
32 fn as_any_mut(&mut self) -> &mut dyn Any;
34
35 fn len(&self) -> usize;
37
38 fn is_empty(&self) -> bool {
40 self.len() == 0
41 }
42
43 fn finish(self: Box<Self>) -> VortexResult<ArrayRef>;
45}
46
47enum CorePart {
49 Chunk(ArrayRef),
51 Storage(Box<dyn VariantStorageBuilder>),
53 Run(Scalar, usize),
55}
56
57impl CorePart {
58 fn len(&self) -> usize {
59 match self {
60 CorePart::Chunk(chunk) => chunk.len(),
61 CorePart::Storage(storage) => storage.len(),
62 CorePart::Run(_, len) => *len,
63 }
64 }
65
66 fn finish(self) -> VortexResult<ArrayRef> {
67 match self {
68 CorePart::Chunk(chunk) => Ok(chunk),
69 CorePart::Storage(storage) => storage.finish(),
70 CorePart::Run(scalar, len) => Ok(ConstantArray::new(scalar, len).into_array()),
71 }
72 }
73}
74
75enum ShreddedPart {
77 Array(ArrayRef),
79 Unshredded(usize),
81}
82
83pub struct VariantBuilder {
94 dtype: DType,
95 core: Vec<CorePart>,
97 finished_len: usize,
99 shredded: Vec<ShreddedPart>,
100 shredded_len: usize,
102 in_core: bool,
104}
105
106impl VariantBuilder {
107 pub fn new(nullability: Nullability) -> Self {
109 Self {
110 dtype: DType::Variant(nullability),
111 core: Vec::new(),
112 finished_len: 0,
113 shredded: Vec::new(),
114 shredded_len: 0,
115 in_core: false,
116 }
117 }
118
119 pub fn append_variant_array(
124 &mut self,
125 array: &VariantArray,
126 ctx: &mut ExecutionCtx,
127 ) -> VortexResult<()> {
128 self.check_dtype(array.dtype())?;
129 if array.is_empty() {
130 return Ok(());
131 }
132 if self.in_core {
133 let chunk = if array.shredded().is_some() {
137 array.clone().into_array()
138 } else {
139 array.core_storage().clone()
140 };
141 self.push(CorePart::Chunk(chunk));
142 return Ok(());
143 }
144
145 if let Some(shredded) = array.shredded() {
146 if let Some(ShreddedPart::Array(first)) = self
147 .shredded
148 .iter()
149 .find(|part| matches!(part, ShreddedPart::Array(_)))
150 {
151 vortex_ensure!(
152 first.dtype().eq_ignore_nullability(shredded.dtype()),
153 "cannot build a Variant from Variants shredded as {} and as {}",
154 first.dtype(),
155 shredded.dtype()
156 );
157 }
158 self.pad_shredded(self.len());
159 self.shredded_len += shredded.len();
160 self.shredded.push(ShreddedPart::Array(shredded.clone()));
161 }
162 self.in_core = true;
163 let appended = array.core_storage().append_to_builder(self, ctx);
164 self.in_core = false;
165 appended
166 }
167
168 pub fn append_storage<B: VariantStorageBuilder>(
173 &mut self,
174 dtype: &DType,
175 new: impl FnOnce(&DType) -> B,
176 append: impl FnOnce(&mut B) -> VortexResult<()>,
177 ) -> VortexResult<()> {
178 self.check_dtype(dtype)?;
179 let reuse = match self.core.last_mut() {
180 Some(CorePart::Storage(storage)) => storage.as_any_mut().is::<B>(),
181 _ => false,
182 };
183 if !reuse {
184 self.push(CorePart::Storage(Box::new(new(&self.dtype))));
185 }
186 let Some(CorePart::Storage(storage)) = self.core.last_mut() else {
187 vortex_bail!("the Variant storage builder was just installed");
188 };
189 let Some(storage) = storage.as_any_mut().downcast_mut::<B>() else {
190 vortex_bail!("the Variant storage builder has the type it was installed as");
191 };
192 append(storage)
193 }
194
195 pub fn append_n_scalars(&mut self, scalar: &Scalar, n: usize) -> VortexResult<()> {
197 self.check_dtype(scalar.dtype())?;
198 if n == 0 {
199 return Ok(());
200 }
201 let scalar = if scalar.dtype() == &self.dtype {
202 scalar.clone()
203 } else {
204 scalar.cast(&self.dtype)?
205 };
206 if let Some(CorePart::Run(run, len)) = self.core.last_mut()
207 && *run == scalar
208 {
209 *len += n;
210 return Ok(());
211 }
212 self.push(CorePart::Run(scalar, n));
213 Ok(())
214 }
215
216 pub fn finish_into_variant(&mut self) -> VortexResult<VariantArray> {
218 let len = self.len();
219 let shredded = self.finish_shredded(len)?;
220 let mut chunks = std::mem::take(&mut self.core)
221 .into_iter()
222 .map(CorePart::finish)
223 .collect::<VortexResult<Vec<_>>>()?;
224 self.finished_len = 0;
225 let core = match chunks.len() {
226 1 => chunks.remove(0),
227 _ => ChunkedArray::try_new(chunks, self.dtype.clone())?.into_array(),
229 };
230 VariantArray::try_new(core, shredded)
231 }
232
233 fn check_dtype(&self, dtype: &DType) -> VortexResult<()> {
236 vortex_ensure!(
237 dtype.is_variant() && (self.dtype.is_nullable() || !dtype.is_nullable()),
238 "cannot append {dtype} to a builder of {}",
239 self.dtype
240 );
241 Ok(())
242 }
243
244 fn push(&mut self, part: CorePart) {
245 if part.len() == 0 && !matches!(part, CorePart::Storage(_)) {
246 return;
247 }
248 self.finished_len += self.core.last().map_or(0, CorePart::len);
249 self.core.push(part);
250 }
251
252 fn pad_shredded(&mut self, len: usize) {
254 if len > self.shredded_len {
255 self.shredded
256 .push(ShreddedPart::Unshredded(len - self.shredded_len));
257 self.shredded_len = len;
258 }
259 }
260
261 fn finish_shredded(&mut self, len: usize) -> VortexResult<Option<ArrayRef>> {
262 let Some(dtype) = self.shredded.iter().find_map(|part| match part {
263 ShreddedPart::Array(array) => Some(array.dtype().clone()),
264 ShreddedPart::Unshredded(_) => None,
265 }) else {
266 self.shredded.clear();
267 self.shredded_len = 0;
268 return Ok(None);
269 };
270 self.pad_shredded(len);
271 let parts = std::mem::take(&mut self.shredded);
272 self.shredded_len = 0;
273
274 let nullable = parts.iter().any(|part| match part {
275 ShreddedPart::Array(array) => array.dtype().is_nullable(),
276 ShreddedPart::Unshredded(_) => true,
277 });
278 let dtype = if nullable { dtype.as_nullable() } else { dtype };
279 let mut chunks = parts
280 .into_iter()
281 .map(|part| match part {
282 ShreddedPart::Array(array) => {
283 vortex_ensure!(
284 array.dtype().eq_ignore_nullability(&dtype),
285 "cannot build a Variant from Variants shredded as {dtype} and as {}",
286 array.dtype()
287 );
288 if array.dtype() == &dtype {
289 Ok(array)
290 } else {
291 array.cast(dtype.clone())
292 }
293 }
294 ShreddedPart::Unshredded(len) => {
295 Ok(ConstantArray::new(Scalar::null(dtype.clone()), len).into_array())
296 }
297 })
298 .collect::<VortexResult<Vec<_>>>()?;
299 if chunks.len() == 1 {
300 return Ok(chunks.pop());
301 }
302 Ok(Some(ChunkedArray::try_new(chunks, dtype)?.into_array()))
303 }
304}
305
306impl ArrayBuilder for VariantBuilder {
307 fn as_any(&self) -> &dyn Any {
308 self
309 }
310
311 fn as_any_mut(&mut self) -> &mut dyn Any {
312 self
313 }
314
315 fn dtype(&self) -> &DType {
316 &self.dtype
317 }
318
319 fn len(&self) -> usize {
320 self.finished_len + self.core.last().map_or(0, CorePart::len)
321 }
322
323 fn append_zeros(&mut self, n: usize) {
324 let zero = Scalar::zero_value(&self.dtype);
325 self.append_n_scalars(&zero, n)
326 .vortex_expect("the zero value of the builder's dtype can be appended");
327 }
328
329 unsafe fn append_nulls_unchecked(&mut self, n: usize) {
330 let null = Scalar::null(self.dtype.clone());
331 self.append_n_scalars(&null, n)
332 .vortex_expect("a null of the builder's dtype can be appended");
333 }
334
335 fn append_scalar(&mut self, scalar: &Scalar) -> VortexResult<()> {
336 self.append_n_scalars(scalar, 1)
337 }
338
339 fn reserve_exact(&mut self, _additional: usize) {}
340
341 fn reserve_chunks(&mut self, additional: usize) {
342 self.core.reserve(additional);
343 self.shredded.reserve(additional);
344 }
345
346 fn finish(&mut self) -> ArrayRef {
347 self.finish_into_variant()
348 .vortex_expect("the appended Variants finish into one")
349 .into_array()
350 }
351
352 fn finish_into_canonical(&mut self, _ctx: &mut ExecutionCtx) -> Canonical {
353 Canonical::Variant(
354 self.finish_into_variant()
355 .vortex_expect("the appended Variants finish into one"),
356 )
357 }
358}
359
360#[cfg(test)]
361mod tests {
362 use std::sync::LazyLock;
363
364 use vortex_error::VortexResult;
365 use vortex_error::vortex_err;
366 use vortex_session::VortexSession;
367
368 use super::*;
369 use crate::VortexSessionExecute;
370 use crate::arrays::Chunked;
371 use crate::arrays::Constant;
372 use crate::arrays::PrimitiveArray;
373 use crate::arrays::chunked::ChunkedArrayExt;
374 use crate::assert_arrays_eq;
375 use crate::builders::builder_with_capacity_in;
376 use crate::memory::BufferAllocatorRef;
377
378 static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
379
380 fn variant(value: i32) -> Scalar {
381 Scalar::variant(Scalar::primitive(value, Nullability::NonNullable))
382 }
383
384 fn values(array: &VariantArray) -> VortexResult<Vec<Option<i32>>> {
386 let mut ctx = SESSION.create_execution_ctx();
387 (0..array.len())
388 .map(|idx| {
389 let scalar = array.execute_scalar(idx, &mut ctx)?;
390 Ok(scalar
391 .as_variant()
392 .value()
393 .and_then(|value| value.as_primitive().as_::<i32>()))
394 })
395 .collect()
396 }
397
398 #[test]
399 fn dispatches_on_the_variant_dtype() {
400 let builder = builder_with_capacity_in(
401 &DType::Variant(Nullability::Nullable),
402 4,
403 BufferAllocatorRef::static_ref(),
404 );
405 assert!(builder.as_any().is::<VariantBuilder>());
406 }
407
408 #[test]
410 fn appends_scalars_as_runs() -> VortexResult<()> {
411 let mut builder = VariantBuilder::new(Nullability::Nullable);
412 builder.append_scalar(&variant(1))?;
413 builder.append_scalar(&variant(1))?;
414 builder.append_nulls(2);
415 builder.append_scalar(&variant(2))?;
416
417 let array = builder.finish_into_variant()?;
418 assert_eq!(values(&array)?, [Some(1), Some(1), None, None, Some(2)]);
419 let core = array.core_storage().as_::<Chunked>();
420 assert_eq!(core.nchunks(), 3);
421 assert!(core.iter_chunks().all(|chunk| chunk.is::<Constant>()));
422 Ok(())
423 }
424
425 #[test]
428 fn pads_the_shredded_child() -> VortexResult<()> {
429 let mut ctx = SESSION.create_execution_ctx();
430 let shredded = VariantArray::try_new(
431 ConstantArray::new(variant(1), 2).into_array(),
432 Some(PrimitiveArray::from_iter([10i32, 20]).into_array()),
433 )?;
434 let mut builder = VariantBuilder::new(Nullability::NonNullable);
435 builder.append_scalar(&variant(3))?;
436 builder.append_variant_array(&shredded, &mut ctx)?;
437 builder.append_scalar(&variant(4))?;
438
439 let array = builder.finish_into_variant()?;
440 assert_eq!(values(&array)?, [Some(3), Some(10), Some(20), Some(4)]);
441 let shredded = array
442 .shredded()
443 .ok_or_else(|| vortex_err!("expected a shredded child"))?;
444 assert_arrays_eq!(
445 shredded,
446 PrimitiveArray::from_option_iter([None, Some(10i32), Some(20), None]),
447 &mut ctx
448 );
449 Ok(())
450 }
451
452 #[test]
454 fn concatenates_the_shredded_children() -> VortexResult<()> {
455 let mut ctx = SESSION.create_execution_ctx();
456 let mut builder = VariantBuilder::new(Nullability::NonNullable);
457 for (values, shredded) in [(vec![1, 2], vec![10i32, 20]), (vec![3], vec![30])] {
458 let core = ChunkedArray::try_new(
459 values
460 .into_iter()
461 .map(|value| ConstantArray::new(variant(value), 1).into_array()),
462 DType::Variant(Nullability::NonNullable),
463 )?;
464 let array = VariantArray::try_new(
465 core.into_array(),
466 Some(PrimitiveArray::from_iter(shredded).into_array()),
467 )?;
468 builder.append_variant_array(&array, &mut ctx)?;
469 }
470
471 let array = builder.finish_into_variant()?;
472 assert_eq!(values(&array)?, [Some(10), Some(20), Some(30)]);
473 let shredded = array
474 .shredded()
475 .ok_or_else(|| vortex_err!("expected a shredded child"))?;
476 assert_arrays_eq!(
477 shredded,
478 PrimitiveArray::from_iter([10i32, 20, 30]),
479 &mut ctx
480 );
481 Ok(())
482 }
483
484 #[test]
485 fn rejects_shredded_children_of_different_dtypes() -> VortexResult<()> {
486 let mut ctx = SESSION.create_execution_ctx();
487 let shredded = |value: i32, typed: ArrayRef| {
488 VariantArray::try_new(
489 ConstantArray::new(variant(value), 1).into_array(),
490 Some(typed),
491 )
492 };
493 let mut builder = VariantBuilder::new(Nullability::NonNullable);
494 builder.append_variant_array(
495 &shredded(1, PrimitiveArray::from_iter([10i32]).into_array())?,
496 &mut ctx,
497 )?;
498
499 let err = builder
500 .append_variant_array(
501 &shredded(2, PrimitiveArray::from_iter([20i64]).into_array())?,
502 &mut ctx,
503 )
504 .and_then(|()| builder.finish_into_variant().map(|_| ()))
505 .unwrap_err();
506 assert!(
507 err.to_string()
508 .contains("cannot build a Variant from Variants shredded as")
509 );
510 Ok(())
511 }
512
513 #[test]
514 fn rejects_nullable_variants_in_a_non_nullable_builder() {
515 let mut builder = VariantBuilder::new(Nullability::NonNullable);
516 let null = Scalar::null(DType::Variant(Nullability::Nullable));
517 assert!(builder.append_scalar(&null).is_err());
518 }
519
520 #[test]
521 fn finishes_empty() -> VortexResult<()> {
522 let array = VariantBuilder::new(Nullability::Nullable).finish_into_variant()?;
523 assert!(array.is_empty());
524 assert!(array.shredded().is_none());
525 Ok(())
526 }
527}