Skip to main content

parquet_variant_compute/
variant_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//! [`VariantArray`] implementation
6
7use crate::VariantArrayBuilder;
8use crate::type_conversion::{
9    generic_conversion_single_value, generic_conversion_single_value_with_result,
10    primitive_conversion_single_value,
11};
12use arrow::array::{
13    Array, ArrayRef, AsArray, BinaryViewArray, StructArray, StructArrayAssembler,
14    downcast_dictionary_array, downcast_run_array, new_null_array,
15};
16use arrow::buffer::NullBuffer;
17use arrow::compute::cast;
18use arrow::datatypes::{
19    Date32Type, Decimal32Type, Decimal64Type, Decimal128Type, Float16Type, Float32Type,
20    Float64Type, Int8Type, Int16Type, Int32Type, Int64Type, Time64MicrosecondType,
21    TimestampMicrosecondType, TimestampNanosecondType,
22};
23use arrow::error::Result;
24use arrow_schema::extension::{ExtensionType, Uuid as UuidExtension};
25use arrow_schema::{ArrowError, DataType, Field, FieldRef, TimeUnit};
26use chrono::{DateTime, NaiveTime};
27use parquet_variant::{
28    Uuid, Variant, VariantDecimal4, VariantDecimal8, VariantDecimal16, VariantDecimalType as _,
29    VariantType,
30};
31
32use std::borrow::Cow;
33use std::sync::Arc;
34
35/// Returns the logical bytes at the given index from a binary-like array, resolving dictionary
36/// and run-end encodings. Returns `None` for nulls or if the logical values aren't binary-like.
37pub(crate) fn binary_array_value(array: &dyn Array, index: usize) -> Option<&[u8]> {
38    if array.is_null(index) {
39        return None;
40    }
41    match array.data_type() {
42        DataType::Binary => Some(array.as_binary::<i32>().value(index)),
43        DataType::LargeBinary => Some(array.as_binary::<i64>().value(index)),
44        DataType::BinaryView => Some(array.as_binary_view().value(index)),
45        DataType::Dictionary(..) => downcast_dictionary_array! {
46            array => {
47                let index = array.key(index)?;
48                binary_array_value(array.values().as_ref(), index)
49            },
50            _ => unreachable!(),
51        },
52        DataType::RunEndEncoded(..) => downcast_run_array! {
53            array => {
54                let index = array.get_physical_index(index);
55                binary_array_value(array.values().as_ref(), index)
56            },
57            _ => unreachable!(),
58        },
59        _ => None,
60    }
61}
62
63/// A binary-like column whose array type is resolved once, not on every row.
64pub(crate) enum BinaryColumn<'a> {
65    View(&'a BinaryViewArray),
66    Other(&'a dyn Array),
67}
68
69impl<'a> BinaryColumn<'a> {
70    pub(crate) fn new(array: &'a dyn Array) -> Self {
71        match array.as_binary_view_opt() {
72            Some(array) => Self::View(array),
73            None => Self::Other(array),
74        }
75    }
76
77    /// The bytes of row `index`, or `None` if the row is null or the column is not binary-like.
78    pub(crate) fn value(&self, index: usize) -> Option<&'a [u8]> {
79        match self {
80            Self::View(array) => array.is_valid(index).then(|| array.value(index)),
81            Self::Other(array) => binary_array_value(*array, index),
82        }
83    }
84}
85
86/// Returns a [`Variant`] from a `metadata` and `value` byte arrays, returns `None`
87/// if one of them is of invalid type.
88pub(crate) fn variant_from_arrays_at<'m, 'v>(
89    metadata: &'m dyn Array,
90    value: &'v dyn Array,
91    index: usize,
92) -> Option<Variant<'m, 'v>> {
93    let metadata = binary_array_value(metadata, index)?;
94    let value = binary_array_value(value, index)?;
95    Some(Variant::new(metadata, value))
96}
97
98/// Returns an all-null binary `value` column of the given length.
99///
100/// The shredding spec requires the `value` column to always be present in the
101/// schema, so producers that have no unshredded values to store must still
102/// emit an all-null column. See <https://github.com/apache/arrow-rs/issues/10306>.
103pub(crate) fn all_null_value_column(len: usize) -> ArrayRef {
104    new_null_array(&DataType::BinaryView, len)
105}
106
107/// Validates that an array has a binary-like data type.
108pub(crate) fn validate_binary_array(array: &dyn Array, field_name: &str) -> Result<()> {
109    match array.data_type() {
110        DataType::Binary | DataType::LargeBinary | DataType::BinaryView => Ok(()),
111        _ => Err(ArrowError::InvalidArgumentError(format!(
112            "VariantArray '{field_name}' field must be Binary, LargeBinary, or BinaryView, got {}",
113            array.data_type()
114        ))),
115    }
116}
117
118/// An array of Parquet [`Variant`] values
119///
120/// A [`VariantArray`] wraps an Arrow [`StructArray`] that stores the underlying
121/// `metadata` and `value` fields, and adds convenience methods to access
122/// the [`Variant`]s.
123///
124/// See [`VariantArrayBuilder`] for constructing `VariantArray` row by row.
125///
126/// See the examples below from converting between `VariantArray` and
127/// `StructArray`.
128///
129/// # Example: collecting optional values
130///
131/// `VariantArray` can collect optional values that convert into [`Variant`].
132/// `None` creates a null row, while `Some(Variant::Null)` creates a valid row
133/// whose value is `Variant::Null`.
134///
135/// ```
136/// # use parquet_variant::Variant;
137/// # use parquet_variant_compute::VariantArray;
138/// let values = [Some(42_i64), None, Some(-1_i64)];
139/// let array: VariantArray = values.into_iter().collect();
140///
141/// assert_eq!(array.value(0), Variant::Int64(42));
142/// assert!(array.is_null(1));
143/// ```
144///
145/// For an all-null array, specify the type when no `Some` value can infer it:
146///
147/// ```
148/// # use parquet_variant::Variant;
149/// # use parquet_variant_compute::VariantArray;
150/// let null_rows = VariantArray::from_iter(vec![None::<Variant>; 3]);
151/// assert!(null_rows.is_null(0));
152/// ```
153///
154/// [`VariantArrayBuilder`]: crate::VariantArrayBuilder
155///
156/// # Documentation
157///
158/// Variant is documented as a canonical Arrow extension type in the
159/// [Parquet Variant] section of the [official list of extension types] on
160/// the Apache Arrow website.
161///
162/// [Parquet Variant]: https://arrow.apache.org/docs/format/CanonicalExtensions.html#parquet-variant
163/// [official list of extension types]: https://arrow.apache.org/docs/format/CanonicalExtensions.html
164///
165/// # Example: Check if a [`StructArray`] has the [`VariantType`] extension
166///
167/// Arrow Arrays only provide [`DataType`], but the extension type information
168/// is stored on a [`Field`]. Thus, you must have access to the [`Schema`] or
169/// [`Field`] to check for the extension type.
170///
171/// [`Schema`]: arrow_schema::Schema
172/// ```
173/// # use arrow::array::StructArray;
174/// # use arrow_schema::{Schema, Field, DataType};
175/// # use parquet_variant_compute::{VariantArray, VariantType};
176/// # fn get_variant_array() -> VariantArray {
177/// #   VariantArray::from_iter([Some("such wow")])
178/// # }
179/// # fn get_schema() -> Schema {
180/// #   Schema::new(vec![
181/// #     Field::new("id", DataType::Int32, false),
182/// #     get_variant_array().field("var"),
183/// #   ])
184/// # }
185/// let schema = get_schema();
186/// assert_eq!(schema.fields().len(), 2);
187/// // first field is not a Variant
188/// assert!(!schema.field(0).has_valid_extension_type::<VariantType>());
189/// // second field is a Variant
190/// assert!(schema.field(1).has_valid_extension_type::<VariantType>());
191/// ```
192///
193/// # Example: Constructing the correct [`Field`] for a [`VariantArray`]
194///
195/// You can construct the correct [`Field`] for a [`VariantArray`] using the
196/// [`VariantArray::field`] method.
197///
198/// ```
199/// # use arrow_schema::{Schema, Field, DataType};
200/// # use parquet_variant_compute::{VariantArray, VariantType};
201/// # fn get_variant_array() -> VariantArray {
202/// #   VariantArray::from_iter([Some("such wow")])
203/// # }
204/// let variant_array = get_variant_array();
205/// // First field is an integer id, second field is a variant
206/// let schema = Schema::new(vec![
207///   Field::new("id", DataType::Int32, false),
208///   // call VariantArray::field to get the correct Field
209///   variant_array.field("var"),
210/// ]);
211/// ```
212///
213/// You can also construct the [`Field`] using [`VariantType`] directly
214///
215/// ```
216/// # use arrow_schema::{Schema, Field, DataType};
217/// # use parquet_variant_compute::{VariantArray, VariantType};
218/// # fn get_variant_array() -> VariantArray {
219/// #   VariantArray::from_iter([Some("such wow")])
220/// # }
221/// # let variant_array = get_variant_array();
222/// // The DataType of a VariantArray varies depending on how it is shredded
223/// let data_type = variant_array.data_type().clone();
224/// // First field is an integer id, second field is a variant
225/// let schema = Schema::new(vec![
226///   Field::new("id", DataType::Int32, false),
227///   Field::new("var", data_type, false)
228///     // Add extension metadata to the field using `VariantType`
229///     .with_extension_type(VariantType),
230/// ]);
231/// ```
232///
233/// # Example: Converting a [`VariantArray`] to a [`StructArray`]
234///
235/// ```
236/// # use arrow::array::StructArray;
237/// # use parquet_variant_compute::VariantArray;
238/// // Create Variant Array
239/// let variant_array = VariantArray::from_iter([Some("such wow")]);
240/// // convert to StructArray
241/// let struct_array: StructArray = variant_array.into();
242/// ```
243///
244/// # Example: Converting a [`StructArray`] to a [`VariantArray`]
245///
246/// ```
247/// # use arrow::array::StructArray;
248/// # use parquet_variant::Variant;
249/// # use parquet_variant_compute::VariantArray;
250/// # fn get_struct_array() -> StructArray {
251/// #   VariantArray::from_iter([Some("such wow")]).into()
252/// # }
253/// let struct_array: StructArray = get_struct_array();
254/// // try and create a VariantArray from it
255/// let variant_array = VariantArray::try_new(&struct_array).unwrap();
256/// assert_eq!(variant_array.value(0), Variant::from("such wow"));
257/// ```
258///
259#[derive(Debug, Clone)]
260pub struct VariantArray {
261    /// Reference to the underlying StructArray
262    inner: StructArray,
263
264    /// The metadata column of this variant (Binary, LargeBinary, or BinaryView), possibly encoded
265    metadata: ArrayRef,
266
267    /// how is this variant array shredded?
268    shredding_state: ShreddingState,
269}
270
271impl VariantArray {
272    /// Creates a new `VariantArray` from a [`StructArray`].
273    ///
274    /// # Arguments
275    /// - `inner` - The underlying [`StructArray`] that contains the variant data.
276    ///
277    /// # Returns
278    /// - A new instance of `VariantArray`.
279    ///
280    /// # Errors:
281    /// - If the data type is not valid [`VariantType`] storage
282    /// - If `typed_value` contains a type that cannot be shredded
283    ///
284    /// # Requirements of the `StructArray`
285    ///
286    /// See [`VariantType`] for the required fields. `typed_value` can be any
287    /// primitive type or be a list, large_list, fixed_size_list, list_view or
288    /// struct. Fixed-size lists are normalized to variable-length lists on read.
289    ///
290    pub fn try_new(inner: &dyn Array) -> Result<Self> {
291        // Before canonicalizing, which would report a non-Variant struct's fields as illegal
292        // shredded types
293        VariantType.supports_data_type(inner.data_type())?;
294
295        // Canonicalize shredded typed_value fields (e.g. decimal narrowing)
296        let inner = canonicalize_shredded_types(inner)?;
297        let inner = inner.as_struct();
298        let metadata_col = inner
299            .column_by_name("metadata")
300            .expect("checked by VariantType");
301
302        let shredding_state = ShreddingState::try_from(inner)?;
303
304        // `try_from` synthesizes an all-null `value` when the input omits it. Rebuild the inner
305        // struct so `inner()` and write-back carry the column too.
306        if inner.column_by_name("value").is_none() {
307            return Ok(Self::from_parts(
308                metadata_col.clone(),
309                shredding_state.value_column().clone(),
310                shredding_state.typed_value_column().cloned(),
311                inner.nulls().cloned(),
312            ));
313        }
314
315        // Note these clones are cheap, they just bump the ref count
316        Ok(Self {
317            inner: inner.clone(),
318            metadata: metadata_col.clone(),
319            shredding_state,
320        })
321    }
322
323    /// Note: annotates `value` as nullable, which the spec only permits for shredded
324    /// variants. It is also needed by `variant_get`'s unshredded intermediates, whose
325    /// `value` column can contain unmasked nulls. Unshredded producers should use
326    /// [`Self::from_parts_unshredded`] instead.
327    pub(crate) fn from_parts(
328        metadata: ArrayRef,
329        value: ArrayRef,
330        typed_value: Option<ArrayRef>,
331        nulls: Option<NullBuffer>,
332    ) -> Self {
333        Self::from_parts_with_nullable_value(metadata, value, typed_value, nulls, true)
334    }
335
336    /// Construct an unshredded `VariantArray`, annotating `value` as non-nullable as the
337    /// spec requires when there is no `typed_value` column.
338    ///
339    /// # Panics
340    /// If `value` contains nulls not masked by `nulls`.
341    pub(crate) fn from_parts_unshredded(
342        metadata: ArrayRef,
343        value: ArrayRef,
344        nulls: Option<NullBuffer>,
345    ) -> Self {
346        Self::from_parts_with_nullable_value(metadata, value, None, nulls, false)
347    }
348
349    fn from_parts_with_nullable_value(
350        metadata: ArrayRef,
351        value: ArrayRef,
352        typed_value: Option<ArrayRef>,
353        nulls: Option<NullBuffer>,
354        value_nullable: bool,
355    ) -> Self {
356        let mut builder = StructArrayAssembler::new()
357            .with_field("metadata", metadata.clone(), false)
358            .with_field("value", value.clone(), value_nullable);
359        if let Some(typed_value) = typed_value.clone() {
360            builder = builder.with_field_ref(typed_value_field(&typed_value), typed_value);
361        }
362        if let Some(nulls) = nulls {
363            builder = builder.with_nulls(nulls);
364        }
365
366        Self {
367            inner: builder.build().unwrap(),
368            metadata,
369            shredding_state: ShreddingState::new(value, typed_value),
370        }
371    }
372
373    /// Returns a reference to the underlying [`StructArray`].
374    pub fn inner(&self) -> &StructArray {
375        &self.inner
376    }
377
378    /// Returns the inner [`StructArray`], consuming self
379    pub fn into_inner(self) -> StructArray {
380        self.inner
381    }
382
383    /// Return the shredding state of this `VariantArray`
384    pub fn shredding_state(&self) -> &ShreddingState {
385        &self.shredding_state
386    }
387
388    /// Return the [`Variant`] instance stored at the given row
389    ///
390    /// This is a convenience wrapper that calls [`VariantArray::try_value`] and unwraps the `Result`.
391    /// Use `try_value` if you need to handle conversion errors gracefully.
392    ///
393    /// # Panics
394    /// Panics if
395    /// * the index is out of bounds,
396    /// * the `metadata`/`value` bytes of the row are invalid, which includes reading a null row, or
397    /// * both `value` and `typed_value` are non-null for a non-struct `typed_value`.
398    pub fn value(&self, index: usize) -> Variant<'_, '_> {
399        self.try_value(index)
400            .unwrap_or_else(|err| panic!("VariantArray::value({index}) failed: {err}"))
401    }
402
403    /// Return the [`Variant`] instance stored at the given row
404    ///
405    /// Note: This method does not check for nulls and the value is arbitrary
406    /// (but still well-defined) if [`is_null`](Self::is_null) returns true for the index.
407    ///
408    /// # Errors
409    ///
410    /// Errors if
411    /// - the index is out of bounds
412    /// - the data in `typed_value` cannot be interpreted as a valid `Variant`
413    /// - both `value` and `typed_value` are non-null for a non-struct `typed_value`
414    ///
415    /// # Panics
416    ///
417    /// Panics if the unshredded `metadata`/`value` bytes fail basic validation, since those are
418    /// read with [`Variant::new`]. This includes reading a row that is null.
419    ///
420    /// If this is a shredded variant but has no value at the shredded location, it
421    /// will return [`Variant::Null`].
422    ///
423    ///
424    /// # Performance Note
425    ///
426    /// This is certainly not the most efficient way to access values in a
427    /// `VariantArray`, but it is useful for testing and debugging.
428    ///
429    /// Note: Does not do deep validation of the [`Variant`], so it is up to the
430    /// caller to ensure that the metadata and value were constructed correctly.
431    pub fn try_value(&self, index: usize) -> Result<Variant<'_, '_>> {
432        if self.len() <= index {
433            return Err(ArrowError::InvalidArgumentError(format!(
434                "Index {index} out of bounds for VariantArray of length {}",
435                self.len()
436            )));
437        }
438
439        let value = self.value_column();
440        match self.typed_value_column() {
441            // Always prefer typed_value, if available
442            Some(typed_value) if typed_value.is_valid(index) => {
443                if !matches!(typed_value.data_type(), DataType::Struct(_)) && value.is_valid(index) {
444                    // Only a partially shredded struct is allowed to have values for both columns
445                    return Err(ArrowError::InvalidArgumentError(
446                        "Invalid variant, conflicting value and typed_value".to_owned(),
447                    ));
448                }
449                typed_value_to_variant(typed_value, index)
450            }
451            // Otherwise fall back to value, if available
452            _ if value.is_valid(index) => variant_from_arrays_at(&self.metadata, value, index)
453                .ok_or_else(|| {
454                    ArrowError::InvalidArgumentError(format!(
455                        "metadata and value fields must be binary-like arrays, instead got {} and {}",
456                        self.metadata.data_type(),
457                        value.data_type()
458                    ))
459                }),
460            // It is technically invalid for both value and typed_value to be null,
461            // but the spec specifically requires readers to return Variant::Null in this case.
462            _ => Ok(Variant::Null),
463        }
464    }
465
466    /// Return a reference to the `metadata` column of the [`StructArray`]
467    pub fn metadata_column(&self) -> &ArrayRef {
468        &self.metadata
469    }
470
471    /// Return a reference to the `value` column of the [`StructArray`]
472    pub fn value_column(&self) -> &ArrayRef {
473        self.shredding_state.value_column()
474    }
475
476    /// Return a reference to the `typed_value` column of the [`StructArray`], if present
477    pub fn typed_value_column(&self) -> Option<&ArrayRef> {
478        self.shredding_state.typed_value_column()
479    }
480
481    /// Return a field to represent this VariantArray in a `Schema` with
482    /// a particular name
483    pub fn field(&self, name: impl Into<String>) -> Field {
484        Field::new(
485            name.into(),
486            self.data_type().clone(),
487            self.inner.is_nullable(),
488        )
489        .with_extension_type(VariantType)
490    }
491
492    /// Returns a new DataType representing this VariantArray's inner type
493    pub fn data_type(&self) -> &DataType {
494        self.inner.data_type()
495    }
496
497    pub fn slice(&self, offset: usize, length: usize) -> Self {
498        let inner = self.inner.slice(offset, length);
499        let metadata = self.metadata.slice(offset, length);
500        let shredding_state = self.shredding_state.slice(offset, length);
501        Self {
502            inner,
503            metadata,
504            shredding_state,
505        }
506    }
507
508    pub fn len(&self) -> usize {
509        self.inner.len()
510    }
511
512    pub fn is_empty(&self) -> bool {
513        self.inner.is_empty()
514    }
515
516    pub fn nulls(&self) -> Option<&NullBuffer> {
517        self.inner.nulls()
518    }
519
520    /// Is the element at index null?
521    pub fn is_null(&self, index: usize) -> bool {
522        self.nulls().is_some_and(|n| n.is_null(index))
523    }
524
525    /// Is the element at index valid (not null)?
526    pub fn is_valid(&self, index: usize) -> bool {
527        !self.is_null(index)
528    }
529
530    /// Returns an iterator over the values in this array
531    pub fn iter(&self) -> VariantArrayIter<'_> {
532        VariantArrayIter::new(self)
533    }
534}
535
536impl<'a> IntoIterator for &'a VariantArray {
537    type Item = Option<Variant<'a, 'a>>;
538    type IntoIter = VariantArrayIter<'a>;
539
540    fn into_iter(self) -> Self::IntoIter {
541        VariantArrayIter::new(self)
542    }
543}
544
545impl PartialEq for VariantArray {
546    fn eq(&self, other: &Self) -> bool {
547        self.inner == other.inner
548    }
549}
550
551impl From<VariantArray> for StructArray {
552    fn from(variant_array: VariantArray) -> Self {
553        variant_array.into_inner()
554    }
555}
556
557impl From<VariantArray> for ArrayRef {
558    fn from(variant_array: VariantArray) -> Self {
559        Arc::new(variant_array.into_inner())
560    }
561}
562
563impl<'m, 'v, V: Into<Variant<'m, 'v>>> FromIterator<Option<V>> for VariantArray {
564    fn from_iter<T: IntoIterator<Item = Option<V>>>(iter: T) -> Self {
565        let iter = iter.into_iter().map(|value| value.map(Into::into));
566
567        let mut b = VariantArrayBuilder::new(iter.size_hint().0);
568        b.extend(iter);
569        b.build()
570    }
571}
572
573impl<'m, 'v> FromIterator<Variant<'m, 'v>> for VariantArray {
574    fn from_iter<T: IntoIterator<Item = Variant<'m, 'v>>>(iter: T) -> Self {
575        Self::from_iter(iter.into_iter().map(Some))
576    }
577}
578
579/// An iterator over [`VariantArray`]
580///
581/// This iterator returns `Option<Option<Variant<'a, 'a>>>` where:
582/// - `None` indicates the end of iteration
583/// - `Some(None)` indicates a null value at this position
584/// - `Some(Some(variant))` indicates a valid variant value
585///
586/// # Example
587///
588/// ```
589/// # use parquet_variant::Variant;
590/// # use parquet_variant_compute::VariantArrayBuilder;
591/// let mut builder = VariantArrayBuilder::new(10);
592/// builder.append_variant(Variant::from(42));
593/// builder.append_null();
594/// builder.append_variant(Variant::from("hello"));
595/// let array = builder.build();
596///
597/// let values = array.iter().collect::<Vec<_>>();
598/// assert_eq!(values.len(), 3);
599/// assert_eq!(values[0], Some(Variant::from(42)));
600/// assert_eq!(values[1], None);
601/// assert_eq!(values[2], Some(Variant::from("hello")));
602/// ```
603#[derive(Debug)]
604pub struct VariantArrayIter<'a> {
605    array: &'a VariantArray,
606    head_i: usize,
607    tail_i: usize,
608}
609
610impl<'a> VariantArrayIter<'a> {
611    /// Creates a new iterator over the given [`VariantArray`]
612    pub fn new(array: &'a VariantArray) -> Self {
613        Self {
614            array,
615            head_i: 0,
616            tail_i: array.len(),
617        }
618    }
619
620    fn value_opt(&self, i: usize) -> Option<Variant<'a, 'a>> {
621        self.array.is_valid(i).then(|| self.array.value(i))
622    }
623}
624
625impl<'a> Iterator for VariantArrayIter<'a> {
626    type Item = Option<Variant<'a, 'a>>;
627
628    #[inline]
629    fn next(&mut self) -> Option<Self::Item> {
630        if self.head_i == self.tail_i {
631            return None;
632        }
633
634        let out = self.value_opt(self.head_i);
635
636        self.head_i += 1;
637
638        Some(out)
639    }
640
641    fn size_hint(&self) -> (usize, Option<usize>) {
642        let remainder = self.tail_i - self.head_i;
643
644        (remainder, Some(remainder))
645    }
646}
647
648impl DoubleEndedIterator for VariantArrayIter<'_> {
649    fn next_back(&mut self) -> Option<Self::Item> {
650        if self.head_i == self.tail_i {
651            return None;
652        }
653
654        self.tail_i -= 1;
655
656        Some(self.value_opt(self.tail_i))
657    }
658}
659
660impl ExactSizeIterator for VariantArrayIter<'_> {}
661
662/// One shredded field of a partially or perfectly shredded variant. For example, suppose the
663/// shredding schema for variant `v` treats it as an object with a single field `a`, where `a` is
664/// itself a struct with the single field `b` of type INT. Then the physical layout of the column
665/// is:
666///
667/// ```text
668/// v: VARIANT {
669///     metadata: BINARY,
670///     value: BINARY,
671///     typed_value: STRUCT {
672///         a: SHREDDED_VARIANT_FIELD {
673///             value: BINARY,
674///             typed_value: STRUCT {
675///                 a: SHREDDED_VARIANT_FIELD {
676///                     value: BINARY,
677///                     typed_value: INT,
678///                 },
679///             },
680///         },
681///     },
682/// }
683/// ```
684///
685/// In the above, each row of `v.value` is either a variant value (shredding failed, `v` was not an
686/// object at all) or a variant object (partial shredding, `v` was an object but included unexpected
687/// fields other than `a`), or is NULL (perfect shredding, `v` was an object containing only the
688/// single expected field `a`).
689///
690/// A similar story unfolds for each `v.typed_value.a.value` -- a variant value if shredding failed
691/// (`v:a` was not an object at all), or a variant object (`v:a` was an object with unexpected
692/// additional fields), or NULL (`v:a` was an object containing only the single expected field `b`).
693///
694/// Finally, `v.typed_value.a.typed_value.b.value` is either NULL (`v:a.b` was an integer) or else a
695/// variant value (which could be `Variant::Null`).
696#[derive(Debug)]
697pub struct ShreddedVariantFieldArray {
698    /// Reference to the underlying StructArray
699    inner: StructArray,
700    shredding_state: ShreddingState,
701}
702
703impl ShreddedVariantFieldArray {
704    /// Creates a new `ShreddedVariantFieldArray` from a [`StructArray`].
705    ///
706    /// # Arguments
707    /// - `inner` - The underlying [`StructArray`] that contains the variant data.
708    ///
709    /// # Returns
710    /// - A new instance of `ShreddedVariantFieldArray`.
711    ///
712    /// # Errors:
713    /// - If the `StructArray` does not contain the required fields
714    ///
715    /// # Requirements of the `StructArray`
716    ///
717    /// 1. A required field named `value` that is binary, large_binary, or
718    ///    binary_view
719    ///
720    /// 2. An optional field named `typed_value` which can be any primitive type
721    ///    or be a list, large_list, list_view or struct
722    ///
723    pub fn try_new(inner: &dyn Array) -> Result<Self> {
724        let Some(inner_struct) = inner.as_struct_opt() else {
725            return Err(ArrowError::InvalidArgumentError(
726                "Invalid ShreddedVariantFieldArray: requires StructArray as input".to_string(),
727            ));
728        };
729
730        let shredding_state = ShreddingState::try_from(inner_struct)?;
731
732        // `try_from` synthesizes an all-null `value` when the input omits it. Rebuild the inner
733        // struct so `inner()` and write-back carry the column too (see `VariantArray::try_new`).
734        if inner_struct.column_by_name("value").is_none() {
735            return Ok(Self::from_parts(
736                shredding_state.value_column().clone(),
737                shredding_state.typed_value_column().cloned(),
738                inner_struct.nulls().cloned(),
739            ));
740        }
741
742        // Note this clone is cheap, it just bumps the ref count
743        Ok(Self {
744            inner: inner_struct.clone(),
745            shredding_state,
746        })
747    }
748
749    /// Return the shredding state of this `VariantArray`
750    pub fn shredding_state(&self) -> &ShreddingState {
751        &self.shredding_state
752    }
753
754    /// Return a reference to the `value` column of the [`StructArray`]
755    pub fn value_column(&self) -> &ArrayRef {
756        self.shredding_state.value_column()
757    }
758
759    /// Return a reference to the `typed_value` column of the [`StructArray`], if present
760    pub fn typed_value_column(&self) -> Option<&ArrayRef> {
761        self.shredding_state.typed_value_column()
762    }
763
764    /// Returns a reference to the underlying [`StructArray`].
765    pub fn inner(&self) -> &StructArray {
766        &self.inner
767    }
768
769    pub(crate) fn from_parts(
770        value: ArrayRef,
771        typed_value: Option<ArrayRef>,
772        nulls: Option<NullBuffer>,
773    ) -> Self {
774        let mut builder = StructArrayAssembler::new().with_field("value", value.clone(), true);
775        if let Some(typed_value) = typed_value.clone() {
776            builder = builder.with_field_ref(typed_value_field(&typed_value), typed_value);
777        }
778        if let Some(nulls) = nulls {
779            builder = builder.with_nulls(nulls);
780        }
781
782        Self {
783            inner: builder.build().unwrap(),
784            shredding_state: ShreddingState::new(value, typed_value),
785        }
786    }
787
788    /// Returns the inner [`StructArray`], consuming self
789    pub fn into_inner(self) -> StructArray {
790        self.inner
791    }
792
793    pub fn data_type(&self) -> &DataType {
794        self.inner.data_type()
795    }
796
797    pub fn len(&self) -> usize {
798        self.inner.len()
799    }
800
801    pub fn is_empty(&self) -> bool {
802        self.inner.is_empty()
803    }
804
805    pub fn offset(&self) -> usize {
806        self.inner.offset()
807    }
808
809    pub fn nulls(&self) -> Option<&NullBuffer> {
810        // According to the shredding spec, ShreddedVariantFieldArray should be
811        // physically non-nullable - SQL NULL is inferred by both value and
812        // typed_value being physically NULL
813        None
814    }
815    /// Is the element at index null?
816    pub fn is_null(&self, index: usize) -> bool {
817        self.nulls().is_some_and(|n| n.is_null(index))
818    }
819
820    /// Is the element at index valid (not null)?
821    pub fn is_valid(&self, index: usize) -> bool {
822        !self.is_null(index)
823    }
824}
825
826impl From<ShreddedVariantFieldArray> for ArrayRef {
827    fn from(array: ShreddedVariantFieldArray) -> Self {
828        Arc::new(array.into_inner())
829    }
830}
831
832impl From<ShreddedVariantFieldArray> for StructArray {
833    fn from(array: ShreddedVariantFieldArray) -> Self {
834        array.into_inner()
835    }
836}
837
838/// Represents the shredding state of a [`VariantArray`]
839///
840/// [`VariantArray`]s can be shredded according to the [Parquet Variant
841/// Shredding Spec]. Shredding means that the actual value is stored in a typed
842/// `typed_field` instead of the generic `value` field.
843///
844/// The `value` column is always present (the spec requires writers to emit
845/// it); `typed_value` is optional. Values in the two columns must be
846/// interpreted according to the following table (see [Parquet Variant
847/// Shredding Spec] for more details):
848///
849/// | value    | typed_value  | Meaning |
850/// |----------|--------------|---------|
851/// | NULL     | NULL         | The value is missing; only valid for shredded object fields |
852/// | non-NULL | NULL         | The value is present and may be any type, including [`Variant::Null`] |
853/// | NULL     | non-NULL     | The value is present and is the shredded type |
854/// | non-NULL | non-NULL     | The value is present and is a partially shredded object |
855///
856///
857/// Applying the above rules to entire columns, we obtain the following:
858///
859/// | value  | typed_value  | Meaning |
860/// |--------|-------------|---------|
861/// | exists | --          | **Unshredded**: If present, the value may be any type, including [`Variant::Null`]
862/// | exists | exists      | **Shredded**: perfectly if `value` is all-null, otherwise imperfectly |
863///
864/// Note the spec requires the `value` column to always be present in the
865/// schema; structs without one are rejected
866/// (see <https://github.com/apache/arrow-rs/issues/10306>).
867///
868/// NOTE: Partial shredding is a row-wise situation that can arise under imperfect shredding (a
869/// column-wise situation): When both columns exist (imperfect shredding) and the typed_value column
870/// is a struct, then both columns can be non-NULL for the same row if value is a variant object
871/// (partial shredding).
872///
873/// [Parquet Variant Shredding Spec]: https://github.com/apache/parquet-format/blob/master/VariantShredding.md#value-shredding
874#[derive(Debug, Clone)]
875pub struct ShreddingState {
876    value: ArrayRef,
877    typed_value: Option<ArrayRef>,
878}
879
880impl ShreddingState {
881    /// Create a new `ShreddingState` from the given `value` and `typed_value` fields
882    ///
883    /// Note you can create a `ShreddingState` from a &[`StructArray`] using
884    /// `ShreddingState::try_from(&struct_array)`, for example:
885    ///
886    /// ```no_run
887    /// # use arrow::array::StructArray;
888    /// # use parquet_variant_compute::ShreddingState;
889    /// # fn get_struct_array() -> StructArray {
890    /// #   unimplemented!()
891    /// # }
892    /// let struct_array: StructArray = get_struct_array();
893    /// let shredding_state = ShreddingState::try_from(&struct_array).unwrap();
894    /// ```
895    pub fn new(value: ArrayRef, typed_value: Option<ArrayRef>) -> Self {
896        Self { value, typed_value }
897    }
898
899    /// Return a reference to the `value` column
900    pub fn value_column(&self) -> &ArrayRef {
901        &self.value
902    }
903
904    /// Return a reference to the `typed_value` column, if present
905    pub fn typed_value_column(&self) -> Option<&ArrayRef> {
906        self.typed_value.as_ref()
907    }
908
909    /// Slice all the underlying arrays
910    pub fn slice(&self, offset: usize, length: usize) -> Self {
911        Self {
912            value: self.value.slice(offset, length),
913            typed_value: self.typed_value.as_ref().map(|tv| tv.slice(offset, length)),
914        }
915    }
916}
917
918impl TryFrom<&StructArray> for ShreddingState {
919    type Error = ArrowError;
920
921    fn try_from(inner_struct: &StructArray) -> Result<Self> {
922        let typed_value = inner_struct.column_by_name("typed_value").cloned();
923        let value = match inner_struct.column_by_name("value") {
924            Some(value) => {
925                validate_binary_array(value.as_ref(), "value")?;
926                value.clone()
927            }
928            // Lenient read: a shredded group may omit the spec-required `value`. Synthesize an
929            // all-null one so the model always has a `value`.
930            None if typed_value.is_some() => all_null_value_column(inner_struct.len()),
931            None => {
932                return Err(ArrowError::InvalidArgumentError(
933                    "Invalid VariantArray: StructArray must contain a 'value' field".to_string(),
934                ));
935            }
936        };
937        Ok(ShreddingState::new(value, typed_value))
938    }
939}
940
941/// Build the `typed_value` [`FieldRef`] for a shredded column.
942///
943/// The Variant spec maps `FixedSizeBinary(16)` exclusively to UUID, so any
944/// shredded column of that type must carry the canonical [`UuidExtension`]
945/// extension metadata on its field.
946fn typed_value_field(array: &ArrayRef) -> FieldRef {
947    let mut field = Field::new("typed_value", array.data_type().clone(), true);
948    if matches!(array.data_type(), DataType::FixedSizeBinary(16)) {
949        field = field.with_extension_type(UuidExtension);
950    }
951    Arc::new(field)
952}
953
954/// returns the non-null element at index as a Variant
955fn typed_value_to_variant(typed_value: &ArrayRef, index: usize) -> Result<Variant<'_, '_>> {
956    let data_type = typed_value.data_type();
957    match data_type {
958        DataType::Null => Ok(Variant::Null),
959        DataType::Boolean => {
960            let boolean_array = typed_value.as_boolean();
961            let value = boolean_array.value(index);
962            Ok(Variant::from(value))
963        }
964        // 16-byte FixedSizeBinary always corresponds to a UUID; all other sizes are illegal.
965        DataType::FixedSizeBinary(16) => {
966            let array = typed_value.as_fixed_size_binary();
967            let value = array.value(index);
968            Ok(Uuid::from_slice(value).unwrap().into()) // unwrap is safe: slice is always 16 bytes
969        }
970        DataType::Binary => {
971            let array = typed_value.as_binary::<i32>();
972            let value = array.value(index);
973            Ok(Variant::from(value))
974        }
975        DataType::LargeBinary => {
976            let array = typed_value.as_binary::<i64>();
977            let value = array.value(index);
978            Ok(Variant::from(value))
979        }
980        DataType::BinaryView => {
981            let array = typed_value.as_binary_view();
982            let value = array.value(index);
983            Ok(Variant::from(value))
984        }
985        DataType::Utf8 => {
986            let array = typed_value.as_string::<i32>();
987            let value = array.value(index);
988            Ok(Variant::from(value))
989        }
990        DataType::LargeUtf8 => {
991            let array = typed_value.as_string::<i64>();
992            let value = array.value(index);
993            Ok(Variant::from(value))
994        }
995        DataType::Utf8View => {
996            let array = typed_value.as_string_view();
997            let value = array.value(index);
998            Ok(Variant::from(value))
999        }
1000        DataType::Int8 => {
1001            primitive_conversion_single_value!(Int8Type, typed_value, index)
1002        }
1003        DataType::Int16 => {
1004            primitive_conversion_single_value!(Int16Type, typed_value, index)
1005        }
1006        DataType::Int32 => {
1007            primitive_conversion_single_value!(Int32Type, typed_value, index)
1008        }
1009        DataType::Int64 => {
1010            primitive_conversion_single_value!(Int64Type, typed_value, index)
1011        }
1012        DataType::Float16 => {
1013            primitive_conversion_single_value!(Float16Type, typed_value, index)
1014        }
1015        DataType::Float32 => {
1016            primitive_conversion_single_value!(Float32Type, typed_value, index)
1017        }
1018        DataType::Float64 => {
1019            primitive_conversion_single_value!(Float64Type, typed_value, index)
1020        }
1021        DataType::Decimal32(_, s) => {
1022            generic_conversion_single_value_with_result!(
1023                Decimal32Type,
1024                as_primitive,
1025                |v| VariantDecimal4::try_new(v, *s as u8),
1026                typed_value,
1027                index
1028            )
1029        }
1030        DataType::Decimal64(_, s) => {
1031            generic_conversion_single_value_with_result!(
1032                Decimal64Type,
1033                as_primitive,
1034                |v| VariantDecimal8::try_new(v, *s as u8),
1035                typed_value,
1036                index
1037            )
1038        }
1039        DataType::Decimal128(_, s) => {
1040            generic_conversion_single_value_with_result!(
1041                Decimal128Type,
1042                as_primitive,
1043                |v| VariantDecimal16::try_new(v, *s as u8),
1044                typed_value,
1045                index
1046            )
1047        }
1048        DataType::Date32 => {
1049            generic_conversion_single_value!(
1050                Date32Type,
1051                as_primitive,
1052                |v| Date32Type::to_naive_date_opt(v).unwrap(),
1053                typed_value,
1054                index
1055            )
1056        }
1057        DataType::Time64(TimeUnit::Microsecond) => {
1058            generic_conversion_single_value_with_result!(
1059                Time64MicrosecondType,
1060                as_primitive,
1061                |v| NaiveTime::from_num_seconds_from_midnight_opt(
1062                    (v / 1_000_000) as u32,
1063                    (v % 1_000_000) as u32 * 1000
1064                )
1065                .ok_or_else(|| format!("Invalid microsecond from midnight: {v}")),
1066                typed_value,
1067                index
1068            )
1069        }
1070        DataType::Timestamp(TimeUnit::Microsecond, Some(_)) => {
1071            generic_conversion_single_value!(
1072                TimestampMicrosecondType,
1073                as_primitive,
1074                |v| DateTime::from_timestamp_micros(v).unwrap(),
1075                typed_value,
1076                index
1077            )
1078        }
1079        DataType::Timestamp(TimeUnit::Microsecond, None) => {
1080            generic_conversion_single_value!(
1081                TimestampMicrosecondType,
1082                as_primitive,
1083                |v| DateTime::from_timestamp_micros(v).unwrap().naive_utc(),
1084                typed_value,
1085                index
1086            )
1087        }
1088        DataType::Timestamp(TimeUnit::Nanosecond, Some(_)) => {
1089            generic_conversion_single_value!(
1090                TimestampNanosecondType,
1091                as_primitive,
1092                DateTime::from_timestamp_nanos,
1093                typed_value,
1094                index
1095            )
1096        }
1097        DataType::Timestamp(TimeUnit::Nanosecond, None) => {
1098            generic_conversion_single_value!(
1099                TimestampNanosecondType,
1100                as_primitive,
1101                |v| DateTime::from_timestamp_nanos(v).naive_utc(),
1102                typed_value,
1103                index
1104            )
1105        }
1106        // todo other types here (note this is very similar to cast_to_variant.rs)
1107        // so it would be great to figure out how to share this code
1108        //
1109        // Composite shredded values may require combining `value` and
1110        // `typed_value` and allocating new encoded bytes. `try_value` returns
1111        // borrowed Variant, so callers must unshred the array first.
1112        _ => Err(ArrowError::NotYetImplemented(format!(
1113            "VariantArray::try_value cannot materialize typed_value of type {} \
1114             as a borrowed Variant; call unshred_variant first",
1115            typed_value.data_type()
1116        ))),
1117    }
1118}
1119
1120/// Canonicalize shredded typed_value fields (e.g. decimal narrowing) and
1121/// verify that all data types in the struct are legal for a variant array.
1122fn canonicalize_shredded_types(array: &dyn Array) -> Result<ArrayRef> {
1123    let new_type = canonicalize_and_verify_data_type_impl(array.data_type(), true)?;
1124    if let Cow::Borrowed(_) = new_type
1125        && let Some(array) = array.as_struct_opt()
1126    {
1127        return Ok(Arc::new(array.clone())); // bypass the unnecessary cast
1128    }
1129    cast(array, new_type.as_ref())
1130}
1131
1132/// Recursively visits a data type, ensuring that it only contains data types that can legally
1133/// appear in a (possibly shredded) variant array. It also narrows decimal types to the smallest
1134/// valid precision (e.g. Decimal128 -> Decimal32 when the precision fits).
1135fn canonicalize_and_verify_data_type(data_type: &DataType) -> Result<Cow<'_, DataType>> {
1136    canonicalize_and_verify_data_type_impl(data_type, false)
1137}
1138
1139fn canonicalize_and_verify_data_type_impl(
1140    data_type: &DataType,
1141    skip_top_level_metadata: bool,
1142) -> Result<Cow<'_, DataType>> {
1143    use DataType::*;
1144
1145    // helper macros
1146    macro_rules! fail {
1147        () => {
1148            return Err(ArrowError::InvalidArgumentError(format!(
1149                "Illegal shredded value type: {data_type}"
1150            )))
1151        };
1152    }
1153    macro_rules! borrow {
1154        () => {
1155            Cow::Borrowed(data_type)
1156        };
1157    }
1158
1159    let new_data_type = match data_type {
1160        // Primitive arrow types that have a direct variant counterpart are allowed
1161        Null | Boolean => borrow!(),
1162        Int8 | Int16 | Int32 | Int64 | Float32 | Float64 => borrow!(),
1163
1164        // Unsigned integers and half-float are not allowed
1165        UInt8 | UInt16 | UInt32 | UInt64 | Float16 => fail!(),
1166
1167        // Most decimal types are allowed, with restrictions on precision and scale
1168        //
1169        // NOTE: arrow-parquet reads widens 32- and 64-bit decimals to 128-bit, but the variant spec
1170        // requires using the narrowest decimal type for a given precision. Fix those up first.
1171        Decimal64(p, s) | Decimal128(p, s)
1172            if VariantDecimal4::is_valid_precision_and_scale(p, s) =>
1173        {
1174            Cow::Owned(Decimal32(*p, *s))
1175        }
1176        Decimal128(p, s) if VariantDecimal8::is_valid_precision_and_scale(p, s) => {
1177            Cow::Owned(Decimal64(*p, *s))
1178        }
1179        Decimal32(p, s) if VariantDecimal4::is_valid_precision_and_scale(p, s) => borrow!(),
1180        Decimal64(p, s) if VariantDecimal8::is_valid_precision_and_scale(p, s) => borrow!(),
1181        Decimal128(p, s) if VariantDecimal16::is_valid_precision_and_scale(p, s) => borrow!(),
1182        Decimal32(..) | Decimal64(..) | Decimal128(..) | Decimal256(..) => fail!(),
1183
1184        // Only micro and nano timestamps are allowed
1185        Timestamp(TimeUnit::Microsecond | TimeUnit::Nanosecond, _) => borrow!(),
1186        Timestamp(TimeUnit::Millisecond | TimeUnit::Second, _) => fail!(),
1187
1188        // Only 32-bit dates and 64-bit microsecond time are allowed.
1189        Date32 | Time64(TimeUnit::Microsecond) => borrow!(),
1190        Date64 | Time32(_) | Time64(_) | Duration(_) | Interval(_) => fail!(),
1191
1192        // Binary, string, and their view counterparts are allowed.
1193        Binary | LargeBinary | BinaryView | Utf8 | LargeUtf8 | Utf8View => borrow!(),
1194
1195        // UUID maps to 16-byte fixed-size binary; no other width is allowed
1196        FixedSizeBinary(16) => borrow!(),
1197        FixedSizeBinary(_) => fail!(),
1198
1199        // FixedSizeList is an Arrow-specific distinction. Normalize it to List on read so
1200        // Variant data written by older arrow-rs versions remains readable without treating
1201        // FixedSizeList as a supported shredding target.
1202        FixedSizeList(field, _) => match canonicalize_and_verify_field(field)? {
1203            Cow::Borrowed(_) => Cow::Owned(DataType::List(field.clone())),
1204            Cow::Owned(new_field) => Cow::Owned(DataType::List(new_field)),
1205        },
1206
1207        // List-like containers and struct are allowed, maps and unions are not
1208        List(field) => match canonicalize_and_verify_field(field)? {
1209            Cow::Borrowed(_) => borrow!(),
1210            Cow::Owned(new_field) => Cow::Owned(DataType::List(new_field)),
1211        },
1212        LargeList(field) => match canonicalize_and_verify_field(field)? {
1213            Cow::Borrowed(_) => borrow!(),
1214            Cow::Owned(new_field) => Cow::Owned(DataType::LargeList(new_field)),
1215        },
1216        ListView(field) => match canonicalize_and_verify_field(field)? {
1217            Cow::Borrowed(_) => borrow!(),
1218            Cow::Owned(new_field) => Cow::Owned(DataType::ListView(new_field)),
1219        },
1220        LargeListView(field) => match canonicalize_and_verify_field(field)? {
1221            Cow::Borrowed(_) => borrow!(),
1222            Cow::Owned(new_field) => Cow::Owned(DataType::LargeListView(new_field)),
1223        },
1224        // Struct is used by the internal layout, and can also represent a shredded variant object.
1225        Struct(fields) => {
1226            // Avoid allocation unless at least one field changes, to avoid unnecessary deep cloning
1227            // of the data type. Even if some fields change, the others are shallow arc clones.
1228            let mut new_fields = std::collections::HashMap::new();
1229            for (i, field) in fields.iter().enumerate() {
1230                if skip_top_level_metadata && field.name() == "metadata" {
1231                    continue;
1232                }
1233                if let Cow::Owned(new_field) = canonicalize_and_verify_field(field)? {
1234                    new_fields.insert(i, new_field);
1235                }
1236            }
1237
1238            if new_fields.is_empty() {
1239                borrow!()
1240            } else {
1241                let new_fields = fields
1242                    .iter()
1243                    .enumerate()
1244                    .map(|(i, field)| new_fields.remove(&i).unwrap_or_else(|| field.clone()));
1245                Cow::Owned(DataType::Struct(new_fields.collect()))
1246            }
1247        }
1248        Map(..) | Union(..) => fail!(),
1249
1250        // We can _possibly_ support (some of) these some day?
1251        Dictionary(..) | RunEndEncoded(..) => fail!(),
1252    };
1253    Ok(new_data_type)
1254}
1255
1256fn canonicalize_and_verify_field(field: &Arc<Field>) -> Result<Cow<'_, Arc<Field>>> {
1257    let new_data_type = canonicalize_and_verify_data_type(field.data_type())?;
1258
1259    // A shredded FixedSizeBinary(16) column is always a UUID. Tag it with the UUID extension type
1260    // on read, as a safety net against writers that emit the column without the extension metadata.
1261    // Canonicalization never rewrites FixedSizeBinary(16), so the type is already correct here.
1262    if matches!(new_data_type.as_ref(), DataType::FixedSizeBinary(16))
1263        && !field.has_valid_extension_type::<UuidExtension>()
1264    {
1265        let new_field = field.as_ref().clone().with_extension_type(UuidExtension);
1266        return Ok(Cow::Owned(Arc::new(new_field)));
1267    }
1268
1269    let Cow::Owned(new_data_type) = new_data_type else {
1270        return Ok(Cow::Borrowed(field));
1271    };
1272    let new_field = field.as_ref().clone().with_data_type(new_data_type);
1273    Ok(Cow::Owned(Arc::new(new_field)))
1274}
1275
1276/// Test-only constructors for perfectly shredded arrays, where every value lives in
1277/// `typed_value` and the required `value` column is all-null.
1278#[cfg(test)]
1279impl VariantArray {
1280    pub(crate) fn perfectly_shredded(
1281        metadata: ArrayRef,
1282        typed_value: ArrayRef,
1283        nulls: Option<NullBuffer>,
1284    ) -> Self {
1285        let value = all_null_value_column(typed_value.len());
1286        Self::from_parts(metadata, value, Some(typed_value), nulls)
1287    }
1288}
1289
1290#[cfg(test)]
1291impl ShreddedVariantFieldArray {
1292    pub(crate) fn perfectly_shredded(typed_value: ArrayRef) -> Self {
1293        let value = all_null_value_column(typed_value.len());
1294        Self::from_parts(value, Some(typed_value), None)
1295    }
1296}
1297
1298#[cfg(test)]
1299mod test {
1300    use crate::{GetOptions, VariantArrayBuilder, json_to_variant, variant_get, variant_to_json};
1301    use std::str::FromStr;
1302
1303    use super::*;
1304    use arrow::array::{
1305        BinaryArray, BinaryDictionaryBuilder, BinaryRunBuilder, BinaryViewArray, Decimal32Array,
1306        Decimal64Array, Decimal128Array, FixedSizeBinaryArray, FixedSizeListArray, Int8Array,
1307        Int64Array, LargeBinaryArray, LargeListArray, LargeListViewArray, ListArray, ListViewArray,
1308        StringArray, Time64MicrosecondArray, UInt8Array,
1309    };
1310    use arrow::buffer::{OffsetBuffer, ScalarBuffer};
1311    use arrow_schema::{Field, Fields};
1312    use parquet_variant::{EMPTY_VARIANT_METADATA_BYTES, ShortString};
1313
1314    #[test]
1315    fn invalid_storage_checked_before_canonicalizing() {
1316        // `UInt8` is also an illegal shredded type, but the storage error must win
1317        let array = StructArrayAssembler::new()
1318            .with_field("metadata", make_binary_view_array(), false)
1319            .with_field("value", Arc::new(UInt8Array::from(vec![1])), true)
1320            .build()
1321            .unwrap();
1322        let err = VariantArray::try_new(&array).unwrap_err();
1323        assert_eq!(
1324            err.to_string(),
1325            "Invalid argument error: VariantType 'value' field must be Binary, LargeBinary, or BinaryView, got UInt8"
1326        );
1327    }
1328
1329    #[test]
1330    fn read_missing_value_column() {
1331        // With `typed_value` present, a missing `value` is read leniently: an all-null `value` is
1332        // synthesized and normalized into the inner struct (so a write-back emits it), and values
1333        // still decode from `typed_value`.
1334        let typed_value = Arc::new(Int64Array::from(vec![Some(1), None, Some(3)])) as ArrayRef;
1335        let metadata =
1336            BinaryViewArray::from_iter_values(std::iter::repeat_n(EMPTY_VARIANT_METADATA_BYTES, 3));
1337        let struct_array = StructArrayAssembler::new()
1338            .with_field("metadata", Arc::new(metadata), false)
1339            .with_field("typed_value", typed_value, true)
1340            .build()
1341            .unwrap();
1342        assert!(struct_array.column_by_name("value").is_none());
1343
1344        let variant_array = VariantArray::try_new(&struct_array).unwrap();
1345        assert_eq!(variant_array.value_column().len(), 3);
1346        assert_eq!(variant_array.value_column().null_count(), 3);
1347        assert!(variant_array.inner().column_by_name("value").is_some());
1348        assert!(variant_array.typed_value_column().is_some());
1349        assert_eq!(variant_array.value(0), Variant::from(1i64));
1350        assert_eq!(variant_array.value(1), Variant::Null);
1351        assert_eq!(variant_array.value(2), Variant::from(3i64));
1352    }
1353
1354    #[test]
1355    fn encoded_metadata_supports_nulls_slices_and_variant_get() {
1356        let json: ArrayRef = Arc::new(StringArray::from(vec![
1357            Some(r#"{"a":0}"#),
1358            Some(r#"{"a":1}"#),
1359            None,
1360            Some(r#"{"b":3}"#),
1361            Some(r#"{"b":4}"#),
1362        ]));
1363        let baseline = json_to_variant(&json).unwrap();
1364        let metadata = baseline.metadata_column().as_binary_view();
1365        let metadata_a = metadata.value(0);
1366        let metadata_b = metadata.value(3);
1367
1368        let logical_metadata = [
1369            Some(metadata_a),
1370            Some(metadata_a),
1371            None,
1372            Some(metadata_b),
1373            Some(metadata_b),
1374        ];
1375
1376        let mut dictionary = BinaryDictionaryBuilder::<Int8Type>::new();
1377        dictionary.extend(logical_metadata);
1378        let dictionary: ArrayRef = Arc::new(dictionary.finish());
1379
1380        let mut ree = BinaryRunBuilder::<Int16Type>::new();
1381        ree.extend(logical_metadata);
1382        let run_end_encoded: ArrayRef = Arc::new(ree.finish());
1383
1384        for metadata in [dictionary, run_end_encoded] {
1385            assert_eq!(binary_array_value(metadata.as_ref(), 2), None);
1386            let fields = Fields::from(vec![
1387                Field::new("metadata", metadata.data_type().clone(), false),
1388                Field::new("value", baseline.value_column().data_type().clone(), false),
1389            ]);
1390            let input = StructArray::try_new(
1391                fields,
1392                vec![metadata, baseline.value_column().clone()],
1393                baseline.nulls().cloned(),
1394            )
1395            .unwrap()
1396            .slice(1, 3);
1397
1398            let variant = VariantArray::try_new(&input).unwrap();
1399            assert_eq!(variant.value(0), baseline.value(1));
1400            assert!(variant.is_null(1));
1401            assert_eq!(variant.value(2), baseline.value(3));
1402
1403            let input: ArrayRef = Arc::new(input);
1404            let options = GetOptions::new_with_path("b".try_into().unwrap())
1405                .with_as_type(Some(Arc::new(Field::new("b", DataType::Int8, true))));
1406            let result = variant_get(&input, options).unwrap();
1407            assert_eq!(
1408                result.as_primitive::<Int8Type>(),
1409                &Int8Array::from(vec![None, None, Some(3)])
1410            );
1411            assert_eq!(
1412                variant_to_json(&input).unwrap(),
1413                StringArray::from(vec![Some(r#"{"a":1}"#), None, Some(r#"{"b":3}"#)])
1414            );
1415        }
1416    }
1417
1418    fn make_binary_view_array() -> ArrayRef {
1419        Arc::new(BinaryViewArray::from(vec![b"test" as &[u8]]))
1420    }
1421
1422    fn make_variant_struct_with_typed_value(typed_value: ArrayRef) -> StructArray {
1423        let metadata = BinaryViewArray::from_iter_values(std::iter::repeat_n(
1424            EMPTY_VARIANT_METADATA_BYTES,
1425            typed_value.len(),
1426        ));
1427        let value = new_null_array(&DataType::BinaryView, typed_value.len());
1428        StructArrayAssembler::new()
1429            .with_field("metadata", Arc::new(metadata), false)
1430            .with_field("value", value, true)
1431            .with_field("typed_value", typed_value, true)
1432            .build()
1433            .unwrap()
1434    }
1435
1436    #[test]
1437    fn try_new_tags_untagged_uuid_on_read() {
1438        // Simulate a foreign writer that shredded a UUID column as bare FixedSizeBinary(16),
1439        // omitting the UUID extension type.
1440        let typed_value = FixedSizeBinaryArray::try_from_iter(std::iter::repeat_n([0u8; 16], 2));
1441        let input = make_variant_struct_with_typed_value(Arc::new(typed_value.unwrap()));
1442
1443        // try_new canonicalizes on the read path and attaches the extension.
1444        let variant_array = VariantArray::try_new(&input).unwrap();
1445        let typed_value = variant_array.inner().field_by_name("typed_value").unwrap();
1446        assert_eq!(typed_value.data_type(), &DataType::FixedSizeBinary(16));
1447        assert!(typed_value.has_valid_extension_type::<UuidExtension>());
1448    }
1449
1450    #[test]
1451    fn try_new_tags_untagged_nested_uuid_on_read() {
1452        // A shredded object { id: { typed_value: FixedSizeBinary(16) } } whose inner UUID leaf
1453        // carries no extension type; canonicalization must reach it recursively.
1454        let leaf = FixedSizeBinaryArray::try_from_iter(std::iter::repeat_n([0u8; 16], 1)).unwrap();
1455        let inner = StructArrayAssembler::new()
1456            .with_field("typed_value", Arc::new(leaf), true)
1457            .build()
1458            .unwrap();
1459        let object = StructArrayAssembler::new()
1460            .with_field("id", Arc::new(inner), false)
1461            .build()
1462            .unwrap();
1463        let input = make_variant_struct_with_typed_value(Arc::new(object));
1464
1465        // typed_value (struct) -> id (struct) -> typed_value (the FixedSizeBinary(16) UUID leaf).
1466        let variant_array = VariantArray::try_new(&input).unwrap();
1467        let object = variant_array.typed_value_column().unwrap().as_struct();
1468        let id = object.column_by_name("id").unwrap().as_struct();
1469        let uuid_leaf = id.field_by_name("typed_value").unwrap();
1470        assert!(uuid_leaf.has_valid_extension_type::<UuidExtension>());
1471    }
1472
1473    #[test]
1474    fn all_null_value_column_is_valid_and_unshredded() {
1475        // An all-null `value` column is accepted (only a *missing* column is
1476        // rejected) and the array is unshredded (no typed_value column)
1477        let metadata = BinaryViewArray::from(vec![b"test" as &[u8]; 3]);
1478        let value = new_null_array(&DataType::BinaryView, 3);
1479
1480        let fields = Fields::from(vec![
1481            Field::new("metadata", DataType::BinaryView, false),
1482            Field::new("value", DataType::BinaryView, true),
1483        ]);
1484        let struct_array = StructArray::new(fields, vec![Arc::new(metadata), value], None);
1485
1486        let variant_array = VariantArray::try_new(&struct_array).unwrap();
1487        assert!(variant_array.typed_value_column().is_none());
1488
1489        // The rows are valid but have neither value nor typed_value; the spec
1490        // requires readers to return Variant::Null in this case
1491        for i in 0..variant_array.len() {
1492            assert!(variant_array.is_valid(i));
1493            assert_eq!(variant_array.value(i), Variant::Null);
1494        }
1495    }
1496
1497    #[test]
1498    fn canonicalize_and_verify_list_like_data_types() {
1499        // `parquet/tests/variant_integration.rs` validates Parquet shredded-variant fixtures that
1500        // use Parquet LIST encoding, but those fixtures do not cover Arrow-specific list container
1501        // variants (`LargeList`, `ListView`, `LargeListView`) accepted by `VariantArray::try_new`.
1502        let make_item_binary = || Arc::new(Field::new("item", DataType::Binary, true));
1503        let make_large_binary = || Arc::new(Field::new("item", DataType::LargeBinary, true));
1504        let make_item_binary_view = || Arc::new(Field::new("item", DataType::BinaryView, true));
1505
1506        let cases = vec![
1507            // Binary item
1508            DataType::LargeList(make_item_binary()),
1509            DataType::ListView(make_item_binary()),
1510            DataType::LargeListView(make_item_binary()),
1511            // Large binary item
1512            DataType::LargeList(make_large_binary()),
1513            DataType::ListView(make_large_binary()),
1514            DataType::LargeListView(make_large_binary()),
1515            // Binary view item
1516            DataType::LargeList(make_item_binary_view()),
1517            DataType::ListView(make_item_binary_view()),
1518            DataType::LargeListView(make_item_binary_view()),
1519        ];
1520
1521        for input in cases {
1522            assert_eq!(
1523                canonicalize_and_verify_data_type(&input).unwrap().as_ref(),
1524                &input
1525            );
1526        }
1527    }
1528
1529    #[test]
1530    fn variant_array_try_new_supports_list_like_typed_value() {
1531        let item_field = Arc::new(Field::new("item", DataType::Int64, true));
1532        let values: ArrayRef = Arc::new(Int64Array::from(vec![Some(1), None, Some(3)]));
1533
1534        let typed_values = vec![
1535            Arc::new(ListArray::new(
1536                item_field.clone(),
1537                OffsetBuffer::new(ScalarBuffer::from(vec![0, 2, 3])),
1538                values.clone(),
1539                None,
1540            )) as ArrayRef,
1541            Arc::new(LargeListArray::new(
1542                item_field.clone(),
1543                OffsetBuffer::new(ScalarBuffer::from(vec![0_i64, 2, 3])),
1544                values.clone(),
1545                None,
1546            )) as ArrayRef,
1547            Arc::new(ListViewArray::new(
1548                item_field.clone(),
1549                ScalarBuffer::from(vec![0, 2]),
1550                ScalarBuffer::from(vec![2, 1]),
1551                values.clone(),
1552                None,
1553            )) as ArrayRef,
1554            Arc::new(LargeListViewArray::new(
1555                item_field,
1556                ScalarBuffer::from(vec![0_i64, 2]),
1557                ScalarBuffer::from(vec![2_i64, 1]),
1558                values,
1559                None,
1560            )) as ArrayRef,
1561        ];
1562
1563        for typed_value in typed_values {
1564            let input = make_variant_struct_with_typed_value(typed_value.clone());
1565            let variant_array = VariantArray::try_new(&input).unwrap();
1566            assert_eq!(
1567                variant_array.typed_value_column().unwrap().data_type(),
1568                typed_value.data_type(),
1569            );
1570        }
1571    }
1572
1573    #[test]
1574    fn variant_array_try_new_normalizes_fixed_size_list_typed_value() {
1575        let element_values: ArrayRef =
1576            ShreddedVariantFieldArray::perfectly_shredded(Arc::new(Int64Array::from(vec![
1577                1, 2, 3, 4,
1578            ])))
1579            .into();
1580        let item_field = Arc::new(Field::new("item", element_values.data_type().clone(), true));
1581        let typed_value: ArrayRef = Arc::new(FixedSizeListArray::new(
1582            item_field.clone(),
1583            2,
1584            element_values,
1585            None,
1586        ));
1587        let input = make_variant_struct_with_typed_value(typed_value);
1588
1589        let variant_array = VariantArray::try_new(&input).unwrap();
1590        assert_eq!(
1591            variant_array.typed_value_column().unwrap().data_type(),
1592            &DataType::List(item_field),
1593        );
1594
1595        let unshredded = crate::unshred_variant(&variant_array).unwrap();
1596        assert!(unshredded.typed_value_column().is_none());
1597        assert_eq!(unshredded.len(), 2);
1598    }
1599
1600    #[test]
1601    fn test_try_value_out_of_bounds() {
1602        let mut b = VariantArrayBuilder::new(2);
1603        b.append_variant(Variant::from(1_i8));
1604        b.append_variant(Variant::Null);
1605        let v = b.build();
1606
1607        assert_eq!(v.try_value(0).unwrap(), Variant::Int8(1));
1608        assert_eq!(v.try_value(1).unwrap(), Variant::Null);
1609
1610        let err = v.try_value(2).unwrap_err();
1611        assert_eq!(
1612            err.to_string(),
1613            "Invalid argument error: Index 2 out of bounds for VariantArray of length 2"
1614        );
1615    }
1616
1617    #[test]
1618    fn test_variant_array_iterable() {
1619        let mut b = VariantArrayBuilder::new(6);
1620
1621        b.append_null();
1622        b.append_variant(Variant::from(1_i8));
1623        b.append_variant(Variant::Null);
1624        b.append_variant(Variant::from(2_i32));
1625        b.append_variant(Variant::from(3_i64));
1626        b.append_null();
1627
1628        let v = b.build();
1629
1630        let variants = v.iter().collect::<Vec<_>>();
1631
1632        assert_eq!(
1633            variants,
1634            vec![
1635                None,
1636                Some(Variant::Int8(1)),
1637                Some(Variant::Null),
1638                Some(Variant::Int32(2)),
1639                Some(Variant::Int64(3)),
1640                None,
1641            ]
1642        );
1643    }
1644
1645    #[test]
1646    fn test_variant_array_iter_double_ended() {
1647        let array = VariantArray::from_iter([Some(0_i32), None, Some(2_i32), None, Some(4_i32)]);
1648        let mut iter = array.iter();
1649
1650        assert_eq!(iter.next(), Some(Some(Variant::from(0_i32))));
1651        assert_eq!(iter.next(), Some(None));
1652
1653        assert_eq!(iter.next_back(), Some(Some(Variant::from(4_i32))));
1654        assert_eq!(iter.next_back(), Some(None));
1655        assert_eq!(iter.next_back(), Some(Some(Variant::from(2_i32))));
1656
1657        assert_eq!(iter.next_back(), None);
1658        assert_eq!(iter.next(), None);
1659    }
1660
1661    #[test]
1662    fn test_variant_array_iter_reverse() {
1663        let array = VariantArray::from_iter([Some("a"), None, Some("aaa"), None, Some("aaaaa")]);
1664
1665        let result: Vec<_> = array.iter().rev().collect();
1666        assert_eq!(
1667            result,
1668            vec![
1669                Some(Variant::from("aaaaa")),
1670                None,
1671                Some(Variant::from("aaa")),
1672                None,
1673                Some(Variant::from("a")),
1674            ]
1675        );
1676    }
1677
1678    #[test]
1679    fn test_variant_array_iter_empty() {
1680        let v = VariantArrayBuilder::new(0).build();
1681        let mut i = v.iter();
1682        assert!(i.next().is_none());
1683        assert!(i.next_back().is_none());
1684    }
1685
1686    #[test]
1687    fn test_from_variant_opts_into_variant_array() {
1688        let v = vec![None, Some(Variant::Null), Some(Variant::BooleanFalse), None];
1689
1690        let variant_array = VariantArray::from_iter(v);
1691
1692        assert_eq!(variant_array.len(), 4);
1693
1694        assert!(variant_array.is_null(0));
1695
1696        assert!(!variant_array.is_null(1));
1697        assert_eq!(variant_array.value(1), Variant::Null);
1698
1699        assert!(!variant_array.is_null(2));
1700        assert_eq!(variant_array.value(2), Variant::BooleanFalse);
1701
1702        assert!(variant_array.is_null(3));
1703    }
1704
1705    #[test]
1706    fn test_from_option_into_variants_into_variant_array() {
1707        // Items that convert cleanly to `Variant` can be collected directly,
1708        // without wrapping them in `Some(Variant::from(..))` first
1709        let v = vec![Some(42_i64), None, Some(-1_i64)];
1710
1711        let variant_array = VariantArray::from_iter(v);
1712
1713        assert_eq!(variant_array.len(), 3);
1714
1715        assert!(!variant_array.is_null(0));
1716        assert_eq!(variant_array.value(0), Variant::Int64(42));
1717
1718        assert!(variant_array.is_null(1));
1719
1720        assert!(!variant_array.is_null(2));
1721        assert_eq!(variant_array.value(2), Variant::Int64(-1));
1722    }
1723
1724    #[test]
1725    fn test_from_option_str_into_variant_array() {
1726        let v = vec![
1727            Some("hello"),
1728            None,
1729            Some(
1730                "hello world this is much longer than the maximum short string length of sixty three bytes",
1731            ),
1732        ];
1733
1734        let variant_array: VariantArray = v.into_iter().collect();
1735
1736        assert_eq!(variant_array.len(), 3);
1737
1738        assert!(!variant_array.is_null(0));
1739        assert_eq!(
1740            variant_array.value(0),
1741            Variant::ShortString(ShortString::try_new("hello").unwrap())
1742        );
1743
1744        assert!(variant_array.is_null(1));
1745
1746        assert!(!variant_array.is_null(2));
1747        assert_eq!(
1748            variant_array.value(2),
1749            Variant::String(
1750                "hello world this is much longer than the maximum short string length of sixty three bytes"
1751            )
1752        );
1753    }
1754
1755    #[test]
1756    fn test_from_variants_into_variant_array() {
1757        let v = vec![
1758            Variant::Null,
1759            Variant::BooleanFalse,
1760            Variant::ShortString(ShortString::try_new("norm").unwrap()),
1761        ];
1762
1763        let variant_array = VariantArray::from_iter(v);
1764
1765        assert_eq!(variant_array.len(), 3);
1766
1767        assert!(!variant_array.is_null(0));
1768        assert_eq!(variant_array.value(0), Variant::Null);
1769
1770        assert!(!variant_array.is_null(1));
1771        assert_eq!(variant_array.value(1), Variant::BooleanFalse);
1772
1773        assert!(!variant_array.is_null(2));
1774        assert_eq!(
1775            variant_array.value(2),
1776            Variant::ShortString(ShortString::try_new("norm").unwrap())
1777        );
1778    }
1779
1780    #[test]
1781    fn test_variant_equality() {
1782        let v_iter = [None, Some(Variant::BooleanFalse), Some(Variant::Null), None];
1783        let v = VariantArray::from_iter(v_iter.clone());
1784
1785        {
1786            let v_copy = v.clone();
1787            assert_eq!(v, v_copy);
1788        }
1789
1790        {
1791            let v_iter_reversed = v_iter.iter().cloned().rev();
1792            let v_reversed = VariantArray::from_iter(v_iter_reversed);
1793
1794            assert_ne!(v, v_reversed);
1795        }
1796
1797        {
1798            let v_sliced = v.slice(0, 1);
1799            assert_ne!(v, v_sliced);
1800        }
1801    }
1802
1803    #[test]
1804    fn binary_typed_value_roundtrips() {
1805        // Verify that a shredded variant with Binary typed_value can be read back
1806        let typed_value: ArrayRef = Arc::new(BinaryArray::from(vec![b"hello" as &[u8]]));
1807        let struct_array = make_variant_struct_with_typed_value(typed_value);
1808
1809        let variant_array = VariantArray::try_new(&struct_array).unwrap();
1810        assert_eq!(variant_array.value(0), Variant::from(b"hello" as &[u8]));
1811    }
1812
1813    #[test]
1814    fn large_binary_typed_value_roundtrips() {
1815        // Verify that a shredded variant with LargeBinary typed_value can be read back
1816        let typed_value: ArrayRef = Arc::new(LargeBinaryArray::from(vec![b"world" as &[u8]]));
1817        let struct_array = make_variant_struct_with_typed_value(typed_value);
1818
1819        let variant_array = VariantArray::try_new(&struct_array).unwrap();
1820        assert_eq!(variant_array.value(0), Variant::from(b"world" as &[u8]));
1821    }
1822
1823    macro_rules! invalid_variant_array_test {
1824        ($fn_name: ident, $invalid_typed_value: expr, $error_msg: literal) => {
1825            #[test]
1826            fn $fn_name() {
1827                let invalid_typed_value = $invalid_typed_value;
1828
1829                let struct_array =
1830                    make_variant_struct_with_typed_value(Arc::new(invalid_typed_value));
1831
1832                let array: VariantArray = VariantArray::try_new(&struct_array)
1833                    .expect("should create variant array")
1834                    .into();
1835
1836                let result = array.try_value(0);
1837                assert!(result.is_err());
1838                let error = result.unwrap_err();
1839                assert!(matches!(error, ArrowError::CastError(_)));
1840
1841                let expected: &str = $error_msg;
1842                assert!(
1843                    error.to_string().contains($error_msg),
1844                    "error `{}` did not contain `{}`",
1845                    error,
1846                    expected
1847                )
1848            }
1849        };
1850    }
1851
1852    invalid_variant_array_test!(
1853        test_variant_array_invalid_time,
1854        Time64MicrosecondArray::from(vec![Some(86401000000)]),
1855        "Cast error: Cast failed at index 0 (array type: Time64(µs)): Invalid microsecond from midnight: 86401000000"
1856    );
1857
1858    invalid_variant_array_test!(
1859        test_variant_array_invalid_decimal32,
1860        Decimal32Array::from(vec![Some(1234567890)]),
1861        "Cast error: Cast failed at index 0 (array type: Decimal32(9, 2)): Invalid argument error: 1234567890 is wider than max precision 9"
1862    );
1863
1864    invalid_variant_array_test!(
1865        test_variant_array_invalid_decimal64,
1866        Decimal64Array::from(vec![Some(1234567890123456789)]),
1867        "Cast error: Cast failed at index 0 (array type: Decimal64(18, 6)): Invalid argument error: 1234567890123456789 is wider than max precision 18"
1868    );
1869
1870    invalid_variant_array_test!(
1871        test_variant_array_invalid_decimal128,
1872        Decimal128Array::from(vec![Some(
1873            i128::from_str("123456789012345678901234567890123456789").unwrap()
1874        ),]),
1875        "Cast error: Cast failed at index 0 (array type: Decimal128(38, 10)): Invalid argument error: 123456789012345678901234567890123456789 is wider than max precision 38"
1876    );
1877    #[test]
1878    fn try_value_errors_on_unimplemented_typed_value_type() {
1879        use crate::{json_to_variant, shred_variant};
1880        use arrow::array::StringArray;
1881
1882        let json: ArrayRef = Arc::new(StringArray::from(vec![r#"{"qty": 3}"#]));
1883        let variant = json_to_variant(&json).unwrap();
1884        let shred_type = DataType::Struct(vec![Field::new("qty", DataType::Int64, true)].into());
1885        let shredded = shred_variant(&variant, &shred_type).unwrap();
1886        // Object-shredded typed_value is not yet implemented: reading it must
1887        // error, never silently return Variant::Null
1888        // TODO: https://github.com/apache/arrow-rs/issues/10620
1889        let err = shredded.try_value(0).unwrap_err();
1890        assert!(
1891            err.to_string().starts_with(
1892                "Not yet implemented: VariantArray::try_value cannot materialize typed_value"
1893            ),
1894            "unexpected error: {err}"
1895        );
1896    }
1897}