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


##########
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:
   looks good



-- 
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