alamb commented on code in PR #12309:
URL: https://github.com/apache/arrow-rs/pull/12309#discussion_r4642086122


##########
parquet-variant/src/variant/view.rs:
##########
@@ -0,0 +1,771 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for 
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) 
under one or more contributor license agreements
+
+//! Views over encoded variant bytes that read only what they use. See 
[`VariantView`].
+
+use arrow_schema::ArrowError;
+
+use crate::decoder::{VariantBasicType, get_basic_type};
+use crate::utils::{
+    first_byte_from_slice, overflow_error, slice_from_slice, 
slice_from_slice_at_offset,
+    str_from_bytes, try_binary_search,
+};
+use crate::variant::list::VariantListHeader;
+use crate::variant::metadata::VariantMetadataHeader;
+use crate::variant::object::VariantObjectHeader;
+use crate::variant::{
+    EMPTY_VARIANT_METADATA, Variant, VariantList, VariantMetadata, 
VariantObject,
+};
+
+/// The size of the header byte of a metadata dictionary, object or list.
+const NUM_HEADER_BYTES: u32 = 1;
+
+#[inline]
+fn checked(value: Option<u32>, what: &str) -> Result<u32, ArrowError> {
+    value.ok_or_else(|| overflow_error(what))
+}
+
+fn index_error(kind: &str, index: usize, len: usize) -> ArrowError {
+    ArrowError::InvalidArgumentError(format!(
+        "{kind} index {index} is out of bounds for length {len}"
+    ))
+}
+
+/// A metadata dictionary of which only the header has been read. See 
[`VariantView`].
+#[derive(Debug, Clone, Copy)]
+pub struct VariantMetadataView<'m> {
+    pub(crate) bytes: &'m [u8],
+    pub(crate) header: VariantMetadataHeader,
+    pub(crate) dictionary_size: u32,
+    pub(crate) first_value_byte: u32,
+}
+
+impl<'m> VariantMetadataView<'m> {
+    /// Reads the header and the dictionary size of the metadata dictionary in 
`bytes`.
+    #[inline]
+    pub fn try_new(bytes: &'m [u8]) -> Result<Self, ArrowError> {
+        let header = 
VariantMetadataHeader::try_new(first_byte_from_slice(bytes)?)?;
+        let dictionary_size =
+            header
+                .offset_size
+                .unpack_u32_at_offset(bytes, NUM_HEADER_BYTES as _, 0)?;
+
+        // There are dictionary_size + 1 offsets, and the string bytes 
immediately follow them.
+        let first_value_byte = checked(
+            dictionary_size
+                .checked_add(1)
+                .and_then(|n| n.checked_mul(header.offset_size()))
+                .and_then(|n| n.checked_add(header.first_offset_byte())),
+            "offset of variant metadata dictionary",
+        )?;
+
+        Ok(Self {
+            bytes,
+            header,
+            dictionary_size,
+            first_value_byte,
+        })
+    }
+
+    /// The number of entries in the dictionary.
+    #[inline]
+    pub fn len(&self) -> usize {
+        self.dictionary_size as _
+    }
+
+    /// True if the dictionary has no entries.
+    #[inline]
+    pub fn is_empty(&self) -> bool {
+        self.dictionary_size == 0
+    }
+
+    /// True if the header declares the entries unique and sorted.
+    #[inline]
+    pub fn is_sorted(&self) -> bool {
+        self.header.is_sorted
+    }
+
+    /// The bytes of entry `id`, without UTF-8 validation.
+    #[inline]
+    pub fn entry(&self, id: usize) -> Result<&'m [u8], ArrowError> {
+        if id >= self.len() {
+            return Err(index_error("Metadata dictionary", id, self.len()));
+        }
+        self.read_entry(id)
+    }
+
+    /// The entry `id` as a string.
+    pub fn entry_str(&self, id: usize) -> Result<&'m str, ArrowError> {
+        str_from_bytes(self.entry(id)?)
+    }
+
+    /// The id of the entry equal to `name`, if any.
+    ///
+    /// The search is a binary search if the dictionary is sorted and has more 
than a few entries,
+    /// and a linear scan otherwise.
+    pub fn find(&self, name: &[u8]) -> Result<Option<u32>, ArrowError> {
+        if self.is_sorted() && self.len() > 10 {
+            let found = try_binary_search(self.len(), |id| 
Ok(self.read_entry(id)?.cmp(name)))?;
+            return Ok(found.map(|id| id as u32));
+        }
+        for id in 0..self.len() {
+            if self.read_entry(id)? == name {
+                return Ok(Some(id as u32));
+            }
+        }
+        Ok(None)
+    }
+
+    /// Checks the first and last offsets, and returns the bounded 
[`VariantMetadata`].
+    #[inline]
+    pub fn into_metadata(self) -> Result<VariantMetadata<'m>, ArrowError> {
+        VariantMetadata::try_from_view(self)
+    }
+
+    /// Entry `i` of the offset array, for `i` in `0..=self.len()`.
+    #[inline]
+    pub(crate) fn offset(&self, i: usize) -> Result<u32, ArrowError> {
+        self.header.offset_size.unpack_u32_at_offset(
+            self.bytes,
+            self.header.first_offset_byte() as _,
+            i,
+        )
+    }
+
+    // The bytes of entry `id`, for `id` in `0..self.len()`.
+    #[inline]
+    fn read_entry(&self, id: usize) -> Result<&'m [u8], ArrowError> {
+        let range = self.offset(id)? as usize..self.offset(id + 1)? as usize;
+        slice_from_slice_at_offset(self.bytes, self.first_value_byte as _, 
range)
+    }
+}
+
+/// A variant value of which only the header byte has been read.

Review Comment:
   for anyone else reviewing this PR, this is a good place to start to 
understand what is going on



##########
parquet-variant/src/variant/object.rs:
##########
@@ -413,23 +391,29 @@ impl<'m, 'v> VariantObject<'m, 'v> {
     fn iter_try_with_shallow_validation(
         &self,
     ) -> impl Iterator<Item = Result<(&'m str, Variant<'m, 'v>), ArrowError>> 
+ '_ {
-        (0..self.len()).map(|i| {
-            let field = self.try_field_with_shallow_validation(i)?;
-            Ok((self.try_field_name(i)?, field))
+        // One view serves every field, and the range bounds each field index.
+        let view = self.view();
+        (0..self.len()).map(move |i| {
+            let field = view.read_field(i)?;
+            let field = Variant::try_new_with_metadata_and_shallow_validation(
+                self.metadata.clone(),
+                field.value,
+            )?;
+            Ok((self.metadata.get(view.read_field_id(i)? as _)?, field))
         })
     }
 
     /// Returns the value of the field with the specified name, if any.
     ///
     /// Returns `Some(Variant)` if the field exists, or `None` if the field 
does not exist.
     pub fn get(&self, name: &str) -> Option<Variant<'m, 'v>> {
-        // Binary search through the field IDs of this object to find the 
requested field name.
-        //
         // NOTE: This does not require a sorted metadata dictionary, because 
the variant spec
         // requires object field ids to be lexically sorted by their 
corresponding string values,
         // and probing the dictionary for a field id is always O(1) work.
-        let cmp = |i| Some(self.field_name(i)?.cmp(name));
-        let i = try_binary_search_range_by(0..self.len(), cmp)?.ok()?;
+        let i = self
+            .view()
+            .find(name.as_bytes())

Review Comment:
   the old code discarded the error via `ok()` but this code panics. I suggest 
we keep the old behavior (and change it in a follow on PR if needed)



##########
parquet-variant/src/variant/view.rs:
##########
@@ -0,0 +1,771 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for 
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) 
under one or more contributor license agreements
+
+//! Views over encoded variant bytes that read only what they use. See 
[`VariantView`].
+
+use arrow_schema::ArrowError;
+
+use crate::decoder::{VariantBasicType, get_basic_type};
+use crate::utils::{
+    first_byte_from_slice, overflow_error, slice_from_slice, 
slice_from_slice_at_offset,
+    str_from_bytes, try_binary_search,
+};
+use crate::variant::list::VariantListHeader;
+use crate::variant::metadata::VariantMetadataHeader;
+use crate::variant::object::VariantObjectHeader;
+use crate::variant::{
+    EMPTY_VARIANT_METADATA, Variant, VariantList, VariantMetadata, 
VariantObject,
+};
+
+/// The size of the header byte of a metadata dictionary, object or list.
+const NUM_HEADER_BYTES: u32 = 1;
+
+#[inline]
+fn checked(value: Option<u32>, what: &str) -> Result<u32, ArrowError> {
+    value.ok_or_else(|| overflow_error(what))
+}
+
+fn index_error(kind: &str, index: usize, len: usize) -> ArrowError {
+    ArrowError::InvalidArgumentError(format!(
+        "{kind} index {index} is out of bounds for length {len}"
+    ))
+}
+
+/// A metadata dictionary of which only the header has been read. See 
[`VariantView`].
+#[derive(Debug, Clone, Copy)]
+pub struct VariantMetadataView<'m> {
+    pub(crate) bytes: &'m [u8],
+    pub(crate) header: VariantMetadataHeader,
+    pub(crate) dictionary_size: u32,
+    pub(crate) first_value_byte: u32,
+}
+
+impl<'m> VariantMetadataView<'m> {
+    /// Reads the header and the dictionary size of the metadata dictionary in 
`bytes`.
+    #[inline]
+    pub fn try_new(bytes: &'m [u8]) -> Result<Self, ArrowError> {
+        let header = 
VariantMetadataHeader::try_new(first_byte_from_slice(bytes)?)?;
+        let dictionary_size =
+            header
+                .offset_size
+                .unpack_u32_at_offset(bytes, NUM_HEADER_BYTES as _, 0)?;
+
+        // There are dictionary_size + 1 offsets, and the string bytes 
immediately follow them.
+        let first_value_byte = checked(
+            dictionary_size
+                .checked_add(1)
+                .and_then(|n| n.checked_mul(header.offset_size()))
+                .and_then(|n| n.checked_add(header.first_offset_byte())),
+            "offset of variant metadata dictionary",
+        )?;
+
+        Ok(Self {
+            bytes,
+            header,
+            dictionary_size,
+            first_value_byte,
+        })
+    }
+
+    /// The number of entries in the dictionary.
+    #[inline]
+    pub fn len(&self) -> usize {
+        self.dictionary_size as _
+    }
+
+    /// True if the dictionary has no entries.
+    #[inline]
+    pub fn is_empty(&self) -> bool {
+        self.dictionary_size == 0
+    }
+
+    /// True if the header declares the entries unique and sorted.
+    #[inline]
+    pub fn is_sorted(&self) -> bool {
+        self.header.is_sorted
+    }
+
+    /// The bytes of entry `id`, without UTF-8 validation.
+    #[inline]
+    pub fn entry(&self, id: usize) -> Result<&'m [u8], ArrowError> {
+        if id >= self.len() {
+            return Err(index_error("Metadata dictionary", id, self.len()));
+        }
+        self.read_entry(id)
+    }
+
+    /// The entry `id` as a string.
+    pub fn entry_str(&self, id: usize) -> Result<&'m str, ArrowError> {
+        str_from_bytes(self.entry(id)?)
+    }
+
+    /// The id of the entry equal to `name`, if any.
+    ///
+    /// The search is a binary search if the dictionary is sorted and has more 
than a few entries,
+    /// and a linear scan otherwise.
+    pub fn find(&self, name: &[u8]) -> Result<Option<u32>, ArrowError> {
+        if self.is_sorted() && self.len() > 10 {
+            let found = try_binary_search(self.len(), |id| 
Ok(self.read_entry(id)?.cmp(name)))?;
+            return Ok(found.map(|id| id as u32));
+        }
+        for id in 0..self.len() {
+            if self.read_entry(id)? == name {
+                return Ok(Some(id as u32));
+            }
+        }
+        Ok(None)
+    }
+
+    /// Checks the first and last offsets, and returns the bounded 
[`VariantMetadata`].
+    #[inline]
+    pub fn into_metadata(self) -> Result<VariantMetadata<'m>, ArrowError> {
+        VariantMetadata::try_from_view(self)
+    }
+
+    /// Entry `i` of the offset array, for `i` in `0..=self.len()`.
+    #[inline]
+    pub(crate) fn offset(&self, i: usize) -> Result<u32, ArrowError> {
+        self.header.offset_size.unpack_u32_at_offset(
+            self.bytes,
+            self.header.first_offset_byte() as _,
+            i,
+        )
+    }
+
+    // The bytes of entry `id`, for `id` in `0..self.len()`.
+    #[inline]
+    fn read_entry(&self, id: usize) -> Result<&'m [u8], ArrowError> {
+        let range = self.offset(id)? as usize..self.offset(id + 1)? as usize;
+        slice_from_slice_at_offset(self.bytes, self.first_value_byte as _, 
range)
+    }
+}
+
+/// A variant value of which only the header byte has been read.
+///
+/// Building a view parses one header and nothing else. Each accessor reads 
and bounds-checks only
+/// the bytes it needs, so malformed input produces an error, never a panic. A 
view does not check
+/// UTF-8, sort order, or any offset it does not read. Field names are 
compared as bytes, which
+/// orders them exactly as `str` does.
+///
+/// Use a view to read a few values out of a variant, such as one path per row 
of a column, without
+/// paying for checks that the access does not use.
+///
+/// # Views and validation
+///
+/// The views [`VariantView`], [`VariantMetadataView`], [`VariantObjectView`] 
and
+/// [`VariantListView`] are the weakest state of a variant. The [`Variant`], 
[`VariantMetadata`],
+/// [`VariantObject`] and [`VariantList`] types are the stronger states:
+///
+/// - [`VariantView::to_variant`], [`VariantMetadataView::into_metadata`],
+///   [`VariantObjectView::into_object`] and [`VariantListView::into_list`] 
check the first and
+///   last offsets, which bound the encoding. Unvalidated instances of the 
stronger types guarantee
+///   those checks.
+/// - The `with_full_validation` methods of the stronger types check 
everything else.
+///
+/// # Example
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadataView, 
VariantView};
+/// # use arrow_schema::ArrowError;
+/// # fn main() -> Result<(), ArrowError> {
+/// let mut builder = VariantBuilder::new();
+/// let mut object = builder.new_object();
+/// object.insert("name", "Ferris");
+/// object.new_list("scores").with_value(7i8).with_value(9i8).finish();
+/// object.finish();
+/// let (metadata, value) = builder.finish();
+///
+/// let view = VariantView::try_new(VariantMetadataView::try_new(&metadata)?, 
&value)?;
+/// let scores = view.get_field(b"scores")?.expect("the field exists");
+/// let found = scores.get_index(1)?.expect("the element exists");
+/// assert_eq!(found.to_variant()?, Variant::Int8(9));
+/// assert!(view.get_field(b"missing")?.is_none());
+/// # Ok(())
+/// # }
+/// ```
+#[derive(Debug, Clone, Copy)]
+pub struct VariantView<'m, 'v> {
+    pub(crate) metadata: VariantMetadataView<'m>,
+    pub(crate) value: &'v [u8],
+    header: u8,
+}
+
+impl<'m, 'v> VariantView<'m, 'v> {
+    /// Reads the header byte of the value that starts at the beginning of 
`value`.
+    ///
+    /// `value` may extend past the end of the value.
+    #[inline]
+    pub fn try_new(metadata: VariantMetadataView<'m>, value: &'v [u8]) -> 
Result<Self, ArrowError> {
+        let header = first_byte_from_slice(value)?;
+        Ok(Self {
+            metadata,
+            value,
+            header,
+        })
+    }
+
+    /// The metadata dictionary of this value.
+    #[inline]
+    pub fn metadata(&self) -> VariantMetadataView<'m> {
+        self.metadata
+    }
+
+    /// The basic type of this value.
+    #[inline]
+    pub fn basic_type(&self) -> VariantBasicType {
+        get_basic_type(self.header)
+    }
+
+    /// This value as an object, or `None` if it is not an object.
+    pub fn as_object(&self) -> Result<Option<VariantObjectView<'m, 'v>>, 
ArrowError> {
+        match self.basic_type() {
+            VariantBasicType::Object => {
+                VariantObjectView::try_new(self.metadata, self.value).map(Some)
+            }
+            _ => Ok(None),
+        }
+    }
+
+    /// This value as a list, or `None` if it is not a list.
+    pub fn as_list(&self) -> Result<Option<VariantListView<'m, 'v>>, 
ArrowError> {
+        match self.basic_type() {
+            VariantBasicType::Array => {
+                VariantListView::try_new(self.metadata, self.value).map(Some)
+            }
+            _ => Ok(None),
+        }
+    }
+
+    /// The value of field `name`, or `None` if this value is not an object or 
has no such field.
+    pub fn get_field(&self, name: &[u8]) -> Result<Option<Self>, ArrowError> {
+        match self.as_object()? {
+            Some(object) => object.get(name),
+            None => Ok(None),
+        }
+    }
+
+    /// Element `index`, or `None` if this value is not a list or has no such 
element.
+    pub fn get_index(&self, index: usize) -> Result<Option<Self>, ArrowError> {
+        match self.as_list()? {
+            Some(list) => list.get(index),
+            None => Ok(None),
+        }
+    }
+
+    /// Decodes this value as an unvalidated [`Variant`].
+    ///
+    /// Only an object or a list reads the metadata dictionary, so only they 
check its bounds.
+    #[inline]
+    pub fn to_variant(&self) -> Result<Variant<'m, 'v>, ArrowError> {
+        let metadata = match self.basic_type() {
+            VariantBasicType::Object | VariantBasicType::Array => 
self.metadata.into_metadata()?,
+            VariantBasicType::Primitive | VariantBasicType::ShortString => 
EMPTY_VARIANT_METADATA,
+        };
+        Variant::try_new_with_metadata_and_shallow_validation(metadata, 
self.value)
+    }
+}
+
+/// A variant object of which only the header has been read. See 
[`VariantView`].
+#[derive(Debug, Clone, Copy)]
+pub struct VariantObjectView<'m, 'v> {
+    pub(crate) metadata: VariantMetadataView<'m>,
+    pub(crate) value: &'v [u8],
+    pub(crate) header: VariantObjectHeader,
+    pub(crate) num_elements: u32,
+    pub(crate) first_field_offset_byte: u32,
+    pub(crate) first_value_byte: u32,
+}
+
+impl<'m, 'v> VariantObjectView<'m, 'v> {
+    /// Reads the header and the field count of the object at the start of 
`value`.
+    #[inline]
+    pub fn try_new(metadata: VariantMetadataView<'m>, value: &'v [u8]) -> 
Result<Self, ArrowError> {
+        let header = 
VariantObjectHeader::try_new(first_byte_from_slice(value)?)?;
+        let num_elements =
+            header
+                .num_elements_size
+                .unpack_u32_at_offset(value, NUM_HEADER_BYTES as _, 0)?;
+
+        let first_field_offset_byte = checked(
+            num_elements
+                .checked_mul(header.field_id_size())
+                .and_then(|n| n.checked_add(header.field_ids_start_byte())),
+            "offset of variant object field offsets",
+        )?;
+        let first_value_byte = checked(
+            num_elements
+                .checked_add(1)
+                .and_then(|n| n.checked_mul(header.field_offset_size()))
+                .and_then(|n| n.checked_add(first_field_offset_byte)),
+            "offset of variant object field values",
+        )?;
+
+        Ok(Self {
+            metadata,
+            value,
+            header,
+            num_elements,
+            first_field_offset_byte,
+            first_value_byte,
+        })
+    }
+
+    /// The number of fields.
+    #[inline]
+    pub fn len(&self) -> usize {
+        self.num_elements as _
+    }
+
+    /// True if the object has no fields.
+    #[inline]
+    pub fn is_empty(&self) -> bool {
+        self.num_elements == 0
+    }
+
+    /// The metadata dictionary id of field `i`.
+    pub fn field_id(&self, i: usize) -> Result<u32, ArrowError> {
+        self.check_index(i)?;
+        self.read_field_id(i)
+    }
+
+    /// The name of field `i`, without UTF-8 validation.
+    pub fn field_name(&self, i: usize) -> Result<&'m [u8], ArrowError> {
+        self.check_index(i)?;
+        self.read_field_name(i)
+    }
+
+    /// The value of field `i`.
+    pub fn field(&self, i: usize) -> Result<VariantView<'m, 'v>, ArrowError> {
+        self.check_index(i)?;
+        self.read_field(i)
+    }
+
+    /// The position of the field named `name`, if any.
+    ///
+    /// The spec requires fields to be sorted by name, so this is a binary 
search.
+    pub fn find(&self, name: &[u8]) -> Result<Option<usize>, ArrowError> {
+        try_binary_search(self.len(), |i| 
Ok(self.read_field_name(i)?.cmp(name)))
+    }
+
+    /// The value of the field named `name`, if any.
+    pub fn get(&self, name: &[u8]) -> Result<Option<VariantView<'m, 'v>>, 
ArrowError> {
+        self.find(name)?.map(|i| self.read_field(i)).transpose()
+    }
+
+    /// The size of the encoded object.
+    ///
+    /// The spec makes the last field offset point one byte past the end of 
the last value.
+    pub fn byte_len(&self) -> Result<usize, ArrowError> {
+        let end = checked(
+            self.read_offset(self.len())?
+                .checked_add(self.first_value_byte),
+            "variant object size",
+        )?;
+        Ok(end as _)
+    }
+
+    /// Checks the last field offset, and returns the bounded 
[`VariantObject`] that uses
+    /// `metadata`, the promoted form of this view's metadata dictionary.

Review Comment:
   why do we need to mention the metadata here? It seems unecessary as the 
function doesn't do anything specific with the metadata 🤔 



##########
parquet-variant/src/variant/list.rs:
##########
@@ -14,26 +13,27 @@ use arrow_schema::ArrowError;
 const NUM_HEADER_BYTES: u32 = 1;
 
 /// A parsed version of the variant array value header byte.
-#[derive(Debug, Clone, PartialEq)]
+#[derive(Debug, Clone, Copy, PartialEq)]
 pub(crate) struct VariantListHeader {
-    num_elements_size: OffsetSizeBytes,
-    offset_size: OffsetSizeBytes,
+    pub(crate) num_elements_size: OffsetSizeBytes,

Review Comment:
   why do we need to make the fields `pub(crate)`? The accessors are pub(crate) 
which should be enough (or maybe we have to change them to return 
`OffsetSizeBytes` or something



##########
parquet-variant/src/variant/object.rs:
##########
@@ -14,30 +13,31 @@ use arrow_schema::ArrowError;
 const NUM_HEADER_BYTES: u32 = 1;
 
 /// Header structure for [`VariantObject`]
-#[derive(Debug, Clone, PartialEq)]
+#[derive(Debug, Clone, Copy, PartialEq)]
 pub(crate) struct VariantObjectHeader {
-    num_elements_size: OffsetSizeBytes,
-    field_id_size: OffsetSizeBytes,
-    field_offset_size: OffsetSizeBytes,
+    pub(crate) num_elements_size: OffsetSizeBytes,

Review Comment:
   also here re pub(crate)



##########
parquet-variant/src/variant/view.rs:
##########
@@ -0,0 +1,771 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for 
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) 
under one or more contributor license agreements
+
+//! Views over encoded variant bytes that read only what they use. See 
[`VariantView`].
+
+use arrow_schema::ArrowError;
+
+use crate::decoder::{VariantBasicType, get_basic_type};
+use crate::utils::{
+    first_byte_from_slice, overflow_error, slice_from_slice, 
slice_from_slice_at_offset,
+    str_from_bytes, try_binary_search,
+};
+use crate::variant::list::VariantListHeader;
+use crate::variant::metadata::VariantMetadataHeader;
+use crate::variant::object::VariantObjectHeader;
+use crate::variant::{
+    EMPTY_VARIANT_METADATA, Variant, VariantList, VariantMetadata, 
VariantObject,
+};
+
+/// The size of the header byte of a metadata dictionary, object or list.
+const NUM_HEADER_BYTES: u32 = 1;
+
+#[inline]
+fn checked(value: Option<u32>, what: &str) -> Result<u32, ArrowError> {
+    value.ok_or_else(|| overflow_error(what))
+}
+
+fn index_error(kind: &str, index: usize, len: usize) -> ArrowError {
+    ArrowError::InvalidArgumentError(format!(
+        "{kind} index {index} is out of bounds for length {len}"
+    ))
+}
+
+/// A metadata dictionary of which only the header has been read. See 
[`VariantView`].
+#[derive(Debug, Clone, Copy)]
+pub struct VariantMetadataView<'m> {
+    pub(crate) bytes: &'m [u8],
+    pub(crate) header: VariantMetadataHeader,
+    pub(crate) dictionary_size: u32,
+    pub(crate) first_value_byte: u32,
+}
+
+impl<'m> VariantMetadataView<'m> {
+    /// Reads the header and the dictionary size of the metadata dictionary in 
`bytes`.
+    #[inline]
+    pub fn try_new(bytes: &'m [u8]) -> Result<Self, ArrowError> {
+        let header = 
VariantMetadataHeader::try_new(first_byte_from_slice(bytes)?)?;
+        let dictionary_size =
+            header
+                .offset_size
+                .unpack_u32_at_offset(bytes, NUM_HEADER_BYTES as _, 0)?;
+
+        // There are dictionary_size + 1 offsets, and the string bytes 
immediately follow them.
+        let first_value_byte = checked(
+            dictionary_size
+                .checked_add(1)
+                .and_then(|n| n.checked_mul(header.offset_size()))
+                .and_then(|n| n.checked_add(header.first_offset_byte())),
+            "offset of variant metadata dictionary",
+        )?;
+
+        Ok(Self {
+            bytes,
+            header,
+            dictionary_size,
+            first_value_byte,
+        })
+    }
+
+    /// The number of entries in the dictionary.
+    #[inline]
+    pub fn len(&self) -> usize {
+        self.dictionary_size as _
+    }
+
+    /// True if the dictionary has no entries.
+    #[inline]
+    pub fn is_empty(&self) -> bool {
+        self.dictionary_size == 0
+    }
+
+    /// True if the header declares the entries unique and sorted.
+    #[inline]
+    pub fn is_sorted(&self) -> bool {
+        self.header.is_sorted
+    }
+
+    /// The bytes of entry `id`, without UTF-8 validation.
+    #[inline]
+    pub fn entry(&self, id: usize) -> Result<&'m [u8], ArrowError> {
+        if id >= self.len() {
+            return Err(index_error("Metadata dictionary", id, self.len()));
+        }
+        self.read_entry(id)
+    }
+
+    /// The entry `id` as a string.
+    pub fn entry_str(&self, id: usize) -> Result<&'m str, ArrowError> {
+        str_from_bytes(self.entry(id)?)
+    }
+
+    /// The id of the entry equal to `name`, if any.
+    ///
+    /// The search is a binary search if the dictionary is sorted and has more 
than a few entries,
+    /// and a linear scan otherwise.
+    pub fn find(&self, name: &[u8]) -> Result<Option<u32>, ArrowError> {
+        if self.is_sorted() && self.len() > 10 {
+            let found = try_binary_search(self.len(), |id| 
Ok(self.read_entry(id)?.cmp(name)))?;
+            return Ok(found.map(|id| id as u32));
+        }
+        for id in 0..self.len() {
+            if self.read_entry(id)? == name {
+                return Ok(Some(id as u32));
+            }
+        }
+        Ok(None)
+    }
+
+    /// Checks the first and last offsets, and returns the bounded 
[`VariantMetadata`].
+    #[inline]
+    pub fn into_metadata(self) -> Result<VariantMetadata<'m>, ArrowError> {
+        VariantMetadata::try_from_view(self)
+    }
+
+    /// Entry `i` of the offset array, for `i` in `0..=self.len()`.
+    #[inline]
+    pub(crate) fn offset(&self, i: usize) -> Result<u32, ArrowError> {
+        self.header.offset_size.unpack_u32_at_offset(
+            self.bytes,
+            self.header.first_offset_byte() as _,
+            i,
+        )
+    }
+
+    // The bytes of entry `id`, for `id` in `0..self.len()`.
+    #[inline]
+    fn read_entry(&self, id: usize) -> Result<&'m [u8], ArrowError> {
+        let range = self.offset(id)? as usize..self.offset(id + 1)? as usize;
+        slice_from_slice_at_offset(self.bytes, self.first_value_byte as _, 
range)
+    }
+}
+
+/// A variant value of which only the header byte has been read.
+///
+/// Building a view parses one header and nothing else. Each accessor reads 
and bounds-checks only
+/// the bytes it needs, so malformed input produces an error, never a panic. A 
view does not check
+/// UTF-8, sort order, or any offset it does not read. Field names are 
compared as bytes, which
+/// orders them exactly as `str` does.
+///
+/// Use a view to read a few values out of a variant, such as one path per row 
of a column, without
+/// paying for checks that the access does not use.
+///
+/// # Views and validation
+///
+/// The views [`VariantView`], [`VariantMetadataView`], [`VariantObjectView`] 
and
+/// [`VariantListView`] are the weakest state of a variant. The [`Variant`], 
[`VariantMetadata`],
+/// [`VariantObject`] and [`VariantList`] types are the stronger states:
+///
+/// - [`VariantView::to_variant`], [`VariantMetadataView::into_metadata`],
+///   [`VariantObjectView::into_object`] and [`VariantListView::into_list`] 
check the first and
+///   last offsets, which bound the encoding. Unvalidated instances of the 
stronger types guarantee
+///   those checks.
+/// - The `with_full_validation` methods of the stronger types check 
everything else.
+///

Review Comment:
   I found this description somewhat redundant and confusing. How about 
something like this to make it clearer
   
   ```suggestion
   /// Views such as [`VariantView`], [`VariantMetadataView`], 
[`VariantObjectView`] 
   /// do the minimum parsing work needed, and defer as much value validation 
as possible to
   /// when the field is accessed. This is more efficient when reading a few 
values out of a variant, 
   /// such as a path, without validating the entire object.
   /// 
   /// For cases that need to validate the entire variant, use 
   /// [`Variant`], [`VariantMetadata`],
   /// [`VariantObject`] and [`VariantList`], which do much more validation 
during construction and 
   /// offer `with_full_validation` methods for additional checks. 
   ```



##########
parquet-variant/src/variant.rs:
##########
@@ -8,14 +8,14 @@ pub use self::metadata::{
     EMPTY_VARIANT_METADATA, EMPTY_VARIANT_METADATA_BYTES, 
VARIANT_SPEC_VERSION, VariantMetadata,
 };
 pub use self::object::VariantObject;
+pub use self::view::{VariantListView, VariantMetadataView, VariantObjectView, 
VariantView};

Review Comment:
   It would be nice to list VariantView here too:
   
   <img width="1099" height="587" alt="Screenshot 2026-11-20 at 7 37 11 AM" 
src="https://github.com/user-attachments/assets/5368cb13-d554-4446-a44d-3553f6efe27e";
 />



##########
parquet-variant/src/builder/metadata.rs:
##########
@@ -117,6 +125,15 @@ impl MetadataBuilder for ReadOnlyMetadataBuilder<'_> {
     fn field_name(&self, field_id: usize) -> &str {
         &self.metadata[field_id]
     }
+    // Byte order is `str` order, so the comparison needs no UTF-8 validation.

Review Comment:
   This comment seems like it should be attached to the code below
   
   ```rust
           // Byte order is `str` order, so the comparison needs no UTF-8 
validation.
           name(field_a_id).cmp(name(field_b_id))
   ```
   
   And then the docstring here should be
   
   ```rust
      /// Compares the field names of two field ids, which must be less than
       /// [`Self::num_field_names`]. Panics if a field id is out of bounds.
   ```
   



##########
parquet-variant/src/variant/metadata.rs:
##########
@@ -4,19 +4,19 @@
 
 use crate::decoder::{OffsetSizeBytes, map_bytes_to_offsets};
 use crate::utils::{
-    first_byte_from_slice, overflow_error, slice_from_slice, 
slice_from_slice_at_offset,
-    string_from_slice, try_binary_search_range_by,
+    overflow_error, slice_from_slice, str_from_bytes, string_from_slice, 
try_binary_search_range_by,
 };
+use crate::variant::view::VariantMetadataView;
 
 use arrow_schema::ArrowError;
 
 /// Header structure for [`VariantMetadata`]
 #[derive(Debug, Clone, Copy, PartialEq)]
 pub(crate) struct VariantMetadataHeader {
     version: u8,
-    is_sorted: bool,
+    pub(crate) is_sorted: bool,

Review Comment:
   likewise here it would be nice to use accessors rather than pub (crate) 
fields



##########
parquet-variant/src/variant/view.rs:
##########
@@ -0,0 +1,771 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for 
additional information regarding copyright ownership
+// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) 
under one or more contributor license agreements
+
+//! Views over encoded variant bytes that read only what they use. See 
[`VariantView`].
+
+use arrow_schema::ArrowError;
+
+use crate::decoder::{VariantBasicType, get_basic_type};
+use crate::utils::{
+    first_byte_from_slice, overflow_error, slice_from_slice, 
slice_from_slice_at_offset,
+    str_from_bytes, try_binary_search,
+};
+use crate::variant::list::VariantListHeader;
+use crate::variant::metadata::VariantMetadataHeader;
+use crate::variant::object::VariantObjectHeader;
+use crate::variant::{
+    EMPTY_VARIANT_METADATA, Variant, VariantList, VariantMetadata, 
VariantObject,
+};
+
+/// The size of the header byte of a metadata dictionary, object or list.
+const NUM_HEADER_BYTES: u32 = 1;
+
+#[inline]
+fn checked(value: Option<u32>, what: &str) -> Result<u32, ArrowError> {
+    value.ok_or_else(|| overflow_error(what))
+}
+
+fn index_error(kind: &str, index: usize, len: usize) -> ArrowError {
+    ArrowError::InvalidArgumentError(format!(
+        "{kind} index {index} is out of bounds for length {len}"
+    ))
+}
+
+/// A metadata dictionary of which only the header has been read. See 
[`VariantView`].
+#[derive(Debug, Clone, Copy)]
+pub struct VariantMetadataView<'m> {
+    pub(crate) bytes: &'m [u8],
+    pub(crate) header: VariantMetadataHeader,
+    pub(crate) dictionary_size: u32,
+    pub(crate) first_value_byte: u32,
+}
+
+impl<'m> VariantMetadataView<'m> {
+    /// Reads the header and the dictionary size of the metadata dictionary in 
`bytes`.
+    #[inline]
+    pub fn try_new(bytes: &'m [u8]) -> Result<Self, ArrowError> {
+        let header = 
VariantMetadataHeader::try_new(first_byte_from_slice(bytes)?)?;
+        let dictionary_size =
+            header
+                .offset_size
+                .unpack_u32_at_offset(bytes, NUM_HEADER_BYTES as _, 0)?;
+
+        // There are dictionary_size + 1 offsets, and the string bytes 
immediately follow them.
+        let first_value_byte = checked(
+            dictionary_size
+                .checked_add(1)
+                .and_then(|n| n.checked_mul(header.offset_size()))
+                .and_then(|n| n.checked_add(header.first_offset_byte())),
+            "offset of variant metadata dictionary",
+        )?;
+
+        Ok(Self {
+            bytes,
+            header,
+            dictionary_size,
+            first_value_byte,
+        })
+    }
+
+    /// The number of entries in the dictionary.
+    #[inline]
+    pub fn len(&self) -> usize {
+        self.dictionary_size as _
+    }
+
+    /// True if the dictionary has no entries.
+    #[inline]
+    pub fn is_empty(&self) -> bool {
+        self.dictionary_size == 0
+    }
+
+    /// True if the header declares the entries unique and sorted.
+    #[inline]
+    pub fn is_sorted(&self) -> bool {
+        self.header.is_sorted
+    }
+
+    /// The bytes of entry `id`, without UTF-8 validation.
+    #[inline]
+    pub fn entry(&self, id: usize) -> Result<&'m [u8], ArrowError> {
+        if id >= self.len() {
+            return Err(index_error("Metadata dictionary", id, self.len()));
+        }
+        self.read_entry(id)
+    }
+
+    /// The entry `id` as a string.
+    pub fn entry_str(&self, id: usize) -> Result<&'m str, ArrowError> {
+        str_from_bytes(self.entry(id)?)
+    }
+
+    /// The id of the entry equal to `name`, if any.
+    ///
+    /// The search is a binary search if the dictionary is sorted and has more 
than a few entries,
+    /// and a linear scan otherwise.
+    pub fn find(&self, name: &[u8]) -> Result<Option<u32>, ArrowError> {
+        if self.is_sorted() && self.len() > 10 {
+            let found = try_binary_search(self.len(), |id| 
Ok(self.read_entry(id)?.cmp(name)))?;
+            return Ok(found.map(|id| id as u32));
+        }
+        for id in 0..self.len() {
+            if self.read_entry(id)? == name {
+                return Ok(Some(id as u32));
+            }
+        }
+        Ok(None)
+    }
+
+    /// Checks the first and last offsets, and returns the bounded 
[`VariantMetadata`].
+    #[inline]
+    pub fn into_metadata(self) -> Result<VariantMetadata<'m>, ArrowError> {
+        VariantMetadata::try_from_view(self)
+    }
+
+    /// Entry `i` of the offset array, for `i` in `0..=self.len()`.
+    #[inline]
+    pub(crate) fn offset(&self, i: usize) -> Result<u32, ArrowError> {
+        self.header.offset_size.unpack_u32_at_offset(
+            self.bytes,
+            self.header.first_offset_byte() as _,
+            i,
+        )
+    }
+
+    // The bytes of entry `id`, for `id` in `0..self.len()`.
+    #[inline]
+    fn read_entry(&self, id: usize) -> Result<&'m [u8], ArrowError> {
+        let range = self.offset(id)? as usize..self.offset(id + 1)? as usize;
+        slice_from_slice_at_offset(self.bytes, self.first_value_byte as _, 
range)
+    }
+}
+
+/// A variant value of which only the header byte has been read.
+///
+/// Building a view parses one header and nothing else. Each accessor reads 
and bounds-checks only
+/// the bytes it needs, so malformed input produces an error, never a panic. A 
view does not check
+/// UTF-8, sort order, or any offset it does not read. Field names are 
compared as bytes, which
+/// orders them exactly as `str` does.
+///
+/// Use a view to read a few values out of a variant, such as one path per row 
of a column, without
+/// paying for checks that the access does not use.
+///
+/// # Views and validation
+///
+/// The views [`VariantView`], [`VariantMetadataView`], [`VariantObjectView`] 
and
+/// [`VariantListView`] are the weakest state of a variant. The [`Variant`], 
[`VariantMetadata`],
+/// [`VariantObject`] and [`VariantList`] types are the stronger states:
+///
+/// - [`VariantView::to_variant`], [`VariantMetadataView::into_metadata`],
+///   [`VariantObjectView::into_object`] and [`VariantListView::into_list`] 
check the first and
+///   last offsets, which bound the encoding. Unvalidated instances of the 
stronger types guarantee
+///   those checks.
+/// - The `with_full_validation` methods of the stronger types check 
everything else.
+///
+/// # Example
+///
+/// ```
+/// # use parquet_variant::{Variant, VariantBuilder, VariantMetadataView, 
VariantView};
+/// # use arrow_schema::ArrowError;
+/// # fn main() -> Result<(), ArrowError> {
+/// let mut builder = VariantBuilder::new();
+/// let mut object = builder.new_object();
+/// object.insert("name", "Ferris");
+/// object.new_list("scores").with_value(7i8).with_value(9i8).finish();
+/// object.finish();
+/// let (metadata, value) = builder.finish();
+///
+/// let view = VariantView::try_new(VariantMetadataView::try_new(&metadata)?, 
&value)?;
+/// let scores = view.get_field(b"scores")?.expect("the field exists");
+/// let found = scores.get_index(1)?.expect("the element exists");
+/// assert_eq!(found.to_variant()?, Variant::Int8(9));
+/// assert!(view.get_field(b"missing")?.is_none());
+/// # Ok(())
+/// # }
+/// ```
+#[derive(Debug, Clone, Copy)]
+pub struct VariantView<'m, 'v> {
+    pub(crate) metadata: VariantMetadataView<'m>,
+    pub(crate) value: &'v [u8],
+    header: u8,
+}
+
+impl<'m, 'v> VariantView<'m, 'v> {
+    /// Reads the header byte of the value that starts at the beginning of 
`value`.
+    ///
+    /// `value` may extend past the end of the value.
+    #[inline]
+    pub fn try_new(metadata: VariantMetadataView<'m>, value: &'v [u8]) -> 
Result<Self, ArrowError> {
+        let header = first_byte_from_slice(value)?;
+        Ok(Self {
+            metadata,
+            value,
+            header,
+        })
+    }
+
+    /// The metadata dictionary of this value.
+    #[inline]
+    pub fn metadata(&self) -> VariantMetadataView<'m> {
+        self.metadata
+    }
+
+    /// The basic type of this value.
+    #[inline]
+    pub fn basic_type(&self) -> VariantBasicType {
+        get_basic_type(self.header)
+    }
+
+    /// This value as an object, or `None` if it is not an object.
+    pub fn as_object(&self) -> Result<Option<VariantObjectView<'m, 'v>>, 
ArrowError> {
+        match self.basic_type() {
+            VariantBasicType::Object => {
+                VariantObjectView::try_new(self.metadata, self.value).map(Some)
+            }
+            _ => Ok(None),
+        }
+    }
+
+    /// This value as a list, or `None` if it is not a list.
+    pub fn as_list(&self) -> Result<Option<VariantListView<'m, 'v>>, 
ArrowError> {
+        match self.basic_type() {
+            VariantBasicType::Array => {
+                VariantListView::try_new(self.metadata, self.value).map(Some)
+            }
+            _ => Ok(None),
+        }
+    }
+
+    /// The value of field `name`, or `None` if this value is not an object or 
has no such field.
+    pub fn get_field(&self, name: &[u8]) -> Result<Option<Self>, ArrowError> {
+        match self.as_object()? {
+            Some(object) => object.get(name),
+            None => Ok(None),
+        }
+    }
+
+    /// Element `index`, or `None` if this value is not a list or has no such 
element.
+    pub fn get_index(&self, index: usize) -> Result<Option<Self>, ArrowError> {
+        match self.as_list()? {
+            Some(list) => list.get(index),
+            None => Ok(None),
+        }
+    }
+
+    /// Decodes this value as an unvalidated [`Variant`].
+    ///
+    /// Only an object or a list reads the metadata dictionary, so only they 
check its bounds.
+    #[inline]
+    pub fn to_variant(&self) -> Result<Variant<'m, 'v>, ArrowError> {
+        let metadata = match self.basic_type() {
+            VariantBasicType::Object | VariantBasicType::Array => 
self.metadata.into_metadata()?,
+            VariantBasicType::Primitive | VariantBasicType::ShortString => 
EMPTY_VARIANT_METADATA,
+        };
+        Variant::try_new_with_metadata_and_shallow_validation(metadata, 
self.value)
+    }
+}
+
+/// A variant object of which only the header has been read. See 
[`VariantView`].
+#[derive(Debug, Clone, Copy)]
+pub struct VariantObjectView<'m, 'v> {
+    pub(crate) metadata: VariantMetadataView<'m>,
+    pub(crate) value: &'v [u8],
+    pub(crate) header: VariantObjectHeader,
+    pub(crate) num_elements: u32,
+    pub(crate) first_field_offset_byte: u32,
+    pub(crate) first_value_byte: u32,
+}
+
+impl<'m, 'v> VariantObjectView<'m, 'v> {
+    /// Reads the header and the field count of the object at the start of 
`value`.
+    #[inline]
+    pub fn try_new(metadata: VariantMetadataView<'m>, value: &'v [u8]) -> 
Result<Self, ArrowError> {
+        let header = 
VariantObjectHeader::try_new(first_byte_from_slice(value)?)?;
+        let num_elements =
+            header
+                .num_elements_size
+                .unpack_u32_at_offset(value, NUM_HEADER_BYTES as _, 0)?;
+
+        let first_field_offset_byte = checked(
+            num_elements
+                .checked_mul(header.field_id_size())
+                .and_then(|n| n.checked_add(header.field_ids_start_byte())),
+            "offset of variant object field offsets",
+        )?;
+        let first_value_byte = checked(
+            num_elements
+                .checked_add(1)
+                .and_then(|n| n.checked_mul(header.field_offset_size()))
+                .and_then(|n| n.checked_add(first_field_offset_byte)),
+            "offset of variant object field values",
+        )?;
+
+        Ok(Self {
+            metadata,
+            value,
+            header,
+            num_elements,
+            first_field_offset_byte,
+            first_value_byte,
+        })
+    }
+
+    /// The number of fields.
+    #[inline]
+    pub fn len(&self) -> usize {
+        self.num_elements as _
+    }
+
+    /// True if the object has no fields.
+    #[inline]
+    pub fn is_empty(&self) -> bool {
+        self.num_elements == 0
+    }
+
+    /// The metadata dictionary id of field `i`.
+    pub fn field_id(&self, i: usize) -> Result<u32, ArrowError> {
+        self.check_index(i)?;
+        self.read_field_id(i)
+    }
+
+    /// The name of field `i`, without UTF-8 validation.
+    pub fn field_name(&self, i: usize) -> Result<&'m [u8], ArrowError> {
+        self.check_index(i)?;
+        self.read_field_name(i)
+    }
+
+    /// The value of field `i`.
+    pub fn field(&self, i: usize) -> Result<VariantView<'m, 'v>, ArrowError> {
+        self.check_index(i)?;
+        self.read_field(i)
+    }
+
+    /// The position of the field named `name`, if any.
+    ///
+    /// The spec requires fields to be sorted by name, so this is a binary 
search.
+    pub fn find(&self, name: &[u8]) -> Result<Option<usize>, ArrowError> {
+        try_binary_search(self.len(), |i| 
Ok(self.read_field_name(i)?.cmp(name)))
+    }
+
+    /// The value of the field named `name`, if any.
+    pub fn get(&self, name: &[u8]) -> Result<Option<VariantView<'m, 'v>>, 
ArrowError> {
+        self.find(name)?.map(|i| self.read_field(i)).transpose()
+    }
+
+    /// The size of the encoded object.
+    ///
+    /// The spec makes the last field offset point one byte past the end of 
the last value.
+    pub fn byte_len(&self) -> Result<usize, ArrowError> {
+        let end = checked(
+            self.read_offset(self.len())?
+                .checked_add(self.first_value_byte),
+            "variant object size",
+        )?;
+        Ok(end as _)
+    }
+
+    /// Checks the last field offset, and returns the bounded 
[`VariantObject`] that uses
+    /// `metadata`, the promoted form of this view's metadata dictionary.
+    #[inline]
+    pub fn into_object(
+        self,
+        metadata: VariantMetadata<'m>,
+    ) -> Result<VariantObject<'m, 'v>, ArrowError> {
+        VariantObject::try_from_view(self, metadata)
+    }
+
+    #[inline]
+    fn check_index(&self, i: usize) -> Result<(), ArrowError> {
+        match i < self.len() {
+            true => Ok(()),
+            false => Err(index_error("Variant object field", i, self.len())),
+        }
+    }
+
+    // The reads below take a field index in `0..self.len()`, which the caller 
has checked.
+    // `read_offset` also takes `self.len()`, for the end of the last value.
+
+    #[inline]
+    pub(crate) fn read_field_id(&self, i: usize) -> Result<u32, ArrowError> {
+        self.header.field_id_size.unpack_u32_at_offset(
+            self.value,
+            self.header.field_ids_start_byte() as _,
+            i,
+        )
+    }
+
+    #[inline]
+    fn read_field_name(&self, i: usize) -> Result<&'m [u8], ArrowError> {
+        self.metadata.entry(self.read_field_id(i)? as _)
+    }
+
+    #[inline]
+    fn read_offset(&self, i: usize) -> Result<u32, ArrowError> {
+        self.header.field_offset_size.unpack_u32_at_offset(
+            self.value,
+            self.first_field_offset_byte as _,
+            i,
+        )
+    }
+
+    #[inline]
+    pub(crate) fn read_field(&self, i: usize) -> Result<VariantView<'m, 'v>, 
ArrowError> {
+        let start = checked(
+            self.read_offset(i)?.checked_add(self.first_value_byte),
+            "variant object field start",
+        )?;
+        VariantView::try_new(
+            self.metadata,
+            slice_from_slice(self.value, start as usize..)?,
+        )
+    }
+}
+
+/// A variant list of which only the header has been read. See [`VariantView`].
+#[derive(Debug, Clone, Copy)]
+pub struct VariantListView<'m, 'v> {
+    pub(crate) metadata: VariantMetadataView<'m>,
+    pub(crate) value: &'v [u8],
+    pub(crate) header: VariantListHeader,
+    pub(crate) num_elements: u32,
+    pub(crate) first_value_byte: u32,
+}
+
+impl<'m, 'v> VariantListView<'m, 'v> {
+    /// Reads the header and the element count of the list at the start of 
`value`.
+    #[inline]
+    pub fn try_new(metadata: VariantMetadataView<'m>, value: &'v [u8]) -> 
Result<Self, ArrowError> {
+        let header = 
VariantListHeader::try_new(first_byte_from_slice(value)?)?;
+        let num_elements =
+            header
+                .num_elements_size
+                .unpack_u32_at_offset(value, NUM_HEADER_BYTES as _, 0)?;
+
+        // There are num_elements + 1 offsets, and the values immediately 
follow them.
+        let first_value_byte = checked(
+            num_elements
+                .checked_add(1)
+                .and_then(|n| n.checked_mul(header.offset_size()))
+                .and_then(|n| n.checked_add(header.first_offset_byte())),
+            "offset of variant list values",
+        )?;
+
+        Ok(Self {
+            metadata,
+            value,
+            header,
+            num_elements,
+            first_value_byte,
+        })
+    }
+
+    /// The number of elements.
+    #[inline]
+    pub fn len(&self) -> usize {
+        self.num_elements as _
+    }
+
+    /// True if the list has no elements.
+    #[inline]
+    pub fn is_empty(&self) -> bool {
+        self.num_elements == 0
+    }
+
+    /// Element `index`, or `None` if `index` is out of bounds.
+    pub fn get(&self, index: usize) -> Result<Option<VariantView<'m, 'v>>, 
ArrowError> {
+        if index >= self.len() {
+            return Ok(None);
+        }
+        let start = checked(
+            self.read_offset(index)?.checked_add(self.first_value_byte),
+            "variant list element start",
+        )?;
+        VariantView::try_new(
+            self.metadata,
+            slice_from_slice(self.value, start as usize..)?,
+        )
+        .map(Some)
+    }
+
+    /// The size of the encoded list.
+    pub fn byte_len(&self) -> Result<usize, ArrowError> {
+        let end = checked(
+            self.read_offset(self.len())?
+                .checked_add(self.first_value_byte),
+            "variant array size",
+        )?;
+        Ok(end as _)
+    }
+
+    /// Checks the first and last offsets, and returns the bounded 
[`VariantList`] that uses
+    /// `metadata`, the promoted form of this view's metadata dictionary.

Review Comment:
   same comment here about `metadata` reference -- I think we should clean up 
the comment



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to