Skip to main content

arrow_array/array/
union_array.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5#![allow(clippy::enum_clike_unportable_variant)]
6
7use crate::{Array, ArrayRef, make_array};
8use arrow_buffer::bit_chunk_iterator::{BitChunkIterator, BitChunks};
9use arrow_buffer::buffer::NullBuffer;
10use arrow_buffer::{BooleanBuffer, Buffer, MutableBuffer, ScalarBuffer};
11use arrow_data::{ArrayData, ArrayDataBuilder};
12use arrow_schema::{ArrowError, DataType, UnionFields, UnionMode};
13/// Contains the `UnionArray` type.
14///
15use std::any::Any;
16use std::collections::HashSet;
17use std::sync::Arc;
18
19/// An array of [values of varying types](https://arrow.apache.org/docs/format/Columnar.html#union-layout)
20///
21/// Each slot in a [UnionArray] can have a value chosen from a number
22/// of types.  Each of the possible types are named like the fields of
23/// a [`StructArray`](crate::StructArray).  A `UnionArray` can
24/// have two possible memory layouts, "dense" or "sparse".  For more
25/// information on please see the
26/// [specification](https://arrow.apache.org/docs/format/Columnar.html#union-layout).
27///
28/// [UnionBuilder](crate::builder::UnionBuilder) can be used to
29/// create [UnionArray]'s of primitive types. `UnionArray`'s of nested
30/// types are also supported but not via `UnionBuilder`, see the tests
31/// for examples.
32///
33/// # Examples
34/// ## Create a dense UnionArray `[1, 3.2, 34]`
35/// ```
36/// use arrow_buffer::ScalarBuffer;
37/// use arrow_schema::*;
38/// use std::sync::Arc;
39/// use arrow_array::{Array, Int32Array, Float64Array, UnionArray};
40///
41/// let int_array = Int32Array::from(vec![1, 34]);
42/// let float_array = Float64Array::from(vec![3.2]);
43/// let type_ids = [0, 1, 0].into_iter().collect::<ScalarBuffer<i8>>();
44/// let offsets = [0, 0, 1].into_iter().collect::<ScalarBuffer<i32>>();
45///
46/// let union_fields = [
47///     (0, Arc::new(Field::new("A", DataType::Int32, false))),
48///     (1, Arc::new(Field::new("B", DataType::Float64, false))),
49/// ].into_iter().collect::<UnionFields>();
50///
51/// let children = vec![
52///     Arc::new(int_array) as Arc<dyn Array>,
53///     Arc::new(float_array),
54/// ];
55///
56/// let array = UnionArray::try_new(
57///     union_fields,
58///     type_ids,
59///     Some(offsets),
60///     children,
61/// ).unwrap();
62///
63/// let value = array.value(0).as_any().downcast_ref::<Int32Array>().unwrap().value(0);
64/// assert_eq!(1, value);
65///
66/// let value = array.value(1).as_any().downcast_ref::<Float64Array>().unwrap().value(0);
67/// assert!(3.2 - value < f64::EPSILON);
68///
69/// let value = array.value(2).as_any().downcast_ref::<Int32Array>().unwrap().value(0);
70/// assert_eq!(34, value);
71/// ```
72///
73/// ## Create a sparse UnionArray `[1, 3.2, 34]`
74/// ```
75/// use arrow_buffer::ScalarBuffer;
76/// use arrow_schema::*;
77/// use std::sync::Arc;
78/// use arrow_array::{Array, Int32Array, Float64Array, UnionArray};
79///
80/// let int_array = Int32Array::from(vec![Some(1), None, Some(34)]);
81/// let float_array = Float64Array::from(vec![None, Some(3.2), None]);
82/// let type_ids = [0_i8, 1, 0].into_iter().collect::<ScalarBuffer<i8>>();
83///
84/// let union_fields = [
85///     (0, Arc::new(Field::new("A", DataType::Int32, false))),
86///     (1, Arc::new(Field::new("B", DataType::Float64, false))),
87/// ].into_iter().collect::<UnionFields>();
88///
89/// let children = vec![
90///     Arc::new(int_array) as Arc<dyn Array>,
91///     Arc::new(float_array),
92/// ];
93///
94/// let array = UnionArray::try_new(
95///     union_fields,
96///     type_ids,
97///     None,
98///     children,
99/// ).unwrap();
100///
101/// let value = array.value(0).as_any().downcast_ref::<Int32Array>().unwrap().value(0);
102/// assert_eq!(1, value);
103///
104/// let value = array.value(1).as_any().downcast_ref::<Float64Array>().unwrap().value(0);
105/// assert!(3.2 - value < f64::EPSILON);
106///
107/// let value = array.value(2).as_any().downcast_ref::<Int32Array>().unwrap().value(0);
108/// assert_eq!(34, value);
109/// ```
110#[derive(Clone)]
111pub struct UnionArray {
112    data_type: DataType,
113    type_ids: ScalarBuffer<i8>,
114    offsets: Option<ScalarBuffer<i32>>,
115    fields: Vec<Option<ArrayRef>>,
116}
117
118impl UnionArray {
119    /// Creates a new `UnionArray`.
120    ///
121    /// Accepts type ids, child arrays and optionally offsets (for dense unions) to create
122    /// a new `UnionArray`.  This method makes no attempt to validate the data provided by the
123    /// caller and assumes that each of the components are correct and consistent with each other.
124    /// See `try_new` for an alternative that validates the data provided.
125    ///
126    /// # Safety
127    ///
128    /// The `type_ids` values should be non-negative and must match one of the type ids of the fields provided in `fields`.
129    /// These values are used to index into the `children` arrays.
130    ///
131    /// The `offsets` is provided in the case of a dense union, sparse unions should use `None`.
132    /// If provided the `offsets` values should be non-negative and must be less than the length of the
133    /// corresponding array.
134    ///
135    /// In both cases above we use signed integer types to maintain compatibility with other
136    /// Arrow implementations.
137    pub unsafe fn new_unchecked(
138        fields: UnionFields,
139        type_ids: ScalarBuffer<i8>,
140        offsets: Option<ScalarBuffer<i32>>,
141        children: Vec<ArrayRef>,
142    ) -> Self {
143        let mode = if offsets.is_some() {
144            UnionMode::Dense
145        } else {
146            UnionMode::Sparse
147        };
148
149        let len = type_ids.len();
150        let builder = ArrayData::builder(DataType::Union(fields, mode))
151            .add_buffer(type_ids.into_inner())
152            .child_data(children.into_iter().map(Array::into_data).collect())
153            .len(len);
154
155        let data = match offsets {
156            Some(offsets) => unsafe { builder.add_buffer(offsets.into_inner()).build_unchecked() },
157            None => unsafe { builder.build_unchecked() },
158        };
159        Self::from(data)
160    }
161
162    /// Attempts to create a new `UnionArray`, validating the inputs provided.
163    ///
164    /// The order of child arrays child array order must match the fields order
165    pub fn try_new(
166        fields: UnionFields,
167        type_ids: ScalarBuffer<i8>,
168        offsets: Option<ScalarBuffer<i32>>,
169        children: Vec<ArrayRef>,
170    ) -> Result<Self, ArrowError> {
171        // There must be a child array for every field.
172        if fields.len() != children.len() {
173            return Err(ArrowError::InvalidArgumentError(
174                "Union fields length must match child arrays length".to_string(),
175            ));
176        }
177
178        if let Some(offsets) = &offsets {
179            // There must be an offset value for every type id value.
180            if offsets.len() != type_ids.len() {
181                return Err(ArrowError::InvalidArgumentError(
182                    "Type Ids and Offsets lengths must match".to_string(),
183                ));
184            }
185        } else {
186            // Sparse union child arrays must be equal in length to the length of the union
187            for child in &children {
188                if child.len() != type_ids.len() {
189                    return Err(ArrowError::InvalidArgumentError(
190                        "Sparse union child arrays must be equal in length to the length of the union".to_string(),
191                    ));
192                }
193            }
194        }
195
196        // Create mapping from type id to array lengths.
197        let max_id = fields.iter().map(|(i, _)| i).max().unwrap_or_default() as usize;
198        let mut array_lens = vec![None; max_id + 1];
199        for (cd, (field_id, _)) in children.iter().zip(fields.iter()) {
200            array_lens[field_id as usize] = Some(cd.len());
201        }
202
203        // Type id values must match one of the fields.
204        for id in &type_ids {
205            match array_lens.get(*id as usize) {
206                Some(Some(_)) => {}
207                _ => {
208                    return Err(ArrowError::InvalidArgumentError(
209                        "Type Ids values must match one of the field type ids".to_owned(),
210                    ));
211                }
212            }
213        }
214
215        // Check the value offsets are in bounds.
216        if let Some(offsets) = &offsets {
217            let mut iter = type_ids.iter().zip(offsets.iter());
218            if iter.any(|(type_id, &offset)| {
219                offset < 0 || offset as usize >= array_lens[*type_id as usize].unwrap()
220            }) {
221                return Err(ArrowError::InvalidArgumentError(
222                    "Offsets must be non-negative and within the length of the Array".to_owned(),
223                ));
224            }
225        }
226
227        // Safety:
228        // - Arguments validated above.
229        let union_array = unsafe { Self::new_unchecked(fields, type_ids, offsets, children) };
230        Ok(union_array)
231    }
232
233    /// Accesses the child array for `type_id`.
234    ///
235    /// # Panics
236    ///
237    /// Panics if the `type_id` provided is not present in the array's DataType
238    /// in the `Union`.
239    pub fn child(&self, type_id: i8) -> &ArrayRef {
240        assert!((type_id as usize) < self.fields.len());
241        let boxed = &self.fields[type_id as usize];
242        boxed.as_ref().expect("invalid type id")
243    }
244
245    /// Returns the `type_id` for the array slot at `index`.
246    ///
247    /// # Panics
248    ///
249    /// Panics if `index` is greater than or equal to the number of child arrays
250    pub fn type_id(&self, index: usize) -> i8 {
251        assert!(index < self.type_ids.len());
252        self.type_ids[index]
253    }
254
255    /// Returns the `type_ids` buffer for this array
256    pub fn type_ids(&self) -> &ScalarBuffer<i8> {
257        &self.type_ids
258    }
259
260    /// Returns the `offsets` buffer if this is a dense array
261    pub fn offsets(&self) -> Option<&ScalarBuffer<i32>> {
262        self.offsets.as_ref()
263    }
264
265    /// Returns the offset into the underlying values array for the array slot at `index`.
266    ///
267    /// # Panics
268    ///
269    /// Panics if `index` is greater than or equal the length of the array.
270    pub fn value_offset(&self, index: usize) -> usize {
271        assert!(index < self.len());
272        match &self.offsets {
273            Some(offsets) => offsets[index] as usize,
274            None => self.offset() + index,
275        }
276    }
277
278    /// Returns the array's value at index `i`.
279    ///
280    /// Note: This method does not check for nulls and the value is arbitrary
281    /// (but still well-defined) if [`is_null`](Self::is_null) returns true for the index.
282    ///
283    /// # Panics
284    /// Panics if index `i` is out of bounds
285    pub fn value(&self, i: usize) -> ArrayRef {
286        let type_id = self.type_id(i);
287        let value_offset = self.value_offset(i);
288        let child = self.child(type_id);
289        child.slice(value_offset, 1)
290    }
291
292    /// Returns the names of the types in the union.
293    pub fn type_names(&self) -> Vec<&str> {
294        match self.data_type() {
295            DataType::Union(fields, _) => fields
296                .iter()
297                .map(|(_, f)| f.name().as_str())
298                .collect::<Vec<&str>>(),
299            _ => unreachable!("Union array's data type is not a union!"),
300        }
301    }
302
303    /// Returns the [`UnionFields`] for the union.
304    pub fn fields(&self) -> &UnionFields {
305        match self.data_type() {
306            DataType::Union(fields, _) => fields,
307            _ => unreachable!("Union array's data type is not a union!"),
308        }
309    }
310
311    /// Returns whether the `UnionArray` is dense (or sparse if `false`).
312    pub fn is_dense(&self) -> bool {
313        match self.data_type() {
314            DataType::Union(_, mode) => mode == &UnionMode::Dense,
315            _ => unreachable!("Union array's data type is not a union!"),
316        }
317    }
318
319    /// Returns a zero-copy slice of this array with the indicated offset and length.
320    ///
321    /// # Panics
322    /// Panics if `offset + length > self.len()`
323    pub fn slice(&self, offset: usize, length: usize) -> Self {
324        let (offsets, fields) = match self.offsets.as_ref() {
325            // If dense union, slice offsets
326            Some(offsets) => (Some(offsets.slice(offset, length)), self.fields.clone()),
327            // Otherwise need to slice sparse children
328            None => {
329                let fields = self
330                    .fields
331                    .iter()
332                    .map(|x| x.as_ref().map(|x| x.slice(offset, length)))
333                    .collect();
334                (None, fields)
335            }
336        };
337
338        Self {
339            data_type: self.data_type.clone(),
340            type_ids: self.type_ids.slice(offset, length),
341            offsets,
342            fields,
343        }
344    }
345
346    /// Deconstruct this array into its constituent parts
347    ///
348    /// # Example
349    ///
350    /// ```
351    /// # use arrow_array::array::UnionArray;
352    /// # use arrow_array::types::Int32Type;
353    /// # use arrow_array::builder::UnionBuilder;
354    /// # use arrow_buffer::ScalarBuffer;
355    /// # fn main() -> Result<(), arrow_schema::ArrowError> {
356    /// let mut builder = UnionBuilder::new_dense();
357    /// builder.append::<Int32Type>("a", 1).unwrap();
358    /// let union_array = builder.build()?;
359    ///
360    /// // Deconstruct into parts
361    /// let (union_fields, type_ids, offsets, children) = union_array.into_parts();
362    ///
363    /// // Reconstruct from parts
364    /// let union_array = UnionArray::try_new(
365    ///     union_fields,
366    ///     type_ids,
367    ///     offsets,
368    ///     children,
369    /// );
370    /// # Ok(())
371    /// # }
372    /// ```
373    pub fn into_parts(
374        self,
375    ) -> (
376        UnionFields,
377        ScalarBuffer<i8>,
378        Option<ScalarBuffer<i32>>,
379        Vec<ArrayRef>,
380    ) {
381        let Self {
382            data_type,
383            type_ids,
384            offsets,
385            mut fields,
386        } = self;
387        match data_type {
388            DataType::Union(union_fields, _) => {
389                let children = union_fields
390                    .iter()
391                    .map(|(type_id, _)| fields[type_id as usize].take().unwrap())
392                    .collect();
393                (union_fields, type_ids, offsets, children)
394            }
395            _ => unreachable!(),
396        }
397    }
398
399    /// Computes the logical nulls for a sparse union, optimized for when there's a lot of fields without nulls
400    fn mask_sparse_skip_without_nulls(&self, nulls: Vec<(i8, NullBuffer)>) -> BooleanBuffer {
401        // Example logic for a union with 5 fields, a, b & c with nulls, d & e without nulls:
402        // let [a_nulls, b_nulls, c_nulls] = nulls;
403        // let [is_a, is_b, is_c] = masks;
404        // let is_d_or_e = !(is_a | is_b | is_c)
405        // let union_chunk_nulls = is_d_or_e  | (is_a & a_nulls) | (is_b & b_nulls) | (is_c & c_nulls)
406        let fold = |(with_nulls_selected, union_nulls), (is_field, field_nulls)| {
407            (
408                with_nulls_selected | is_field,
409                union_nulls | (is_field & field_nulls),
410            )
411        };
412
413        self.mask_sparse_helper(
414            nulls,
415            |type_ids_chunk_array, nulls_masks_iters| {
416                let (with_nulls_selected, union_nulls) = nulls_masks_iters
417                    .iter_mut()
418                    .map(|(field_type_id, field_nulls)| {
419                        let field_nulls = field_nulls.next().unwrap();
420                        let is_field = selection_mask(type_ids_chunk_array, *field_type_id);
421
422                        (is_field, field_nulls)
423                    })
424                    .fold((0, 0), fold);
425
426                // In the example above, this is the is_d_or_e = !(is_a | is_b) part
427                let without_nulls_selected = !with_nulls_selected;
428
429                // if a field without nulls is selected, the value is always true(set bit)
430                // otherwise, the true/set bits have been computed above
431                without_nulls_selected | union_nulls
432            },
433            |type_ids_remainder, bit_chunks| {
434                let (with_nulls_selected, union_nulls) = bit_chunks
435                    .iter()
436                    .map(|(field_type_id, field_bit_chunks)| {
437                        let field_nulls = field_bit_chunks.remainder_bits();
438                        let is_field = selection_mask(type_ids_remainder, *field_type_id);
439
440                        (is_field, field_nulls)
441                    })
442                    .fold((0, 0), fold);
443
444                let without_nulls_selected = !with_nulls_selected;
445
446                without_nulls_selected | union_nulls
447            },
448        )
449    }
450
451    /// Computes the logical nulls for a sparse union, optimized for when there's a lot of fields fully null
452    fn mask_sparse_skip_fully_null(&self, mut nulls: Vec<(i8, NullBuffer)>) -> BooleanBuffer {
453        let DataType::Union(fields, _) = self.data_type() else {
454            unreachable!("Union array's data type is not a union!")
455        };
456
457        let type_ids = fields.iter().map(|(id, _)| id).collect::<HashSet<_>>();
458        let with_nulls = nulls.iter().map(|(id, _)| *id).collect::<HashSet<_>>();
459
460        let without_nulls_ids = type_ids
461            .difference(&with_nulls)
462            .copied()
463            .collect::<Vec<_>>();
464
465        nulls.retain(|(_, nulls)| nulls.null_count() < nulls.len());
466
467        // Example logic for a union with 6 fields, a, b & c with nulls, d & e without nulls, and f fully_null:
468        // let [a_nulls, b_nulls, c_nulls] = nulls;
469        // let [is_a, is_b, is_c, is_d, is_e] = masks;
470        // let union_chunk_nulls = is_d | is_e | (is_a & a_nulls) | (is_b & b_nulls) | (is_c & c_nulls)
471        self.mask_sparse_helper(
472            nulls,
473            |type_ids_chunk_array, nulls_masks_iters| {
474                let union_nulls = nulls_masks_iters.iter_mut().fold(
475                    0,
476                    |union_nulls, (field_type_id, nulls_iter)| {
477                        let field_nulls = nulls_iter.next().unwrap();
478
479                        if field_nulls == 0 {
480                            union_nulls
481                        } else {
482                            let is_field = selection_mask(type_ids_chunk_array, *field_type_id);
483
484                            union_nulls | (is_field & field_nulls)
485                        }
486                    },
487                );
488
489                // Given the example above, this is the is_d_or_e = (is_d | is_e) part
490                let without_nulls_selected =
491                    without_nulls_selected(type_ids_chunk_array, &without_nulls_ids);
492
493                // if a field without nulls is selected, the value is always true(set bit)
494                // otherwise, the true/set bits have been computed above
495                union_nulls | without_nulls_selected
496            },
497            |type_ids_remainder, bit_chunks| {
498                let union_nulls =
499                    bit_chunks
500                        .iter()
501                        .fold(0, |union_nulls, (field_type_id, field_bit_chunks)| {
502                            let is_field = selection_mask(type_ids_remainder, *field_type_id);
503                            let field_nulls = field_bit_chunks.remainder_bits();
504
505                            union_nulls | is_field & field_nulls
506                        });
507
508                union_nulls | without_nulls_selected(type_ids_remainder, &without_nulls_ids)
509            },
510        )
511    }
512
513    /// Computes the logical nulls for a sparse union, optimized for when all fields contains nulls
514    fn mask_sparse_all_with_nulls_skip_one(&self, nulls: Vec<(i8, NullBuffer)>) -> BooleanBuffer {
515        // Example logic for a union with 3 fields, a, b & c, all containing nulls:
516        // let [a_nulls, b_nulls, c_nulls] = nulls;
517        // We can skip the first field: it's selection mask is the negation of all others selection mask
518        // let [is_b, is_c] = selection_masks;
519        // let is_a = !(is_b | is_c)
520        // let union_chunk_nulls = (is_a & a_nulls) | (is_b & b_nulls) | (is_c & c_nulls)
521        self.mask_sparse_helper(
522            nulls,
523            |type_ids_chunk_array, nulls_masks_iters| {
524                let (is_not_first, union_nulls) = nulls_masks_iters[1..] // skip first
525                    .iter_mut()
526                    .fold(
527                        (0, 0),
528                        |(is_not_first, union_nulls), (field_type_id, nulls_iter)| {
529                            let field_nulls = nulls_iter.next().unwrap();
530                            let is_field = selection_mask(type_ids_chunk_array, *field_type_id);
531
532                            (
533                                is_not_first | is_field,
534                                union_nulls | (is_field & field_nulls),
535                            )
536                        },
537                    );
538
539                let is_first = !is_not_first;
540                let first_nulls = nulls_masks_iters[0].1.next().unwrap();
541
542                (is_first & first_nulls) | union_nulls
543            },
544            |type_ids_remainder, bit_chunks| {
545                bit_chunks
546                    .iter()
547                    .fold(0, |union_nulls, (field_type_id, field_bit_chunks)| {
548                        let field_nulls = field_bit_chunks.remainder_bits();
549                        // The same logic as above, except that since this runs at most once,
550                        // it doesn't make difference to speed-up the first selection mask
551                        let is_field = selection_mask(type_ids_remainder, *field_type_id);
552
553                        union_nulls | (is_field & field_nulls)
554                    })
555            },
556        )
557    }
558
559    /// Maps `nulls` to `BitChunk's` and then to `BitChunkIterator's`, then divides `self.type_ids` into exact chunks of 64 values,
560    /// calling `mask_chunk` for every exact chunk, and `mask_remainder` for the remainder, if any, collecting the result in a `BooleanBuffer`
561    fn mask_sparse_helper(
562        &self,
563        nulls: Vec<(i8, NullBuffer)>,
564        mut mask_chunk: impl FnMut(&[i8; 64], &mut [(i8, BitChunkIterator)]) -> u64,
565        mask_remainder: impl FnOnce(&[i8], &[(i8, BitChunks)]) -> u64,
566    ) -> BooleanBuffer {
567        let bit_chunks = nulls
568            .iter()
569            .map(|(type_id, nulls)| (*type_id, nulls.inner().bit_chunks()))
570            .collect::<Vec<_>>();
571
572        let mut nulls_masks_iter = bit_chunks
573            .iter()
574            .map(|(type_id, bit_chunks)| (*type_id, bit_chunks.iter()))
575            .collect::<Vec<_>>();
576
577        let (chunks_exact, remainder) = self.type_ids.as_chunks::<64>();
578
579        let chunks = chunks_exact
580            .iter()
581            .map(|type_ids_chunk| mask_chunk(type_ids_chunk, &mut nulls_masks_iter));
582
583        // SAFETY:
584        // chunks is a ChunksExact iterator, which implements TrustedLen, and correctly reports its length
585        let mut buffer = unsafe { MutableBuffer::from_trusted_len_iter(chunks) };
586
587        if !remainder.is_empty() {
588            buffer.push(mask_remainder(remainder, &bit_chunks));
589        }
590
591        BooleanBuffer::new(buffer.into(), 0, self.type_ids.len())
592    }
593
594    /// Computes the logical nulls for a sparse or dense union, by gathering individual bits from the null buffer of the selected field
595    fn gather_nulls(&self, nulls: Vec<(i8, NullBuffer)>) -> BooleanBuffer {
596        let one_null = NullBuffer::new_null(1);
597        let one_valid = NullBuffer::new_valid(1);
598
599        // Unsafe code below depend on it:
600        // To remove one branch from the loop, if the a type_id is not utilized, or it's logical_nulls is None/all set,
601        // we use a null buffer of len 1 and a index_mask of 0, or the true null buffer and usize::MAX otherwise.
602        // We then unconditionally access the null buffer with index & index_mask,
603        // which always return 0 for the 1-len buffer, or the true index unchanged otherwise
604        // We also use a 256 array, so llvm knows that `type_id as u8 as usize` is always in bounds
605        let mut logical_nulls_array = [(&one_valid, Mask::Zero); 256];
606
607        for (type_id, nulls) in &nulls {
608            if nulls.null_count() == nulls.len() {
609                // Similarly, if all values are null, use a 1-null null-buffer to reduce cache pressure a bit
610                logical_nulls_array[*type_id as u8 as usize] = (&one_null, Mask::Zero);
611            } else {
612                logical_nulls_array[*type_id as u8 as usize] = (nulls, Mask::Max);
613            }
614        }
615
616        match &self.offsets {
617            Some(offsets) => {
618                assert_eq!(self.type_ids.len(), offsets.len());
619
620                BooleanBuffer::collect_bool(self.type_ids.len(), |i| unsafe {
621                    // SAFETY: BooleanBuffer::collect_bool calls us 0..self.type_ids.len()
622                    let type_id = *self.type_ids.get_unchecked(i);
623                    // SAFETY: We asserted that offsets len and self.type_ids len are equal
624                    let offset = *offsets.get_unchecked(i);
625
626                    let (nulls, offset_mask) = &logical_nulls_array[type_id as u8 as usize];
627
628                    // SAFETY:
629                    // If offset_mask is Max
630                    // 1. Offset validity is checked at union creation
631                    // 2. If the null buffer len equals it's array len is checked at array creation
632                    // If offset_mask is Zero, the null buffer len is 1
633                    nulls
634                        .inner()
635                        .value_unchecked(offset as usize & *offset_mask as usize)
636                })
637            }
638            None => {
639                BooleanBuffer::collect_bool(self.type_ids.len(), |index| unsafe {
640                    // SAFETY: BooleanBuffer::collect_bool calls us 0..self.type_ids.len()
641                    let type_id = *self.type_ids.get_unchecked(index);
642
643                    let (nulls, index_mask) = &logical_nulls_array[type_id as u8 as usize];
644
645                    // SAFETY:
646                    // If index_mask is Max
647                    // 1. On sparse union, every child len match it's parent, this is checked at union creation
648                    // 2. If the null buffer len equals it's array len is checked at array creation
649                    // If index_mask is Zero, the null buffer len is 1
650                    nulls.inner().value_unchecked(index & *index_mask as usize)
651                })
652            }
653        }
654    }
655
656    /// Returns a vector of tuples containing each field's type_id and its logical null buffer.
657    /// Only fields with non-zero null counts are included.
658    fn fields_logical_nulls(&self) -> Vec<(i8, NullBuffer)> {
659        self.fields
660            .iter()
661            .enumerate()
662            .filter_map(|(type_id, field)| Some((type_id as i8, field.as_ref()?.logical_nulls()?)))
663            .filter(|(_, nulls)| nulls.null_count() > 0)
664            .collect()
665    }
666}
667
668impl From<ArrayData> for UnionArray {
669    fn from(data: ArrayData) -> Self {
670        let (data_type, len, _nulls, offset, buffers, child_data) = data.into_parts();
671
672        let (fields, mode) = match &data_type {
673            DataType::Union(fields, mode) => (fields, mode),
674            d => panic!("UnionArray expected ArrayData with type Union got {d}"),
675        };
676
677        let (type_ids, offsets) = match mode {
678            UnionMode::Sparse => {
679                let [buffer]: [Buffer; 1] = buffers.try_into().expect("1 buffer for type_ids");
680                (ScalarBuffer::new(buffer, offset, len), None)
681            }
682            UnionMode::Dense => {
683                let [type_ids_buffer, offsets_buffer]: [Buffer; 2] = buffers
684                    .try_into()
685                    .expect("2 buffers for type_ids and offsets");
686                (
687                    ScalarBuffer::new(type_ids_buffer, offset, len),
688                    Some(ScalarBuffer::new(offsets_buffer, offset, len)),
689                )
690            }
691        };
692
693        let max_id = fields.iter().map(|(i, _)| i).max().unwrap_or_default() as usize;
694        let mut boxed_fields = vec![None; max_id + 1];
695        for (cd, (field_id, _)) in child_data.into_iter().zip(fields.iter()) {
696            let cd = match mode {
697                UnionMode::Sparse => cd.sliced(offset, len),
698                UnionMode::Dense => cd,
699            };
700            boxed_fields[field_id as usize] = Some(make_array(cd));
701        }
702        Self {
703            data_type,
704            type_ids,
705            offsets,
706            fields: boxed_fields,
707        }
708    }
709}
710
711impl From<UnionArray> for ArrayData {
712    fn from(array: UnionArray) -> Self {
713        let len = array.len();
714        let DataType::Union(f, _) = &array.data_type else {
715            unreachable!()
716        };
717        let buffers = match array.offsets {
718            Some(o) => vec![array.type_ids.into_inner(), o.into_inner()],
719            None => vec![array.type_ids.into_inner()],
720        };
721
722        let child = f
723            .iter()
724            .map(|(i, _)| array.fields[i as usize].as_ref().unwrap().to_data())
725            .collect();
726
727        let builder = ArrayDataBuilder::new(array.data_type)
728            .len(len)
729            .buffers(buffers)
730            .child_data(child);
731        unsafe { builder.build_unchecked() }
732    }
733}
734
735/// SAFETY: Correctly implements the contract of Arrow Arrays
736unsafe impl Array for UnionArray {
737    fn as_any(&self) -> &dyn Any {
738        self
739    }
740
741    fn to_arc(&self) -> ArrayRef {
742        Arc::new(self.clone())
743    }
744
745    fn to_data(&self) -> ArrayData {
746        self.clone().into()
747    }
748
749    fn into_data(self) -> ArrayData {
750        self.into()
751    }
752
753    fn data_type(&self) -> &DataType {
754        &self.data_type
755    }
756
757    fn slice(&self, offset: usize, length: usize) -> ArrayRef {
758        Arc::new(self.slice(offset, length))
759    }
760
761    fn len(&self) -> usize {
762        self.type_ids.len()
763    }
764
765    fn is_empty(&self) -> bool {
766        self.type_ids.is_empty()
767    }
768
769    fn shrink_to_fit(&mut self) {
770        self.type_ids.shrink_to_fit();
771        if let Some(offsets) = &mut self.offsets {
772            offsets.shrink_to_fit();
773        }
774        for array in self.fields.iter_mut().flatten() {
775            array.shrink_to_fit();
776        }
777        self.fields.shrink_to_fit();
778    }
779
780    fn offset(&self) -> usize {
781        0
782    }
783
784    fn nulls(&self) -> Option<&NullBuffer> {
785        None
786    }
787
788    fn logical_nulls(&self) -> Option<NullBuffer> {
789        let DataType::Union(fields, _) = self.data_type() else {
790            unreachable!()
791        };
792
793        if fields.len() <= 1 {
794            return self
795                .fields
796                .iter()
797                .enumerate()
798                .find_map(|(type_id, field_opt)| {
799                    field_opt
800                        .as_ref()
801                        .and_then(|field| field.logical_nulls())
802                        .map(|logical_nulls| {
803                            if self.is_dense() {
804                                self.gather_nulls(vec![(type_id as i8, logical_nulls)])
805                                    .into()
806                            } else {
807                                logical_nulls
808                            }
809                        })
810                });
811        }
812
813        let logical_nulls = self.fields_logical_nulls();
814
815        if logical_nulls.is_empty() {
816            return None;
817        }
818
819        let fully_null_count = logical_nulls
820            .iter()
821            .filter(|(_, nulls)| nulls.null_count() == nulls.len())
822            .count();
823
824        if fully_null_count == fields.len() {
825            if let Some((_, exactly_sized)) = logical_nulls
826                .iter()
827                .find(|(_, nulls)| nulls.len() == self.len())
828            {
829                return Some(exactly_sized.clone());
830            }
831
832            if let Some((_, bigger)) = logical_nulls
833                .iter()
834                .find(|(_, nulls)| nulls.len() > self.len())
835            {
836                return Some(bigger.slice(0, self.len()));
837            }
838
839            return Some(NullBuffer::new_null(self.len()));
840        }
841
842        let boolean_buffer = match &self.offsets {
843            Some(_) => self.gather_nulls(logical_nulls),
844            None => {
845                // Choose the fastest way to compute the logical nulls
846                // Gather computes one null per iteration, while the others work on 64 nulls chunks,
847                // but must also compute selection masks, which is expensive,
848                // so it's cost is the number of selection masks computed per chunk
849                // Since computing the selection mask gets auto-vectorized, it's performance depends on which simd feature is enabled
850                // For gather, the cost is the threshold where masking becomes slower than gather, which is determined with benchmarks
851                // TODO: bench on avx512f(feature is still unstable)
852                let gather_relative_cost = if cfg!(target_feature = "avx2") {
853                    10
854                } else if cfg!(target_feature = "sse4.1") {
855                    3
856                } else if cfg!(target_arch = "x86") || cfg!(target_arch = "x86_64") {
857                    // x86 baseline includes sse2
858                    2
859                } else {
860                    // TODO: bench on non x86
861                    // Always use gather on non benchmarked archs because even though it may slower on some cases,
862                    // it's performance depends only on the union length, without being affected by the number of fields
863                    0
864                };
865
866                let strategies = [
867                    (SparseStrategy::Gather, gather_relative_cost, true),
868                    (
869                        SparseStrategy::MaskAllFieldsWithNullsSkipOne,
870                        fields.len() - 1,
871                        fields.len() == logical_nulls.len(),
872                    ),
873                    (
874                        SparseStrategy::MaskSkipWithoutNulls,
875                        logical_nulls.len(),
876                        true,
877                    ),
878                    (
879                        SparseStrategy::MaskSkipFullyNull,
880                        fields.len() - fully_null_count,
881                        true,
882                    ),
883                ];
884
885                let (strategy, _, _) = strategies
886                    .iter()
887                    .filter(|(_, _, applicable)| *applicable)
888                    .min_by_key(|(_, cost, _)| cost)
889                    .unwrap();
890
891                match strategy {
892                    SparseStrategy::Gather => self.gather_nulls(logical_nulls),
893                    SparseStrategy::MaskAllFieldsWithNullsSkipOne => {
894                        self.mask_sparse_all_with_nulls_skip_one(logical_nulls)
895                    }
896                    SparseStrategy::MaskSkipWithoutNulls => {
897                        self.mask_sparse_skip_without_nulls(logical_nulls)
898                    }
899                    SparseStrategy::MaskSkipFullyNull => {
900                        self.mask_sparse_skip_fully_null(logical_nulls)
901                    }
902                }
903            }
904        };
905
906        let null_buffer = NullBuffer::from(boolean_buffer);
907
908        if null_buffer.null_count() > 0 {
909            Some(null_buffer)
910        } else {
911            None
912        }
913    }
914
915    fn is_nullable(&self) -> bool {
916        self.fields
917            .iter()
918            .flatten()
919            .any(|field| field.is_nullable())
920    }
921
922    fn get_buffer_memory_size(&self) -> usize {
923        let mut sum = self.type_ids.inner().capacity();
924        if let Some(o) = self.offsets.as_ref() {
925            sum += o.inner().capacity()
926        }
927        self.fields
928            .iter()
929            .filter_map(|x| x.as_ref().map(|x| x.get_buffer_memory_size()))
930            .sum::<usize>()
931            + sum
932    }
933
934    fn get_array_memory_size(&self) -> usize {
935        let mut sum = self.type_ids.inner().capacity();
936        if let Some(o) = self.offsets.as_ref() {
937            sum += o.inner().capacity()
938        }
939        std::mem::size_of::<Self>()
940            + self
941                .fields
942                .iter()
943                .filter_map(|x| x.as_ref().map(|x| x.get_array_memory_size()))
944                .sum::<usize>()
945            + sum
946    }
947
948    #[cfg(feature = "pool")]
949    fn claim(&self, pool: &dyn arrow_buffer::MemoryPool) {
950        self.type_ids.claim(pool);
951        if let Some(offsets) = &self.offsets {
952            offsets.claim(pool);
953        }
954        for field in self.fields.iter().flatten() {
955            field.claim(pool);
956        }
957    }
958}
959
960impl std::fmt::Debug for UnionArray {
961    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
962        let header = if self.is_dense() {
963            "UnionArray(Dense)\n["
964        } else {
965            "UnionArray(Sparse)\n["
966        };
967        writeln!(f, "{header}")?;
968
969        writeln!(f, "-- type id buffer:")?;
970        writeln!(f, "{:?}", self.type_ids)?;
971
972        if let Some(offsets) = &self.offsets {
973            writeln!(f, "-- offsets buffer:")?;
974            writeln!(f, "{offsets:?}")?;
975        }
976
977        let DataType::Union(fields, _) = self.data_type() else {
978            unreachable!()
979        };
980
981        for (type_id, field) in fields.iter() {
982            let child = self.child(type_id);
983            writeln!(
984                f,
985                "-- child {}: \"{}\" ({:?})",
986                type_id,
987                field.name(),
988                field.data_type()
989            )?;
990            std::fmt::Debug::fmt(child, f)?;
991            writeln!(f)?;
992        }
993        writeln!(f, "]")
994    }
995}
996
997/// How to compute the logical nulls of a sparse union. All strategies return the same result.
998/// Those starting with Mask perform bitwise masking for each chunk of 64 values, including
999/// computing expensive selection masks of fields: which fields masks must be computed is the
1000/// difference between them
1001enum SparseStrategy {
1002    /// Gather individual bits from the null buffer of the selected field
1003    Gather,
1004    /// All fields contains nulls, so we can skip the selection mask computation of one field by negating the others
1005    MaskAllFieldsWithNullsSkipOne,
1006    /// Skip the selection mask computation of the fields without nulls
1007    MaskSkipWithoutNulls,
1008    /// Skip the selection mask computation of the fully nulls fields
1009    MaskSkipFullyNull,
1010}
1011
1012#[derive(Copy, Clone)]
1013#[repr(usize)]
1014enum Mask {
1015    Zero = 0,
1016    Max = usize::MAX,
1017}
1018
1019fn selection_mask(type_ids_chunk: &[i8], type_id: i8) -> u64 {
1020    type_ids_chunk
1021        .iter()
1022        .copied()
1023        .enumerate()
1024        .fold(0, |packed, (bit_idx, v)| {
1025            packed | (((v == type_id) as u64) << bit_idx)
1026        })
1027}
1028
1029/// Returns a bitmask where bits indicate if any id from `without_nulls_ids` exist in `type_ids_chunk`.
1030fn without_nulls_selected(type_ids_chunk: &[i8], without_nulls_ids: &[i8]) -> u64 {
1031    without_nulls_ids
1032        .iter()
1033        .fold(0, |fully_valid_selected, field_type_id| {
1034            fully_valid_selected | selection_mask(type_ids_chunk, *field_type_id)
1035        })
1036}
1037
1038#[cfg(test)]
1039mod tests {
1040    use super::*;
1041    use std::collections::HashSet;
1042
1043    use crate::array::Int8Type;
1044    use crate::builder::UnionBuilder;
1045    use crate::cast::AsArray;
1046    use crate::types::{Float32Type, Float64Type, Int32Type, Int64Type};
1047    use crate::{Float64Array, Int32Array, Int64Array, NullArray, StringArray};
1048    use crate::{Int8Array, RecordBatch};
1049    use arrow_buffer::Buffer;
1050    use arrow_schema::{Field, Schema};
1051    use rstest::rstest;
1052
1053    #[test]
1054    fn test_dense_i32() {
1055        let mut builder = UnionBuilder::new_dense();
1056        builder.append::<Int32Type>("a", 1).unwrap();
1057        builder.append::<Int32Type>("b", 2).unwrap();
1058        builder.append::<Int32Type>("c", 3).unwrap();
1059        builder.append::<Int32Type>("a", 4).unwrap();
1060        builder.append::<Int32Type>("c", 5).unwrap();
1061        builder.append::<Int32Type>("a", 6).unwrap();
1062        builder.append::<Int32Type>("b", 7).unwrap();
1063        let union = builder.build().unwrap();
1064
1065        let expected_type_ids = vec![0_i8, 1, 2, 0, 2, 0, 1];
1066        let expected_offsets = vec![0_i32, 0, 0, 1, 1, 2, 1];
1067        let expected_array_values = [1_i32, 2, 3, 4, 5, 6, 7];
1068
1069        // Check type ids
1070        assert_eq!(*union.type_ids(), expected_type_ids);
1071        for (i, id) in expected_type_ids.iter().enumerate() {
1072            assert_eq!(id, &union.type_id(i));
1073        }
1074
1075        // Check offsets
1076        assert_eq!(*union.offsets().unwrap(), expected_offsets);
1077        for (i, id) in expected_offsets.iter().enumerate() {
1078            assert_eq!(union.value_offset(i), *id as usize);
1079        }
1080
1081        // Check data
1082        assert_eq!(
1083            *union.child(0).as_primitive::<Int32Type>().values(),
1084            [1_i32, 4, 6]
1085        );
1086        assert_eq!(
1087            *union.child(1).as_primitive::<Int32Type>().values(),
1088            [2_i32, 7]
1089        );
1090        assert_eq!(
1091            *union.child(2).as_primitive::<Int32Type>().values(),
1092            [3_i32, 5]
1093        );
1094
1095        assert_eq!(expected_array_values.len(), union.len());
1096        for (i, expected_value) in expected_array_values.iter().enumerate() {
1097            assert!(!union.is_null(i));
1098            let slot = union.value(i);
1099            let slot = slot.as_any().downcast_ref::<Int32Array>().unwrap();
1100            assert_eq!(slot.len(), 1);
1101            let value = slot.value(0);
1102            assert_eq!(expected_value, &value);
1103        }
1104    }
1105
1106    #[test]
1107    fn slice_union_array_single_field() {
1108        // Dense Union
1109        // [1, null, 3, null, 4]
1110        let union_array = {
1111            let mut builder = UnionBuilder::new_dense();
1112            builder.append::<Int32Type>("a", 1).unwrap();
1113            builder.append_null::<Int32Type>("a").unwrap();
1114            builder.append::<Int32Type>("a", 3).unwrap();
1115            builder.append_null::<Int32Type>("a").unwrap();
1116            builder.append::<Int32Type>("a", 4).unwrap();
1117            builder.build().unwrap()
1118        };
1119
1120        // [null, 3, null]
1121        let union_slice = union_array.slice(1, 3);
1122        let logical_nulls = union_slice.logical_nulls().unwrap();
1123
1124        assert_eq!(logical_nulls.len(), 3);
1125        assert!(logical_nulls.is_null(0));
1126        assert!(logical_nulls.is_valid(1));
1127        assert!(logical_nulls.is_null(2));
1128    }
1129
1130    #[test]
1131    fn test_dense_i32_large() {
1132        let mut builder = UnionBuilder::new_dense();
1133
1134        let expected_type_ids = vec![0_i8; 1024];
1135        let expected_offsets: Vec<_> = (0..1024).collect();
1136        let expected_array_values: Vec<_> = (1..=1024).collect();
1137
1138        expected_array_values
1139            .iter()
1140            .for_each(|v| builder.append::<Int32Type>("a", *v).unwrap());
1141
1142        let union = builder.build().unwrap();
1143
1144        // Check type ids
1145        assert_eq!(*union.type_ids(), expected_type_ids);
1146        for (i, id) in expected_type_ids.iter().enumerate() {
1147            assert_eq!(id, &union.type_id(i));
1148        }
1149
1150        // Check offsets
1151        assert_eq!(*union.offsets().unwrap(), expected_offsets);
1152        for (i, id) in expected_offsets.iter().enumerate() {
1153            assert_eq!(union.value_offset(i), *id as usize);
1154        }
1155
1156        for (i, expected_value) in expected_array_values.iter().enumerate() {
1157            assert!(!union.is_null(i));
1158            let slot = union.value(i);
1159            let slot = slot.as_primitive::<Int32Type>();
1160            assert_eq!(slot.len(), 1);
1161            let value = slot.value(0);
1162            assert_eq!(expected_value, &value);
1163        }
1164    }
1165
1166    #[test]
1167    fn test_dense_mixed() {
1168        let mut builder = UnionBuilder::new_dense();
1169        builder.append::<Int32Type>("a", 1).unwrap();
1170        builder.append::<Int64Type>("c", 3).unwrap();
1171        builder.append::<Int32Type>("a", 4).unwrap();
1172        builder.append::<Int64Type>("c", 5).unwrap();
1173        builder.append::<Int32Type>("a", 6).unwrap();
1174        let union = builder.build().unwrap();
1175
1176        assert_eq!(5, union.len());
1177        for i in 0..union.len() {
1178            let slot = union.value(i);
1179            assert!(!union.is_null(i));
1180            match i {
1181                0 => {
1182                    let slot = slot.as_any().downcast_ref::<Int32Array>().unwrap();
1183                    assert_eq!(slot.len(), 1);
1184                    let value = slot.value(0);
1185                    assert_eq!(1_i32, value);
1186                }
1187                1 => {
1188                    let slot = slot.as_any().downcast_ref::<Int64Array>().unwrap();
1189                    assert_eq!(slot.len(), 1);
1190                    let value = slot.value(0);
1191                    assert_eq!(3_i64, value);
1192                }
1193                2 => {
1194                    let slot = slot.as_any().downcast_ref::<Int32Array>().unwrap();
1195                    assert_eq!(slot.len(), 1);
1196                    let value = slot.value(0);
1197                    assert_eq!(4_i32, value);
1198                }
1199                3 => {
1200                    let slot = slot.as_any().downcast_ref::<Int64Array>().unwrap();
1201                    assert_eq!(slot.len(), 1);
1202                    let value = slot.value(0);
1203                    assert_eq!(5_i64, value);
1204                }
1205                4 => {
1206                    let slot = slot.as_any().downcast_ref::<Int32Array>().unwrap();
1207                    assert_eq!(slot.len(), 1);
1208                    let value = slot.value(0);
1209                    assert_eq!(6_i32, value);
1210                }
1211                _ => unreachable!(),
1212            }
1213        }
1214    }
1215
1216    #[test]
1217    fn test_dense_mixed_with_nulls() {
1218        let mut builder = UnionBuilder::new_dense();
1219        builder.append::<Int32Type>("a", 1).unwrap();
1220        builder.append::<Int64Type>("c", 3).unwrap();
1221        builder.append::<Int32Type>("a", 10).unwrap();
1222        builder.append_null::<Int32Type>("a").unwrap();
1223        builder.append::<Int32Type>("a", 6).unwrap();
1224        let union = builder.build().unwrap();
1225
1226        assert_eq!(5, union.len());
1227        for i in 0..union.len() {
1228            let slot = union.value(i);
1229            match i {
1230                0 => {
1231                    let slot = slot.as_any().downcast_ref::<Int32Array>().unwrap();
1232                    assert!(!slot.is_null(0));
1233                    assert_eq!(slot.len(), 1);
1234                    let value = slot.value(0);
1235                    assert_eq!(1_i32, value);
1236                }
1237                1 => {
1238                    let slot = slot.as_any().downcast_ref::<Int64Array>().unwrap();
1239                    assert!(!slot.is_null(0));
1240                    assert_eq!(slot.len(), 1);
1241                    let value = slot.value(0);
1242                    assert_eq!(3_i64, value);
1243                }
1244                2 => {
1245                    let slot = slot.as_any().downcast_ref::<Int32Array>().unwrap();
1246                    assert!(!slot.is_null(0));
1247                    assert_eq!(slot.len(), 1);
1248                    let value = slot.value(0);
1249                    assert_eq!(10_i32, value);
1250                }
1251                3 => assert!(slot.is_null(0)),
1252                4 => {
1253                    let slot = slot.as_any().downcast_ref::<Int32Array>().unwrap();
1254                    assert!(!slot.is_null(0));
1255                    assert_eq!(slot.len(), 1);
1256                    let value = slot.value(0);
1257                    assert_eq!(6_i32, value);
1258                }
1259                _ => unreachable!(),
1260            }
1261        }
1262    }
1263
1264    #[test]
1265    fn test_dense_mixed_with_nulls_and_offset() {
1266        let mut builder = UnionBuilder::new_dense();
1267        builder.append::<Int32Type>("a", 1).unwrap();
1268        builder.append::<Int64Type>("c", 3).unwrap();
1269        builder.append::<Int32Type>("a", 10).unwrap();
1270        builder.append_null::<Int32Type>("a").unwrap();
1271        builder.append::<Int32Type>("a", 6).unwrap();
1272        let union = builder.build().unwrap();
1273
1274        let slice = union.slice(2, 3);
1275        let new_union = slice.as_any().downcast_ref::<UnionArray>().unwrap();
1276
1277        assert_eq!(3, new_union.len());
1278        for i in 0..new_union.len() {
1279            let slot = new_union.value(i);
1280            match i {
1281                0 => {
1282                    let slot = slot.as_any().downcast_ref::<Int32Array>().unwrap();
1283                    assert!(!slot.is_null(0));
1284                    assert_eq!(slot.len(), 1);
1285                    let value = slot.value(0);
1286                    assert_eq!(10_i32, value);
1287                }
1288                1 => assert!(slot.is_null(0)),
1289                2 => {
1290                    let slot = slot.as_any().downcast_ref::<Int32Array>().unwrap();
1291                    assert!(!slot.is_null(0));
1292                    assert_eq!(slot.len(), 1);
1293                    let value = slot.value(0);
1294                    assert_eq!(6_i32, value);
1295                }
1296                _ => unreachable!(),
1297            }
1298        }
1299    }
1300
1301    #[test]
1302    fn test_dense_mixed_with_str() {
1303        let string_array = StringArray::from(vec!["foo", "bar", "baz"]);
1304        let int_array = Int32Array::from(vec![5, 6]);
1305        let float_array = Float64Array::from(vec![10.0]);
1306
1307        let type_ids = [1, 0, 0, 2, 0, 1].into_iter().collect::<ScalarBuffer<i8>>();
1308        let offsets = [0, 0, 1, 0, 2, 1]
1309            .into_iter()
1310            .collect::<ScalarBuffer<i32>>();
1311
1312        let fields = [
1313            (0, Arc::new(Field::new("A", DataType::Utf8, false))),
1314            (1, Arc::new(Field::new("B", DataType::Int32, false))),
1315            (2, Arc::new(Field::new("C", DataType::Float64, false))),
1316        ]
1317        .into_iter()
1318        .collect::<UnionFields>();
1319        let children = [
1320            Arc::new(string_array) as Arc<dyn Array>,
1321            Arc::new(int_array),
1322            Arc::new(float_array),
1323        ]
1324        .into_iter()
1325        .collect();
1326        let array =
1327            UnionArray::try_new(fields, type_ids.clone(), Some(offsets.clone()), children).unwrap();
1328
1329        // Check type ids
1330        assert_eq!(*array.type_ids(), type_ids);
1331        for (i, id) in type_ids.iter().enumerate() {
1332            assert_eq!(id, &array.type_id(i));
1333        }
1334
1335        // Check offsets
1336        assert_eq!(*array.offsets().unwrap(), offsets);
1337        for (i, id) in offsets.iter().enumerate() {
1338            assert_eq!(*id as usize, array.value_offset(i));
1339        }
1340
1341        // Check values
1342        assert_eq!(6, array.len());
1343
1344        let slot = array.value(0);
1345        let value = slot.as_any().downcast_ref::<Int32Array>().unwrap().value(0);
1346        assert_eq!(5, value);
1347
1348        let slot = array.value(1);
1349        let value = slot
1350            .as_any()
1351            .downcast_ref::<StringArray>()
1352            .unwrap()
1353            .value(0);
1354        assert_eq!("foo", value);
1355
1356        let slot = array.value(2);
1357        let value = slot
1358            .as_any()
1359            .downcast_ref::<StringArray>()
1360            .unwrap()
1361            .value(0);
1362        assert_eq!("bar", value);
1363
1364        let slot = array.value(3);
1365        let value = slot
1366            .as_any()
1367            .downcast_ref::<Float64Array>()
1368            .unwrap()
1369            .value(0);
1370        assert_eq!(10.0, value);
1371
1372        let slot = array.value(4);
1373        let value = slot
1374            .as_any()
1375            .downcast_ref::<StringArray>()
1376            .unwrap()
1377            .value(0);
1378        assert_eq!("baz", value);
1379
1380        let slot = array.value(5);
1381        let value = slot.as_any().downcast_ref::<Int32Array>().unwrap().value(0);
1382        assert_eq!(6, value);
1383    }
1384
1385    #[test]
1386    fn test_sparse_i32() {
1387        let mut builder = UnionBuilder::new_sparse();
1388        builder.append::<Int32Type>("a", 1).unwrap();
1389        builder.append::<Int32Type>("b", 2).unwrap();
1390        builder.append::<Int32Type>("c", 3).unwrap();
1391        builder.append::<Int32Type>("a", 4).unwrap();
1392        builder.append::<Int32Type>("c", 5).unwrap();
1393        builder.append::<Int32Type>("a", 6).unwrap();
1394        builder.append::<Int32Type>("b", 7).unwrap();
1395        let union = builder.build().unwrap();
1396
1397        let expected_type_ids = vec![0_i8, 1, 2, 0, 2, 0, 1];
1398        let expected_array_values = [1_i32, 2, 3, 4, 5, 6, 7];
1399
1400        // Check type ids
1401        assert_eq!(*union.type_ids(), expected_type_ids);
1402        for (i, id) in expected_type_ids.iter().enumerate() {
1403            assert_eq!(id, &union.type_id(i));
1404        }
1405
1406        // Check offsets, sparse union should only have a single buffer
1407        assert!(union.offsets().is_none());
1408
1409        // Check data
1410        assert_eq!(
1411            *union.child(0).as_primitive::<Int32Type>().values(),
1412            [1_i32, 0, 0, 4, 0, 6, 0],
1413        );
1414        assert_eq!(
1415            *union.child(1).as_primitive::<Int32Type>().values(),
1416            [0_i32, 2_i32, 0, 0, 0, 0, 7]
1417        );
1418        assert_eq!(
1419            *union.child(2).as_primitive::<Int32Type>().values(),
1420            [0_i32, 0, 3_i32, 0, 5, 0, 0]
1421        );
1422
1423        assert_eq!(expected_array_values.len(), union.len());
1424        for (i, expected_value) in expected_array_values.iter().enumerate() {
1425            assert!(!union.is_null(i));
1426            let slot = union.value(i);
1427            let slot = slot.as_any().downcast_ref::<Int32Array>().unwrap();
1428            assert_eq!(slot.len(), 1);
1429            let value = slot.value(0);
1430            assert_eq!(expected_value, &value);
1431        }
1432    }
1433
1434    #[test]
1435    fn test_sparse_mixed() {
1436        let mut builder = UnionBuilder::new_sparse();
1437        builder.append::<Int32Type>("a", 1).unwrap();
1438        builder.append::<Float64Type>("c", 3.0).unwrap();
1439        builder.append::<Int32Type>("a", 4).unwrap();
1440        builder.append::<Float64Type>("c", 5.0).unwrap();
1441        builder.append::<Int32Type>("a", 6).unwrap();
1442        let union = builder.build().unwrap();
1443
1444        let expected_type_ids = vec![0_i8, 1, 0, 1, 0];
1445
1446        // Check type ids
1447        assert_eq!(*union.type_ids(), expected_type_ids);
1448        for (i, id) in expected_type_ids.iter().enumerate() {
1449            assert_eq!(id, &union.type_id(i));
1450        }
1451
1452        // Check offsets, sparse union should only have a single buffer, i.e. no offsets
1453        assert!(union.offsets().is_none());
1454
1455        for i in 0..union.len() {
1456            let slot = union.value(i);
1457            assert!(!union.is_null(i));
1458            match i {
1459                0 => {
1460                    let slot = slot.as_any().downcast_ref::<Int32Array>().unwrap();
1461                    assert_eq!(slot.len(), 1);
1462                    let value = slot.value(0);
1463                    assert_eq!(1_i32, value);
1464                }
1465                1 => {
1466                    let slot = slot.as_any().downcast_ref::<Float64Array>().unwrap();
1467                    assert_eq!(slot.len(), 1);
1468                    let value = slot.value(0);
1469                    assert_eq!(value, 3_f64);
1470                }
1471                2 => {
1472                    let slot = slot.as_any().downcast_ref::<Int32Array>().unwrap();
1473                    assert_eq!(slot.len(), 1);
1474                    let value = slot.value(0);
1475                    assert_eq!(4_i32, value);
1476                }
1477                3 => {
1478                    let slot = slot.as_any().downcast_ref::<Float64Array>().unwrap();
1479                    assert_eq!(slot.len(), 1);
1480                    let value = slot.value(0);
1481                    assert_eq!(5_f64, value);
1482                }
1483                4 => {
1484                    let slot = slot.as_any().downcast_ref::<Int32Array>().unwrap();
1485                    assert_eq!(slot.len(), 1);
1486                    let value = slot.value(0);
1487                    assert_eq!(6_i32, value);
1488                }
1489                _ => unreachable!(),
1490            }
1491        }
1492    }
1493
1494    #[test]
1495    fn test_sparse_mixed_with_nulls() {
1496        let mut builder = UnionBuilder::new_sparse();
1497        builder.append::<Int32Type>("a", 1).unwrap();
1498        builder.append_null::<Int32Type>("a").unwrap();
1499        builder.append::<Float64Type>("c", 3.0).unwrap();
1500        builder.append::<Int32Type>("a", 4).unwrap();
1501        let union = builder.build().unwrap();
1502
1503        let expected_type_ids = vec![0_i8, 0, 1, 0];
1504
1505        // Check type ids
1506        assert_eq!(*union.type_ids(), expected_type_ids);
1507        for (i, id) in expected_type_ids.iter().enumerate() {
1508            assert_eq!(id, &union.type_id(i));
1509        }
1510
1511        // Check offsets, sparse union should only have a single buffer, i.e. no offsets
1512        assert!(union.offsets().is_none());
1513
1514        for i in 0..union.len() {
1515            let slot = union.value(i);
1516            match i {
1517                0 => {
1518                    let slot = slot.as_any().downcast_ref::<Int32Array>().unwrap();
1519                    assert!(!slot.is_null(0));
1520                    assert_eq!(slot.len(), 1);
1521                    let value = slot.value(0);
1522                    assert_eq!(1_i32, value);
1523                }
1524                1 => assert!(slot.is_null(0)),
1525                2 => {
1526                    let slot = slot.as_any().downcast_ref::<Float64Array>().unwrap();
1527                    assert!(!slot.is_null(0));
1528                    assert_eq!(slot.len(), 1);
1529                    let value = slot.value(0);
1530                    assert_eq!(value, 3_f64);
1531                }
1532                3 => {
1533                    let slot = slot.as_any().downcast_ref::<Int32Array>().unwrap();
1534                    assert!(!slot.is_null(0));
1535                    assert_eq!(slot.len(), 1);
1536                    let value = slot.value(0);
1537                    assert_eq!(4_i32, value);
1538                }
1539                _ => unreachable!(),
1540            }
1541        }
1542    }
1543
1544    #[test]
1545    fn test_sparse_mixed_with_nulls_and_offset() {
1546        let mut builder = UnionBuilder::new_sparse();
1547        builder.append::<Int32Type>("a", 1).unwrap();
1548        builder.append_null::<Int32Type>("a").unwrap();
1549        builder.append::<Float64Type>("c", 3.0).unwrap();
1550        builder.append_null::<Float64Type>("c").unwrap();
1551        builder.append::<Int32Type>("a", 4).unwrap();
1552        let union = builder.build().unwrap();
1553
1554        let slice = union.slice(1, 4);
1555        let new_union = slice.as_any().downcast_ref::<UnionArray>().unwrap();
1556
1557        assert_eq!(4, new_union.len());
1558        for i in 0..new_union.len() {
1559            let slot = new_union.value(i);
1560            match i {
1561                0 => assert!(slot.is_null(0)),
1562                1 => {
1563                    let slot = slot.as_primitive::<Float64Type>();
1564                    assert!(!slot.is_null(0));
1565                    assert_eq!(slot.len(), 1);
1566                    let value = slot.value(0);
1567                    assert_eq!(value, 3_f64);
1568                }
1569                2 => assert!(slot.is_null(0)),
1570                3 => {
1571                    let slot = slot.as_primitive::<Int32Type>();
1572                    assert!(!slot.is_null(0));
1573                    assert_eq!(slot.len(), 1);
1574                    let value = slot.value(0);
1575                    assert_eq!(4_i32, value);
1576                }
1577                _ => unreachable!(),
1578            }
1579        }
1580    }
1581
1582    fn test_union_validity(union_array: &UnionArray) {
1583        assert_eq!(union_array.null_count(), 0);
1584
1585        for i in 0..union_array.len() {
1586            assert!(!union_array.is_null(i));
1587            assert!(union_array.is_valid(i));
1588        }
1589    }
1590
1591    #[rstest]
1592    fn test_union_array_validity(
1593        #[values(UnionBuilder::new_sparse(), UnionBuilder::new_dense())] mut builder: UnionBuilder,
1594    ) {
1595        builder.append::<Int32Type>("a", 1).unwrap();
1596        builder.append_null::<Int32Type>("a").unwrap();
1597        builder.append::<Float64Type>("c", 3.0).unwrap();
1598        builder.append_null::<Float64Type>("c").unwrap();
1599        builder.append::<Int32Type>("a", 4).unwrap();
1600        let union = builder.build().unwrap();
1601        test_union_validity(&union);
1602    }
1603
1604    #[test]
1605    fn test_type_check() {
1606        let mut builder = UnionBuilder::new_sparse();
1607        builder.append::<Float32Type>("a", 1.0).unwrap();
1608        let err = builder.append::<Int32Type>("a", 1).unwrap_err().to_string();
1609        assert!(
1610            err.contains(
1611                "Attempt to write col \"a\" with type Int32 doesn't match existing type Float32"
1612            ),
1613            "{}",
1614            err
1615        );
1616    }
1617
1618    #[rstest]
1619    fn slice_union_array(
1620        #[values(UnionBuilder::new_sparse(), UnionBuilder::new_dense())] builder: UnionBuilder,
1621    ) {
1622        // [1, null, 3.0, null, 4]
1623        fn create_union(mut builder: UnionBuilder) -> UnionArray {
1624            builder.append::<Int32Type>("a", 1).unwrap();
1625            builder.append_null::<Int32Type>("a").unwrap();
1626            builder.append::<Float64Type>("c", 3.0).unwrap();
1627            builder.append_null::<Float64Type>("c").unwrap();
1628            builder.append::<Int32Type>("a", 4).unwrap();
1629            builder.build().unwrap()
1630        }
1631
1632        fn create_batch(union: UnionArray) -> RecordBatch {
1633            let schema = Schema::new(vec![Field::new(
1634                "struct_array",
1635                union.data_type().clone(),
1636                true,
1637            )]);
1638
1639            RecordBatch::try_new(Arc::new(schema), vec![Arc::new(union)]).unwrap()
1640        }
1641
1642        fn test_slice_union(record_batch_slice: RecordBatch) {
1643            let union_slice = record_batch_slice
1644                .column(0)
1645                .as_any()
1646                .downcast_ref::<UnionArray>()
1647                .unwrap();
1648
1649            assert_eq!(union_slice.type_id(0), 0);
1650            assert_eq!(union_slice.type_id(1), 1);
1651            assert_eq!(union_slice.type_id(2), 1);
1652
1653            let slot = union_slice.value(0);
1654            let array = slot.as_primitive::<Int32Type>();
1655            assert_eq!(array.len(), 1);
1656            assert!(array.is_null(0));
1657
1658            let slot = union_slice.value(1);
1659            let array = slot.as_primitive::<Float64Type>();
1660            assert_eq!(array.len(), 1);
1661            assert!(array.is_valid(0));
1662            assert_eq!(array.value(0), 3.0);
1663
1664            let slot = union_slice.value(2);
1665            let array = slot.as_primitive::<Float64Type>();
1666            assert_eq!(array.len(), 1);
1667            assert!(array.is_null(0));
1668        }
1669
1670        let record_batch = create_batch(create_union(builder));
1671        // [null, 3.0, null]
1672        let record_batch_slice = record_batch.slice(1, 3);
1673        test_slice_union(record_batch_slice);
1674    }
1675
1676    #[rstest]
1677    #[case::middle_slice(1, 2)]
1678    #[case::prefix_slice(0, 2)]
1679    #[case::suffix_slice(2, 2)]
1680    #[case::empty_at_start(0, 0)]
1681    #[case::empty_at_end(4, 0)]
1682    #[case::whole_array(0, 4)]
1683    fn test_union_from_sliced_array_data(
1684        #[case] offset: usize,
1685        #[case] len: usize,
1686        #[values(UnionMode::Sparse, UnionMode::Dense)] mode: UnionMode,
1687    ) {
1688        let fields = UnionFields::try_new(
1689            [3, 7],
1690            [
1691                Field::new("ints", DataType::Int32, false),
1692                Field::new("floats", DataType::Float64, false),
1693            ],
1694        )
1695        .unwrap();
1696        let offsets = (mode == UnionMode::Dense).then(|| vec![0, 1, 2, 3].into());
1697        let array = UnionArray::try_new(
1698            fields,
1699            vec![3, 7, 3, 7].into(),
1700            offsets,
1701            vec![
1702                Arc::new(Int32Array::from(vec![10, 20, 30, 40])),
1703                Arc::new(Float64Array::from(vec![1.0, 2.0, 3.0, 4.0])),
1704            ],
1705        )
1706        .unwrap();
1707
1708        let expected = array.slice(offset, len);
1709        let actual = make_array(array.to_data().slice(offset, len));
1710        let actual = actual.as_any().downcast_ref::<UnionArray>().unwrap();
1711        for i in 0..len {
1712            assert_eq!(actual.value(i).to_data(), expected.value(i).to_data());
1713        }
1714        assert_eq!(actual.to_data(), expected.to_data());
1715    }
1716
1717    #[test]
1718    fn test_sparse_union_from_sliced_array_data_logical_nulls() {
1719        let child = Int32Array::from(vec![Some(10), None, Some(30)]);
1720        let fields =
1721            UnionFields::try_new([0], [Field::new("ints", DataType::Int32, true)]).unwrap();
1722        let array =
1723            UnionArray::try_new(fields, vec![0, 0, 0].into(), None, vec![Arc::new(child)]).unwrap();
1724        for (offset, len) in [(0, 1), (1, 1), (2, 1), (3, 0)] {
1725            let expected = array.slice(offset, len);
1726            let actual = make_array(array.to_data().slice(offset, len));
1727            assert_eq!(actual.logical_nulls(), expected.logical_nulls());
1728            assert_eq!(actual.to_data(), expected.to_data());
1729        }
1730    }
1731
1732    #[test]
1733    fn test_custom_type_ids() {
1734        let data_type = DataType::Union(
1735            UnionFields::try_new(
1736                vec![8, 4, 9],
1737                vec![
1738                    Field::new("strings", DataType::Utf8, false),
1739                    Field::new("integers", DataType::Int32, false),
1740                    Field::new("floats", DataType::Float64, false),
1741                ],
1742            )
1743            .unwrap(),
1744            UnionMode::Dense,
1745        );
1746
1747        let string_array = StringArray::from(vec!["foo", "bar", "baz"]);
1748        let int_array = Int32Array::from(vec![5, 6, 4]);
1749        let float_array = Float64Array::from(vec![10.0]);
1750
1751        let type_ids = Buffer::from_vec(vec![4_i8, 8, 4, 8, 9, 4, 8]);
1752        let value_offsets = Buffer::from_vec(vec![0_i32, 0, 1, 1, 0, 2, 2]);
1753
1754        let data = ArrayData::builder(data_type)
1755            .len(7)
1756            .buffers(vec![type_ids, value_offsets])
1757            .child_data(vec![
1758                string_array.into_data(),
1759                int_array.into_data(),
1760                float_array.into_data(),
1761            ])
1762            .build()
1763            .unwrap();
1764
1765        let array = UnionArray::from(data);
1766
1767        let v = array.value(0);
1768        assert_eq!(v.data_type(), &DataType::Int32);
1769        assert_eq!(v.len(), 1);
1770        assert_eq!(v.as_primitive::<Int32Type>().value(0), 5);
1771
1772        let v = array.value(1);
1773        assert_eq!(v.data_type(), &DataType::Utf8);
1774        assert_eq!(v.len(), 1);
1775        assert_eq!(v.as_string::<i32>().value(0), "foo");
1776
1777        let v = array.value(2);
1778        assert_eq!(v.data_type(), &DataType::Int32);
1779        assert_eq!(v.len(), 1);
1780        assert_eq!(v.as_primitive::<Int32Type>().value(0), 6);
1781
1782        let v = array.value(3);
1783        assert_eq!(v.data_type(), &DataType::Utf8);
1784        assert_eq!(v.len(), 1);
1785        assert_eq!(v.as_string::<i32>().value(0), "bar");
1786
1787        let v = array.value(4);
1788        assert_eq!(v.data_type(), &DataType::Float64);
1789        assert_eq!(v.len(), 1);
1790        assert_eq!(v.as_primitive::<Float64Type>().value(0), 10.0);
1791
1792        let v = array.value(5);
1793        assert_eq!(v.data_type(), &DataType::Int32);
1794        assert_eq!(v.len(), 1);
1795        assert_eq!(v.as_primitive::<Int32Type>().value(0), 4);
1796
1797        let v = array.value(6);
1798        assert_eq!(v.data_type(), &DataType::Utf8);
1799        assert_eq!(v.len(), 1);
1800        assert_eq!(v.as_string::<i32>().value(0), "baz");
1801    }
1802
1803    #[test]
1804    fn into_parts() {
1805        let mut builder = UnionBuilder::new_dense();
1806        builder.append::<Int32Type>("a", 1).unwrap();
1807        builder.append::<Int8Type>("b", 2).unwrap();
1808        builder.append::<Int32Type>("a", 3).unwrap();
1809        let dense_union = builder.build().unwrap();
1810
1811        let field = [
1812            &Arc::new(Field::new("a", DataType::Int32, false)),
1813            &Arc::new(Field::new("b", DataType::Int8, false)),
1814        ];
1815        let (union_fields, type_ids, offsets, children) = dense_union.into_parts();
1816        assert_eq!(
1817            union_fields
1818                .iter()
1819                .map(|(_, field)| field)
1820                .collect::<Vec<_>>(),
1821            field
1822        );
1823        assert_eq!(type_ids, [0, 1, 0]);
1824        assert!(offsets.is_some());
1825        assert_eq!(offsets.as_ref().unwrap(), &[0, 0, 1]);
1826
1827        let result = UnionArray::try_new(union_fields, type_ids, offsets, children);
1828        assert!(result.is_ok());
1829        assert_eq!(result.unwrap().len(), 3);
1830
1831        let mut builder = UnionBuilder::new_sparse();
1832        builder.append::<Int32Type>("a", 1).unwrap();
1833        builder.append::<Int8Type>("b", 2).unwrap();
1834        builder.append::<Int32Type>("a", 3).unwrap();
1835        let sparse_union = builder.build().unwrap();
1836
1837        let (union_fields, type_ids, offsets, children) = sparse_union.into_parts();
1838        assert_eq!(type_ids, [0, 1, 0]);
1839        assert!(offsets.is_none());
1840
1841        let result = UnionArray::try_new(union_fields, type_ids, offsets, children);
1842        assert!(result.is_ok());
1843        assert_eq!(result.unwrap().len(), 3);
1844    }
1845
1846    #[test]
1847    fn into_parts_custom_type_ids() {
1848        let set_field_type_ids: [i8; 3] = [8, 4, 9];
1849        let data_type = DataType::Union(
1850            UnionFields::try_new(
1851                set_field_type_ids,
1852                [
1853                    Field::new("strings", DataType::Utf8, false),
1854                    Field::new("integers", DataType::Int32, false),
1855                    Field::new("floats", DataType::Float64, false),
1856                ],
1857            )
1858            .unwrap(),
1859            UnionMode::Dense,
1860        );
1861        let string_array = StringArray::from(vec!["foo", "bar", "baz"]);
1862        let int_array = Int32Array::from(vec![5, 6, 4]);
1863        let float_array = Float64Array::from(vec![10.0]);
1864        let type_ids = Buffer::from_vec(vec![4_i8, 8, 4, 8, 9, 4, 8]);
1865        let value_offsets = Buffer::from_vec(vec![0_i32, 0, 1, 1, 0, 2, 2]);
1866        let data = ArrayData::builder(data_type)
1867            .len(7)
1868            .buffers(vec![type_ids, value_offsets])
1869            .child_data(vec![
1870                string_array.into_data(),
1871                int_array.into_data(),
1872                float_array.into_data(),
1873            ])
1874            .build()
1875            .unwrap();
1876        let array = UnionArray::from(data);
1877
1878        let (union_fields, type_ids, offsets, children) = array.into_parts();
1879        assert_eq!(
1880            type_ids.iter().collect::<HashSet<_>>(),
1881            set_field_type_ids.iter().collect::<HashSet<_>>()
1882        );
1883        let result = UnionArray::try_new(union_fields, type_ids, offsets, children);
1884        assert!(result.is_ok());
1885        let array = result.unwrap();
1886        assert_eq!(array.len(), 7);
1887    }
1888
1889    #[test]
1890    fn test_dense_union_large_child() {
1891        let fields =
1892            UnionFields::try_new([3], [Field::new("nulls", DataType::Null, true)]).unwrap();
1893
1894        // NullArray represents these lengths without allocating a values buffer.
1895        for child_len in [i32::MAX as usize + 1, i32::MAX as usize + 2] {
1896            let array = UnionArray::try_new(
1897                fields.clone(),
1898                vec![3, 3].into(),
1899                Some(vec![0, i32::MAX].into()),
1900                vec![Arc::new(NullArray::new(child_len))],
1901            )
1902            .unwrap();
1903
1904            assert_eq!(array.child(3).len(), child_len);
1905            assert_eq!(array.value(1).len(), 1);
1906            array.to_data().validate_full().unwrap();
1907        }
1908    }
1909
1910    #[test]
1911    fn test_sparse_union_rejects_child_length_mismatch() {
1912        let fields = UnionFields::try_new(
1913            [3, 2],
1914            [
1915                Field::new("a", DataType::Utf8, false),
1916                Field::new("b", DataType::Utf8, false),
1917            ],
1918        )
1919        .unwrap();
1920        let children = vec![
1921            Arc::new(StringArray::from_iter_values(["a", "b"])) as _,
1922            Arc::new(StringArray::from_iter_values(["c", "d"])) as _,
1923        ];
1924
1925        let type_ids = vec![3, 3, 2].into();
1926        let err = UnionArray::try_new(fields, type_ids, None, children).unwrap_err();
1927        assert_eq!(
1928            err.to_string(),
1929            "Invalid argument error: Sparse union child arrays must be equal in length to the length of the union"
1930        );
1931    }
1932
1933    #[rstest]
1934    #[case::unassigned_id(1)]
1935    #[case::id_above_max(7)]
1936    fn test_union_rejects_unknown_type_id(#[case] unknown_id: i8) {
1937        let fields = UnionFields::try_new(
1938            [3, 2],
1939            [
1940                Field::new("a", DataType::Utf8, false),
1941                Field::new("b", DataType::Utf8, false),
1942            ],
1943        )
1944        .unwrap();
1945        let children = vec![
1946            Arc::new(StringArray::from_iter_values(["a", "b"])) as _,
1947            Arc::new(StringArray::from_iter_values(["c", "d"])) as _,
1948        ];
1949        let type_ids = vec![unknown_id, 2].into();
1950        let err = UnionArray::try_new(fields, type_ids, None, children).unwrap_err();
1951        assert_eq!(
1952            err.to_string(),
1953            "Invalid argument error: Type Ids values must match one of the field type ids"
1954        );
1955    }
1956
1957    #[test]
1958    fn test_dense_union_accepts_valid_offsets() {
1959        let fields = UnionFields::try_new(
1960            [3, 2],
1961            [
1962                Field::new("a", DataType::Utf8, false),
1963                Field::new("b", DataType::Utf8, false),
1964            ],
1965        )
1966        .unwrap();
1967        let children = vec![
1968            Arc::new(StringArray::from_iter_values(["a", "b"])) as _,
1969            Arc::new(StringArray::from_iter_values(["c"])) as _,
1970        ];
1971        let type_ids = ScalarBuffer::from(vec![3_i8, 3, 2]);
1972        let offsets = Some(vec![0, 1, 0].into());
1973        UnionArray::try_new(fields, type_ids, offsets, children).unwrap();
1974    }
1975
1976    #[rstest]
1977    #[case::out_of_bounds(
1978        vec![0, 1, 1],
1979        "Invalid argument error: Offsets must be non-negative and within the length of the Array"
1980    )]
1981    #[case::negative(
1982        vec![0, -1, 0],
1983        "Invalid argument error: Offsets must be non-negative and within the length of the Array"
1984    )]
1985    #[case::length_mismatch(
1986        vec![0, 1],
1987        "Invalid argument error: Type Ids and Offsets lengths must match"
1988    )]
1989    fn test_dense_union_rejects_invalid_offsets(
1990        #[case] offsets: Vec<i32>,
1991        #[case] expected_error: &str,
1992    ) {
1993        let fields = UnionFields::try_new(
1994            [3, 2],
1995            [
1996                Field::new("a", DataType::Utf8, false),
1997                Field::new("b", DataType::Utf8, false),
1998            ],
1999        )
2000        .unwrap();
2001        let children = vec![
2002            Arc::new(StringArray::from_iter_values(["a", "b"])) as _,
2003            Arc::new(StringArray::from_iter_values(["c"])) as _,
2004        ];
2005        let type_ids = ScalarBuffer::from(vec![3_i8, 3, 2]);
2006        let err =
2007            UnionArray::try_new(fields, type_ids, Some(offsets.into()), children).unwrap_err();
2008        assert_eq!(err.to_string(), expected_error);
2009    }
2010
2011    #[test]
2012    fn test_union_rejects_child_count_mismatch() {
2013        let fields = UnionFields::try_new(
2014            [3, 2],
2015            [
2016                Field::new("a", DataType::Utf8, false),
2017                Field::new("b", DataType::Utf8, false),
2018            ],
2019        )
2020        .unwrap();
2021        let type_ids = ScalarBuffer::from(vec![3_i8, 3, 2]);
2022        let err = UnionArray::try_new(fields, type_ids, None, vec![]).unwrap_err();
2023
2024        assert_eq!(
2025            err.to_string(),
2026            "Invalid argument error: Union fields length must match child arrays length"
2027        );
2028    }
2029
2030    #[test]
2031    fn test_logical_nulls_fast_paths() {
2032        // fields.len() <= 1
2033        let array = UnionArray::try_new(UnionFields::empty(), vec![].into(), None, vec![]).unwrap();
2034
2035        assert_eq!(array.logical_nulls(), None);
2036
2037        let fields = UnionFields::try_new(
2038            [1, 3],
2039            [
2040                Field::new("a", DataType::Int8, false), // non nullable
2041                Field::new("b", DataType::Int8, false), // non nullable
2042            ],
2043        )
2044        .unwrap();
2045        let array = UnionArray::try_new(
2046            fields,
2047            vec![1].into(),
2048            None,
2049            vec![
2050                Arc::new(Int8Array::from_value(5, 1)),
2051                Arc::new(Int8Array::from_value(5, 1)),
2052            ],
2053        )
2054        .unwrap();
2055
2056        assert_eq!(array.logical_nulls(), None);
2057
2058        let nullable_fields = UnionFields::try_new(
2059            [1, 3],
2060            [
2061                Field::new("a", DataType::Int8, true), // nullable but without nulls
2062                Field::new("b", DataType::Int8, true), // nullable but without nulls
2063            ],
2064        )
2065        .unwrap();
2066        let array = UnionArray::try_new(
2067            nullable_fields.clone(),
2068            vec![1, 1].into(),
2069            None,
2070            vec![
2071                Arc::new(Int8Array::from_value(-5, 2)), // nullable but without nulls
2072                Arc::new(Int8Array::from_value(-5, 2)), // nullable but without nulls
2073            ],
2074        )
2075        .unwrap();
2076
2077        assert_eq!(array.logical_nulls(), None);
2078
2079        let array = UnionArray::try_new(
2080            nullable_fields.clone(),
2081            vec![1, 1].into(),
2082            None,
2083            vec![
2084                // every child is completely null
2085                Arc::new(Int8Array::new_null(2)), // all null, same len as it's parent
2086                Arc::new(Int8Array::new_null(2)), // all null, same len as it's parent
2087            ],
2088        )
2089        .unwrap();
2090
2091        assert_eq!(array.logical_nulls(), Some(NullBuffer::new_null(2)));
2092
2093        let array = UnionArray::try_new(
2094            nullable_fields.clone(),
2095            vec![1, 1].into(),
2096            Some(vec![0, 1].into()),
2097            vec![
2098                // every child is completely null
2099                Arc::new(Int8Array::new_null(3)), // bigger that parent
2100                Arc::new(Int8Array::new_null(3)), // bigger that parent
2101            ],
2102        )
2103        .unwrap();
2104
2105        assert_eq!(array.logical_nulls(), Some(NullBuffer::new_null(2)));
2106    }
2107
2108    #[test]
2109    fn test_dense_union_logical_nulls_gather() {
2110        // union of [{A=1}, {A=2}, {B=3.2}, {B=}, {C=}, {C=}]
2111        let int_array = Int32Array::from(vec![1, 2]);
2112        let float_array = Float64Array::from(vec![Some(3.2), None]);
2113        let str_array = StringArray::new_null(1);
2114        let type_ids = [1, 1, 3, 3, 4, 4].into_iter().collect::<ScalarBuffer<i8>>();
2115        let offsets = [0, 1, 0, 1, 0, 0]
2116            .into_iter()
2117            .collect::<ScalarBuffer<i32>>();
2118
2119        let children = vec![
2120            Arc::new(int_array) as Arc<dyn Array>,
2121            Arc::new(float_array),
2122            Arc::new(str_array),
2123        ];
2124
2125        let array = UnionArray::try_new(union_fields(), type_ids, Some(offsets), children).unwrap();
2126
2127        let expected = BooleanBuffer::from(vec![true, true, true, false, false, false]);
2128
2129        assert_eq!(expected, array.logical_nulls().unwrap().into_inner());
2130        assert_eq!(expected, array.gather_nulls(array.fields_logical_nulls()));
2131    }
2132
2133    #[test]
2134    fn test_dense_union_one_field_nonzero_type_id_logical_nulls() {
2135        let fields = UnionFields::try_new([5], [Field::new("a", DataType::Int32, true)]).unwrap();
2136        let child = Arc::new(Int32Array::from(vec![None, Some(1)]));
2137        let array = UnionArray::try_new(
2138            fields,
2139            vec![5, 5, 5].into(),
2140            Some(vec![1, 0, 1].into()),
2141            vec![child],
2142        )
2143        .unwrap();
2144
2145        let expected = NullBuffer::from(vec![true, false, true]);
2146        assert_eq!(array.logical_nulls(), Some(expected));
2147        assert_eq!(array.logical_null_count(), 1);
2148    }
2149
2150    #[test]
2151    fn test_sparse_union_logical_nulls_mask_all_nulls_skip_one() {
2152        let fields: UnionFields = [
2153            (1, Arc::new(Field::new("A", DataType::Int32, true))),
2154            (3, Arc::new(Field::new("B", DataType::Float64, true))),
2155        ]
2156        .into_iter()
2157        .collect();
2158
2159        // union of [{A=}, {A=}, {B=3.2}, {B=}]
2160        let int_array = Int32Array::new_null(4);
2161        let float_array = Float64Array::from(vec![None, None, Some(3.2), None]);
2162        let type_ids = [1, 1, 3, 3].into_iter().collect::<ScalarBuffer<i8>>();
2163
2164        let children = vec![Arc::new(int_array) as Arc<dyn Array>, Arc::new(float_array)];
2165
2166        let array = UnionArray::try_new(fields.clone(), type_ids, None, children).unwrap();
2167
2168        let expected = BooleanBuffer::from(vec![false, false, true, false]);
2169
2170        assert_eq!(expected, array.logical_nulls().unwrap().into_inner());
2171        assert_eq!(
2172            expected,
2173            array.mask_sparse_all_with_nulls_skip_one(array.fields_logical_nulls())
2174        );
2175
2176        //like above, but repeated to generate two exact bitmasks and a non empty remainder
2177        let len = 2 * 64 + 32;
2178
2179        let int_array = Int32Array::new_null(len);
2180        let float_array = Float64Array::from_iter([Some(3.2), None].into_iter().cycle().take(len));
2181        let type_ids = ScalarBuffer::from_iter([1, 1, 3, 3].into_iter().cycle().take(len));
2182
2183        let array = UnionArray::try_new(
2184            fields,
2185            type_ids,
2186            None,
2187            vec![Arc::new(int_array), Arc::new(float_array)],
2188        )
2189        .unwrap();
2190
2191        let expected =
2192            BooleanBuffer::from_iter([false, false, true, false].into_iter().cycle().take(len));
2193
2194        assert_eq!(array.len(), len);
2195        assert_eq!(expected, array.logical_nulls().unwrap().into_inner());
2196        assert_eq!(
2197            expected,
2198            array.mask_sparse_all_with_nulls_skip_one(array.fields_logical_nulls())
2199        );
2200    }
2201
2202    #[test]
2203    fn test_sparse_union_logical_mask_mixed_nulls_skip_fully_valid() {
2204        // union of [{A=2}, {A=2}, {B=3.2}, {B=}, {C=}, {C=}]
2205        let int_array = Int32Array::from_value(2, 6);
2206        let float_array = Float64Array::from_value(4.2, 6);
2207        let str_array = StringArray::new_null(6);
2208        let type_ids = [1, 1, 3, 3, 4, 4].into_iter().collect::<ScalarBuffer<i8>>();
2209
2210        let children = vec![
2211            Arc::new(int_array) as Arc<dyn Array>,
2212            Arc::new(float_array),
2213            Arc::new(str_array),
2214        ];
2215
2216        let array = UnionArray::try_new(union_fields(), type_ids, None, children).unwrap();
2217
2218        let expected = BooleanBuffer::from(vec![true, true, true, true, false, false]);
2219
2220        assert_eq!(expected, array.logical_nulls().unwrap().into_inner());
2221        assert_eq!(
2222            expected,
2223            array.mask_sparse_skip_without_nulls(array.fields_logical_nulls())
2224        );
2225
2226        //like above, but repeated to generate two exact bitmasks and a non empty remainder
2227        let len = 2 * 64 + 32;
2228
2229        let int_array = Int32Array::from_value(2, len);
2230        let float_array = Float64Array::from_value(4.2, len);
2231        let str_array = StringArray::from_iter([None, Some("a")].into_iter().cycle().take(len));
2232        let type_ids = ScalarBuffer::from_iter([1, 1, 3, 3, 4, 4].into_iter().cycle().take(len));
2233
2234        let children = vec![
2235            Arc::new(int_array) as Arc<dyn Array>,
2236            Arc::new(float_array),
2237            Arc::new(str_array),
2238        ];
2239
2240        let array = UnionArray::try_new(union_fields(), type_ids, None, children).unwrap();
2241
2242        let expected = BooleanBuffer::from_iter(
2243            [true, true, true, true, false, true]
2244                .into_iter()
2245                .cycle()
2246                .take(len),
2247        );
2248
2249        assert_eq!(array.len(), len);
2250        assert_eq!(expected, array.logical_nulls().unwrap().into_inner());
2251        assert_eq!(
2252            expected,
2253            array.mask_sparse_skip_without_nulls(array.fields_logical_nulls())
2254        );
2255    }
2256
2257    #[test]
2258    fn test_sparse_union_logical_mask_mixed_nulls_skip_fully_null() {
2259        // union of [{A=}, {A=}, {B=4.2}, {B=4.2}, {C=}, {C=}]
2260        let int_array = Int32Array::new_null(6);
2261        let float_array = Float64Array::from_value(4.2, 6);
2262        let str_array = StringArray::new_null(6);
2263        let type_ids = [1, 1, 3, 3, 4, 4].into_iter().collect::<ScalarBuffer<i8>>();
2264
2265        let children = vec![
2266            Arc::new(int_array) as Arc<dyn Array>,
2267            Arc::new(float_array),
2268            Arc::new(str_array),
2269        ];
2270
2271        let array = UnionArray::try_new(union_fields(), type_ids, None, children).unwrap();
2272
2273        let expected = BooleanBuffer::from(vec![false, false, true, true, false, false]);
2274
2275        assert_eq!(expected, array.logical_nulls().unwrap().into_inner());
2276        assert_eq!(
2277            expected,
2278            array.mask_sparse_skip_fully_null(array.fields_logical_nulls())
2279        );
2280
2281        //like above, but repeated to generate two exact bitmasks and a non empty remainder
2282        let len = 2 * 64 + 32;
2283
2284        let int_array = Int32Array::new_null(len);
2285        let float_array = Float64Array::from_value(4.2, len);
2286        let str_array = StringArray::new_null(len);
2287        let type_ids = ScalarBuffer::from_iter([1, 1, 3, 3, 4, 4].into_iter().cycle().take(len));
2288
2289        let children = vec![
2290            Arc::new(int_array) as Arc<dyn Array>,
2291            Arc::new(float_array),
2292            Arc::new(str_array),
2293        ];
2294
2295        let array = UnionArray::try_new(union_fields(), type_ids, None, children).unwrap();
2296
2297        let expected = BooleanBuffer::from_iter(
2298            [false, false, true, true, false, false]
2299                .into_iter()
2300                .cycle()
2301                .take(len),
2302        );
2303
2304        assert_eq!(array.len(), len);
2305        assert_eq!(expected, array.logical_nulls().unwrap().into_inner());
2306        assert_eq!(
2307            expected,
2308            array.mask_sparse_skip_fully_null(array.fields_logical_nulls())
2309        );
2310    }
2311
2312    #[test]
2313    fn test_sparse_union_logical_nulls_gather() {
2314        let n_fields = 50;
2315
2316        let non_null = Int32Array::from_value(2, 4);
2317        let mixed = Int32Array::from(vec![None, None, Some(1), None]);
2318        let fully_null = Int32Array::new_null(4);
2319
2320        let array = UnionArray::try_new(
2321            (1..)
2322                .step_by(2)
2323                .map(|i| {
2324                    (
2325                        i,
2326                        Arc::new(Field::new(format!("f{i}"), DataType::Int32, true)),
2327                    )
2328                })
2329                .take(n_fields)
2330                .collect(),
2331            vec![1, 3, 3, 5].into(),
2332            None,
2333            [
2334                Arc::new(non_null) as ArrayRef,
2335                Arc::new(mixed),
2336                Arc::new(fully_null),
2337            ]
2338            .into_iter()
2339            .cycle()
2340            .take(n_fields)
2341            .collect(),
2342        )
2343        .unwrap();
2344
2345        let expected = BooleanBuffer::from(vec![true, false, true, false]);
2346
2347        assert_eq!(expected, array.logical_nulls().unwrap().into_inner());
2348        assert_eq!(expected, array.gather_nulls(array.fields_logical_nulls()));
2349    }
2350
2351    fn union_fields() -> UnionFields {
2352        [
2353            (1, Arc::new(Field::new("A", DataType::Int32, true))),
2354            (3, Arc::new(Field::new("B", DataType::Float64, true))),
2355            (4, Arc::new(Field::new("C", DataType::Utf8, true))),
2356        ]
2357        .into_iter()
2358        .collect()
2359    }
2360
2361    #[test]
2362    fn test_is_nullable() {
2363        assert!(!create_union_array(false, false).is_nullable());
2364        assert!(create_union_array(true, false).is_nullable());
2365        assert!(create_union_array(false, true).is_nullable());
2366        assert!(create_union_array(true, true).is_nullable());
2367    }
2368
2369    /// Create a union array with a float and integer field
2370    ///
2371    /// If the `int_nullable` is true, the integer field will have nulls
2372    /// If the `float_nullable` is true, the float field will have nulls
2373    ///
2374    /// Note the `Field` definitions are always declared to be nullable
2375    fn create_union_array(int_nullable: bool, float_nullable: bool) -> UnionArray {
2376        let int_array = if int_nullable {
2377            Int32Array::from(vec![Some(1), None, Some(3)])
2378        } else {
2379            Int32Array::from(vec![1, 2, 3])
2380        };
2381        let float_array = if float_nullable {
2382            Float64Array::from(vec![Some(3.2), None, Some(4.2)])
2383        } else {
2384            Float64Array::from(vec![3.2, 4.2, 5.2])
2385        };
2386        let type_ids = [0, 1, 0].into_iter().collect::<ScalarBuffer<i8>>();
2387        let offsets = [0, 0, 0].into_iter().collect::<ScalarBuffer<i32>>();
2388        let union_fields = [
2389            (0, Arc::new(Field::new("A", DataType::Int32, true))),
2390            (1, Arc::new(Field::new("B", DataType::Float64, true))),
2391        ]
2392        .into_iter()
2393        .collect::<UnionFields>();
2394
2395        let children = vec![Arc::new(int_array) as Arc<dyn Array>, Arc::new(float_array)];
2396
2397        UnionArray::try_new(union_fields, type_ids, Some(offsets), children).unwrap()
2398    }
2399}