diff --git a/parquet-variant/src/builder/metadata.rs b/parquet-variant/src/builder/metadata.rs index 38582ed32f87..281559368305 100644 --- a/parquet-variant/src/builder/metadata.rs +++ b/parquet-variant/src/builder/metadata.rs @@ -2,6 +2,7 @@ // 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 +use std::cmp::Ordering; use std::collections::HashMap; use arrow_schema::ArrowError; @@ -30,6 +31,13 @@ pub trait MetadataBuilder: std::fmt::Debug { /// [`Self::num_field_names`]. Panics if the field id is out of bounds. fn field_name(&self, field_id: usize) -> &str; + /// 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. + fn cmp_field_names(&self, field_a_id: u32, field_b_id: u32) -> Ordering { + self.field_name(field_a_id as _) + .cmp(self.field_name(field_b_id as _)) + } + /// Returns the number of field names stored in this metadata builder. Any number less than this /// is a valid field id. The builder can be reverted back to this size later on (discarding any /// newer/higher field ids) by calling [`Self::truncate_field_names`]. @@ -117,6 +125,17 @@ impl MetadataBuilder for ReadOnlyMetadataBuilder<'_> { fn field_name(&self, field_id: usize) -> &str { &self.metadata[field_id] } + /// 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. + fn cmp_field_names(&self, field_a_id: u32, field_b_id: u32) -> Ordering { + let view = self.metadata.view(); + let name = |id: u32| { + view.entry(id as _) + .expect("Invalid metadata dictionary entry") + }; + // Byte order is `str` order, so the comparison needs no UTF-8 validation. + name(field_a_id).cmp(name(field_b_id)) + } fn num_field_names(&self) -> usize { self.metadata.len() } diff --git a/parquet-variant/src/builder/object.rs b/parquet-variant/src/builder/object.rs index c6ecc5927c6e..9a92f25921c5 100644 --- a/parquet-variant/src/builder/object.rs +++ b/parquet-variant/src/builder/object.rs @@ -251,9 +251,7 @@ impl<'a, S: BuilderSpecificState> ObjectBuilder<'a, S> { let metadata_builder = self.parent_state.metadata_builder(); self.fields.sort_by(|&field_a_id, _, &field_b_id, _| { - let field_a_name = metadata_builder.field_name(field_a_id as usize); - let field_b_name = metadata_builder.field_name(field_b_id as usize); - field_a_name.cmp(field_b_name) + metadata_builder.cmp_field_names(field_a_id, field_b_id) }); let max_id = self.fields.iter().map(|(i, _)| *i).max().unwrap_or(0); diff --git a/parquet-variant/src/decoder.rs b/parquet-variant/src/decoder.rs index e99005e5c865..d87b967b9fee 100644 --- a/parquet-variant/src/decoder.rs +++ b/parquet-variant/src/decoder.rs @@ -137,6 +137,18 @@ impl OffsetSizeBytes { Ok(result) } + /// Build from two `offset_size_minus_one` bits, ignoring the higher bits. + #[inline] + pub(crate) const fn from_bits(offset_size_minus_one: u8) -> Self { + use OffsetSizeBytes::*; + match offset_size_minus_one & 0x03 { + 0 => One, + 1 => Two, + 2 => Three, + _ => Four, + } + } + /// Return one unsigned little-endian value from `bytes`. /// /// * `bytes` – the byte buffer to index diff --git a/parquet-variant/src/lib.rs b/parquet-variant/src/lib.rs index ce4fcaaeae69..59bc3b7ba84b 100644 --- a/parquet-variant/src/lib.rs +++ b/parquet-variant/src/lib.rs @@ -10,6 +10,7 @@ //! ## Main APIs //! - [`Variant`]: Represents a variant value, which can be an object, list, or primitive. //! - [`VariantBuilder`]: For building `Variant` values. +//! - [`VariantView`]: Reads a few values out of encoded variant bytes without validating the rest. //! //! ## 🚧 Work In Progress //! diff --git a/parquet-variant/src/utils.rs b/parquet-variant/src/utils.rs index 7c9ca8ef1fbc..8045cb7384f0 100644 --- a/parquet-variant/src/utils.rs +++ b/parquet-variant/src/utils.rs @@ -57,6 +57,7 @@ pub(crate) fn array_from_slice( .map_err(|e: TryFromSliceError| ArrowError::InvalidArgumentError(e.to_string())) } +#[inline] pub(crate) fn first_byte_from_slice(slice: &[u8]) -> Result { slice .first() @@ -93,40 +94,23 @@ pub(crate) fn str_from_bytes(bytes: &[u8]) -> Result<&str, ArrowError> { .map_err(|_| ArrowError::InvalidArgumentError("invalid UTF-8 string".to_string())) } -/// Performs a binary search over a range using a fallible key extraction function; a failed key -/// extraction immediately terminates the search. -/// -/// This is similar to the standard library's `binary_search_by`, but generalized to ranges instead -/// of slices. +/// Binary search over `range` with a fallible comparison, which returns the first error it hits. /// -/// # Arguments -/// * `range` - The range to search in -/// * `target` - The target value to search for -/// * `key_extractor` - A function that extracts a comparable key from slice elements. -/// This function can fail and return None. -/// -/// # Returns -/// * `Some(Ok(index))` - Element found at the given index -/// * `Some(Err(index))` - Element not found, but would be inserted at the given index -/// * `None` - Key extraction failed -pub(crate) fn try_binary_search_range_by( +/// Returns the index for which `cmp` returns [`Ordering::Equal`], if any. +pub(crate) fn try_binary_search_range_by( range: Range, - cmp: F, -) -> Option> -where - F: Fn(usize) -> Option, -{ + cmp: impl Fn(usize) -> Result, +) -> Result, ArrowError> { let Range { mut start, mut end } = range; while start < end { let mid = start + (end - start) / 2; match cmp(mid)? { - Ordering::Equal => return Some(Ok(mid)), + Ordering::Equal => return Ok(Some(mid)), Ordering::Greater => end = mid, Ordering::Less => start = mid + 1, } } - - Some(Err(start)) + Ok(None) } /// Verifies the expected size of type T, for a type that should only grow if absolutely necessary. diff --git a/parquet-variant/src/variant.rs b/parquet-variant/src/variant.rs index e8175bdec9d7..493aa081319c 100644 --- a/parquet-variant/src/variant.rs +++ b/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}; // Publicly export types used in the API +pub use crate::decoder::VariantBasicType; pub use half::f16; pub use uuid::Uuid; -use crate::decoder::{ - self, VariantBasicType, VariantPrimitiveType, get_basic_type, get_primitive_type, -}; +use crate::decoder::{self, VariantPrimitiveType, get_basic_type, get_primitive_type}; use crate::path::{VariantPath, VariantPathElement}; use crate::utils::{first_byte_from_slice, slice_from_slice}; use std::ops::Deref; @@ -27,6 +27,7 @@ mod decimal; mod list; mod metadata; mod object; +mod view; const MAX_SHORT_STRING_BYTES: usize = 0x3F; @@ -207,6 +208,9 @@ impl Deref for ShortString<'_> { /// knows the underlying bytes were already validated previously, or if the caller intends to /// perform a small number of (fallible) accesses to a large variant value. /// +/// A [`VariantView`] reads only the bytes that each access uses, which makes it cheaper than an +/// _unvalidated_ instance for reading a few values, such as one path per row of a column. +/// /// A _validated_ variant value guarantees that the associated [metadata] and all nested [object] /// and [array] values are _valid_. Primitive variant subtypes are always _valid_ by construction. /// @@ -381,7 +385,7 @@ impl<'m, 'v> Variant<'m, 'v> { } // The actual constructor, which only performs shallow (constant-time) validation. - fn try_new_with_metadata_and_shallow_validation( + pub(crate) fn try_new_with_metadata_and_shallow_validation( metadata: VariantMetadata<'m>, value: &'v [u8], ) -> Result { diff --git a/parquet-variant/src/variant/list.rs b/parquet-variant/src/variant/list.rs index c125cf39af20..e12567cb0cca 100644 --- a/parquet-variant/src/variant/list.rs +++ b/parquet-variant/src/variant/list.rs @@ -3,9 +3,8 @@ // SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements 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, -}; +use crate::utils::{slice_from_slice, slice_from_slice_at_offset}; +use crate::variant::view::VariantListView; use crate::variant::{MAX_NESTING_DEPTH, Variant, VariantMetadata}; use arrow_schema::ArrowError; @@ -14,7 +13,7 @@ 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, @@ -22,18 +21,25 @@ pub(crate) struct VariantListHeader { impl VariantListHeader { // Hide the ugly casting - const fn num_elements_size(&self) -> u32 { + pub(crate) const fn num_elements_size(&self) -> u32 { self.num_elements_size as _ } - const fn offset_size(&self) -> u32 { + pub(crate) const fn offset_size(&self) -> u32 { self.offset_size as _ } + pub(crate) const fn num_elements_size_bytes(&self) -> OffsetSizeBytes { + self.num_elements_size + } + pub(crate) const fn offset_size_bytes(&self) -> OffsetSizeBytes { + self.offset_size + } // Avoid materializing this offset, since it's cheaply and safely computable - const fn first_offset_byte(&self) -> u32 { + pub(crate) const fn first_offset_byte(&self) -> u32 { NUM_HEADER_BYTES + self.num_elements_size() } + #[inline] pub(crate) fn try_new(header_byte: u8) -> Result { // The 6 first bits to the left are the value_header and the 2 bits // to the right are the basic type, so we shift to get only the value_header @@ -153,33 +159,17 @@ impl<'m, 'v> VariantList<'m, 'v> { metadata: VariantMetadata<'m>, value: &'v [u8], ) -> Result { - let header_byte = first_byte_from_slice(value)?; - let header = VariantListHeader::try_new(header_byte)?; - - // Skip the header byte to read the num_elements; the offset array immediately follows - let num_elements = - header - .num_elements_size - .unpack_u32_at_offset(value, NUM_HEADER_BYTES as _, 0)?; - - // (num_elements + 1) * offset_size + first_offset_byte - let first_value_byte = num_elements - .checked_add(1) - .and_then(|n| n.checked_mul(header.offset_size())) - .and_then(|n| n.checked_add(header.first_offset_byte())) - .ok_or_else(|| overflow_error("offset of variant list values"))?; - - let mut new_self = Self { - metadata, - value, - header, - num_elements, - first_value_byte, - validated: false, - }; + VariantListView::try_new(metadata.view(), value)?.try_into_list(metadata) + } - // Validate just the first and last offset, ignoring the other offsets and all value bytes. - let first_offset = new_self.get_offset(0)?; + // Promotes a view by validating just the first and last offset, ignoring the other offsets + // and all value bytes. + #[inline] + pub(crate) fn try_from_view( + view: VariantListView<'m, 'v>, + metadata: VariantMetadata<'m>, + ) -> Result { + let first_offset = view.read_offset(0)?; if first_offset != 0 { return Err(ArrowError::InvalidArgumentError(format!( "First offset is not zero: {first_offset}" @@ -187,12 +177,27 @@ impl<'m, 'v> VariantList<'m, 'v> { } // Use the last offset to upper-bound the value buffer - let last_offset = new_self - .get_offset(num_elements as _)? - .checked_add(first_value_byte) - .ok_or_else(|| overflow_error("variant array size"))?; - new_self.value = slice_from_slice(value, ..last_offset as _)?; - Ok(new_self) + let last_offset = view.byte_len()?; + Ok(Self { + metadata, + value: slice_from_slice(view.value, ..last_offset)?, + header: view.header, + num_elements: view.num_elements, + first_value_byte: view.first_value_byte, + validated: false, + }) + } + + /// A view of this list, which reads only the elements it is asked for. + #[inline] + pub fn view(&self) -> VariantListView<'m, 'v> { + VariantListView { + metadata: self.metadata.view(), + value: self.value, + header: self.header, + num_elements: self.num_elements, + first_value_byte: self.first_value_byte, + } } /// True if this instance is fully [validated] for panic-free infallible accesses. @@ -288,9 +293,24 @@ impl<'m, 'v> VariantList<'m, 'v> { // Fallible version of `get`, performing only basic (constant-time) validation. fn try_get_with_shallow_validation(&self, index: usize) -> Result, ArrowError> { + if index >= self.len() { + return Err(ArrowError::InvalidArgumentError(format!( + "Variant list index {index} is out of bounds for length {}", + self.len() + ))); + } + self.element(&self.view(), index) + } + + // Reads element `index`, which the caller has bounded by `self.len()`, through `view`. + fn element( + &self, + view: &VariantListView<'m, 'v>, + index: usize, + ) -> Result, ArrowError> { // Fetch the value bytes between the two offsets for this index, from the value array region // of the byte buffer - let byte_range = self.get_offset(index)? as _..self.get_offset(index + 1)? as _; + let byte_range = view.read_offset(index)? as _..view.read_offset(index + 1)? as _; let value_bytes = slice_from_slice_at_offset(self.value, self.first_value_byte as _, byte_range)?; Variant::try_new_with_metadata_and_shallow_validation(self.metadata.clone(), value_bytes) @@ -321,16 +341,9 @@ impl<'m, 'v> VariantList<'m, 'v> { fn iter_try_with_shallow_validation( &self, ) -> impl Iterator, ArrowError>> + '_ { - (0..self.len()).map(|i| self.try_get_with_shallow_validation(i)) - } - - // Attempts to retrieve the ith offset from the offset array region of the byte buffer. - fn get_offset(&self, index: usize) -> Result { - let byte_range = self.header.first_offset_byte() as _..self.first_value_byte as _; - let offset_bytes = slice_from_slice(self.value, byte_range)?; - self.header - .offset_size - .unpack_u32_at_offset(offset_bytes, 0, index) + // One view serves every element, and the range bounds each element index. + let view = self.view(); + (0..self.len()).map(move |i| self.element(&view, i)) } } diff --git a/parquet-variant/src/variant/metadata.rs b/parquet-variant/src/variant/metadata.rs index 0974318e8a93..2693399bcb9d 100644 --- a/parquet-variant/src/variant/metadata.rs +++ b/parquet-variant/src/variant/metadata.rs @@ -4,9 +4,9 @@ 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; @@ -32,12 +32,18 @@ const NUM_HEADER_BYTES: u32 = 1; impl VariantMetadataHeader { // Hide the cast - const fn offset_size(&self) -> u32 { + pub(crate) const fn offset_size(&self) -> u32 { self.offset_size as u32 } + pub(crate) const fn offset_size_bytes(&self) -> OffsetSizeBytes { + self.offset_size + } + pub(crate) const fn is_sorted(&self) -> bool { + self.is_sorted + } // Avoid materializing this offset, since it's cheaply and safely computable - const fn first_offset_byte(&self) -> u32 { + pub(crate) const fn first_offset_byte(&self) -> u32 { NUM_HEADER_BYTES + self.offset_size() } @@ -57,6 +63,7 @@ impl VariantMetadataHeader { /// - sorted_strings is a 1-bit value indicating whether dictionary strings are sorted and unique. /// - offset_size_minus_one is a 2-bit value providing the number of bytes per dictionary size and offset field. /// - The actual number of bytes, offset_size, is offset_size_minus_one + 1 + #[inline] pub(crate) fn try_new(header_byte: u8) -> Result { let version = header_byte & 0x0F; // First four bits if version != VARIANT_SPEC_VERSION { @@ -199,35 +206,14 @@ impl<'m> VariantMetadata<'m> { // The actual constructor, which performs only basic (constant-const) validation. pub(crate) fn try_new_with_shallow_validation(bytes: &'m [u8]) -> Result { - let header_byte = first_byte_from_slice(bytes)?; - let header = VariantMetadataHeader::try_new(header_byte)?; - - // First element after header is dictionary size; the offset array immediately follows. - let dictionary_size = - header - .offset_size - .unpack_u32_at_offset(bytes, NUM_HEADER_BYTES as usize, 0)?; - - // Calculate the starting offset of the dictionary string bytes. - // - // There are dict_size + 1 offsets, and the value bytes immediately follow - // = (dict_size + 1) * offset_size + header.first_offset_byte() - let first_value_byte = dictionary_size - .checked_add(1) - .and_then(|n| n.checked_mul(header.offset_size())) - .and_then(|n| n.checked_add(header.first_offset_byte())) - .ok_or_else(|| overflow_error("offset of variant metadata dictionary"))?; - - let mut new_self = Self { - bytes, - header, - dictionary_size, - first_value_byte, - validated: false, - }; + VariantMetadataView::try_new(bytes)?.try_into_metadata() + } - // Validate just the first and last offset, ignoring the other offsets and all value bytes. - let first_offset = new_self.get_offset(0)?; + // Promotes a view by validating just the first and last offset, ignoring the other offsets + // and all value bytes. + #[inline] + pub(crate) fn try_from_view(view: VariantMetadataView<'m>) -> Result { + let first_offset = view.offset(0)?; if first_offset != 0 { return Err(ArrowError::InvalidArgumentError(format!( "First offset is not zero: {first_offset}" @@ -235,12 +221,28 @@ impl<'m> VariantMetadata<'m> { } // Use the last offset to upper-bound the byte slice - let last_offset = new_self - .get_offset(dictionary_size as _)? - .checked_add(first_value_byte) + let last_offset = view + .offset(view.len())? + .checked_add(view.first_value_byte) .ok_or_else(|| overflow_error("variant metadata size"))?; - new_self.bytes = slice_from_slice(bytes, ..last_offset as _)?; - Ok(new_self) + Ok(Self { + bytes: slice_from_slice(view.bytes, ..last_offset as _)?, + header: view.header, + dictionary_size: view.dictionary_size, + first_value_byte: view.first_value_byte, + validated: false, + }) + } + + /// A view of this dictionary, which reads only the entries it is asked for. + #[inline] + pub fn view(&self) -> VariantMetadataView<'m> { + VariantMetadataView { + bytes: self.bytes, + header: self.header, + dictionary_size: self.dictionary_size, + first_value_byte: self.first_value_byte, + } } /// The number of metadata dictionary entries @@ -334,16 +336,6 @@ impl<'m> VariantMetadata<'m> { self.header.version } - /// Gets an offset into the dictionary entry by index. - /// - /// This offset is an index into the dictionary, at the boundary between string `i-1` and string - /// `i`. See [`Self::get`] to retrieve a specific dictionary entry. - fn get_offset(&self, i: usize) -> Result { - let offset_byte_range = self.header.first_offset_byte() as _..self.first_value_byte as _; - let bytes = slice_from_slice(self.bytes, offset_byte_range)?; - self.header.offset_size.unpack_u32_at_offset(bytes, 0, i) - } - /// Returns the total size, in bytes, of the metadata. /// /// Note this value may be smaller than what was passed to [`Self::new`] or @@ -358,16 +350,13 @@ impl<'m> VariantMetadata<'m> { /// /// [invalid]: Self#Validation pub fn get(&self, i: usize) -> Result<&'m str, ArrowError> { - let byte_range = self.get_offset(i)? as _..self.get_offset(i + 1)? as _; + let value_bytes = self.view().entry(i)?; if !self.validated { - return string_from_slice(self.bytes, self.first_value_byte as _, byte_range); + return str_from_bytes(value_bytes); } // Full validation already proved every dictionary entry is valid UTF-8, so validating // again here would charge that cost once per field access instead of once per buffer. - let value_bytes = - slice_from_slice_at_offset(self.bytes, self.first_value_byte as _, byte_range)?; - debug_assert!(std::str::from_utf8(value_bytes).is_ok()); // SAFETY: `validated` is set only by `with_full_validation`, which proved that every @@ -439,14 +428,11 @@ impl<'m> VariantMetadata<'m> { let offsets = slice_from_slice(self.bytes, offset_byte_range).ok()?; let offset_size = self.header.offset_size; let cmp = |i| { - Some( - offset_size - .unpack_u32_at_offset(offsets, 0, i) - .ok()? - .cmp(&field_name_offset), - ) + Ok(offset_size + .unpack_u32_at_offset(offsets, 0, i)? + .cmp(&field_name_offset)) }; - let field_id = try_binary_search_range_by(0..self.len(), cmp)?.ok()?; + let field_id = try_binary_search_range_by(0..self.len(), cmp).ok()??; // Verify that this entry has exactly `field_name`'s bytes; see "Correctness" above. let entry_end = offset_size @@ -472,15 +458,11 @@ impl<'m> VariantMetadata<'m> { return Some((field_id, self.get_impl(field_id as _))); } - let field_id = if self.is_sorted() && self.len() > 10 { - // Binary search is faster for a not-tiny sorted metadata dictionary - let cmp = |i| Some(self.get_impl(i).cmp(field_name)); - try_binary_search_range_by(0..self.len(), cmp)?.ok()? - } else { - // Fall back to Linear search for tiny or unsorted dictionary - (0..self.len()).find(|i| self.get_impl(*i) == field_name)? - }; - Some((field_id as u32, self.get_impl(field_id))) + let field_id = self + .view() + .find(field_name.as_bytes()) + .expect("Invalid metadata dictionary entry")?; + Some((field_id, self.get_impl(field_id as _))) } /// Returns an iterator that attempts to visit all dictionary entries, producing `Err` if the @@ -549,11 +531,11 @@ mod tests { assert_eq!(&md[1], "dog"); // Offsets - assert_eq!(md.get_offset(0).unwrap(), 0x00); - assert_eq!(md.get_offset(1).unwrap(), 0x03); - assert_eq!(md.get_offset(2).unwrap(), 0x06); + assert_eq!(md.view().offset(0).unwrap(), 0x00); + assert_eq!(md.view().offset(1).unwrap(), 0x03); + assert_eq!(md.view().offset(2).unwrap(), 0x06); - let err = md.get_offset(3).unwrap_err(); + let err = md.get(2).unwrap_err(); assert!( matches!(err, ArrowError::InvalidArgumentError(_)), "unexpected error: {err:?}" diff --git a/parquet-variant/src/variant/object.rs b/parquet-variant/src/variant/object.rs index ba1e9eab8a95..08805c426e8b 100644 --- a/parquet-variant/src/variant/object.rs +++ b/parquet-variant/src/variant/object.rs @@ -3,9 +3,8 @@ // SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements use crate::decoder::{OffsetSizeBytes, map_bytes_to_offsets}; -use crate::utils::{ - first_byte_from_slice, overflow_error, slice_from_slice, try_binary_search_range_by, -}; +use crate::utils::slice_from_slice; +use crate::variant::view::VariantObjectView; use crate::variant::{MAX_NESTING_DEPTH, Variant, VariantMetadata}; use arrow_schema::ArrowError; @@ -14,45 +13,57 @@ use arrow_schema::ArrowError; const NUM_HEADER_BYTES: u32 = 1; /// Header structure for [`VariantObject`] -#[derive(Debug, Clone, PartialEq)] -pub(crate) struct VariantObjectHeader { - num_elements_size: OffsetSizeBytes, - field_id_size: OffsetSizeBytes, - field_offset_size: OffsetSizeBytes, +/// +/// Holds the `value_header` bits of the header byte. Views copy the header, and copying one byte +/// is cheaper than copying the three decoded sizes. +#[derive(Clone, Copy, PartialEq)] +pub(crate) struct VariantObjectHeader(u8); + +impl std::fmt::Debug for VariantObjectHeader { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("VariantObjectHeader") + .field("num_elements_size", &self.num_elements_size_bytes()) + .field("field_id_size", &self.field_id_size_bytes()) + .field("field_offset_size", &self.field_offset_size_bytes()) + .finish() + } } impl VariantObjectHeader { // Hide the ugly casting - const fn num_elements_size(&self) -> u32 { - self.num_elements_size as _ + pub(crate) const fn num_elements_size(&self) -> u32 { + self.num_elements_size_bytes() as _ + } + pub(crate) const fn field_id_size(&self) -> u32 { + self.field_id_size_bytes() as _ + } + pub(crate) const fn field_offset_size(&self) -> u32 { + self.field_offset_size_bytes() as _ + } + #[inline] + pub(crate) const fn num_elements_size_bytes(&self) -> OffsetSizeBytes { + match self.0 & 0x10 != 0 { + true => OffsetSizeBytes::Four, + false => OffsetSizeBytes::One, + } } - const fn field_id_size(&self) -> u32 { - self.field_id_size as _ + #[inline] + pub(crate) const fn field_id_size_bytes(&self) -> OffsetSizeBytes { + OffsetSizeBytes::from_bits(self.0 >> 2) } - const fn field_offset_size(&self) -> u32 { - self.field_offset_size as _ + #[inline] + pub(crate) const fn field_offset_size_bytes(&self) -> OffsetSizeBytes { + OffsetSizeBytes::from_bits(self.0) } // Avoid materializing this offset, since it's cheaply and safely computable - const fn field_ids_start_byte(&self) -> u32 { + pub(crate) const fn field_ids_start_byte(&self) -> u32 { NUM_HEADER_BYTES + self.num_elements_size() } - pub(crate) fn try_new(header_byte: u8) -> Result { - // Parse the header byte to get object parameters - let value_header = header_byte >> 2; - let field_offset_size_minus_one = value_header & 0x03; // Last 2 bits - let field_id_size_minus_one = (value_header >> 2) & 0x03; // Next 2 bits - let is_large = (value_header & 0x10) != 0; // 5th bit - let num_elements_size = match is_large { - true => OffsetSizeBytes::Four, - false => OffsetSizeBytes::One, - }; - Ok(Self { - num_elements_size, - field_id_size: OffsetSizeBytes::try_new(field_id_size_minus_one)?, - field_offset_size: OffsetSizeBytes::try_new(field_offset_size_minus_one)?, - }) + #[inline] + pub(crate) const fn new(header_byte: u8) -> Self { + Self(header_byte >> 2) } } @@ -153,48 +164,42 @@ impl<'m, 'v> VariantObject<'m, 'v> { metadata: VariantMetadata<'m>, value: &'v [u8], ) -> Result { - let header_byte = first_byte_from_slice(value)?; - let header = VariantObjectHeader::try_new(header_byte)?; - - // Determine num_elements size based on is_large flag and fetch the value - let num_elements = - header - .num_elements_size - .unpack_u32_at_offset(value, NUM_HEADER_BYTES as _, 0)?; - - // Calculate byte offsets for field offsets and values with overflow protection, and verify - // they're in bounds - let first_field_offset_byte = num_elements - .checked_mul(header.field_id_size()) - .and_then(|n| n.checked_add(header.field_ids_start_byte())) - .ok_or_else(|| overflow_error("offset of variant object field offsets"))?; - - let first_value_byte = 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)) - .ok_or_else(|| overflow_error("offset of variant object field values"))?; - - let mut new_self = Self { - metadata, - value, - header, - num_elements, - first_field_offset_byte, - first_value_byte, - validated: false, - }; + VariantObjectView::try_new(metadata.view(), value)?.try_into_object(metadata) + } + // Promotes a view by validating just the last field offset. + #[inline] + pub(crate) fn try_from_view( + view: VariantObjectView<'m, 'v>, + metadata: VariantMetadata<'m>, + ) -> Result { // Spec says: "The last field_offset points to the byte after the end of the last value" // // Use it to upper-bound the value bytes, which also verifies that the field id and field // offset arrays are in bounds. - let last_offset = new_self - .get_offset(num_elements as _)? - .checked_add(first_value_byte) - .ok_or_else(|| overflow_error("variant object size"))?; - new_self.value = slice_from_slice(value, ..last_offset as _)?; - Ok(new_self) + let last_offset = view.byte_len()?; + Ok(Self { + metadata, + value: slice_from_slice(view.value, ..last_offset)?, + header: view.header, + num_elements: view.num_elements, + first_field_offset_byte: view.first_field_offset_byte, + first_value_byte: view.first_value_byte, + validated: false, + }) + } + + /// A view of this object, which reads only the fields it is asked for. + #[inline] + pub fn view(&self) -> VariantObjectView<'m, 'v> { + VariantObjectView { + metadata: self.metadata.view(), + value: self.value, + header: self.header, + num_elements: self.num_elements, + first_field_offset_byte: self.first_field_offset_byte, + first_value_byte: self.first_value_byte, + } } /// True if this instance is fully [validated] for panic-free infallible accesses. @@ -235,7 +240,7 @@ impl<'m, 'v> VariantObject<'m, 'v> { )?; let mut field_ids_iter = - map_bytes_to_offsets(field_id_buffer, self.header.field_id_size); + map_bytes_to_offsets(field_id_buffer, self.header.field_id_size_bytes()); // Validate all field ids exist in the metadata dictionary and the corresponding field names are lexicographically sorted if self.metadata.is_sorted() { @@ -300,7 +305,7 @@ impl<'m, 'v> VariantObject<'m, 'v> { let value_buffer = slice_from_slice(self.value, self.first_value_byte as _..)?; - map_bytes_to_offsets(field_offset_buffer, self.header.field_offset_size) + map_bytes_to_offsets(field_offset_buffer, self.header.field_offset_size_bytes()) .take(num_offsets.saturating_sub(1)) .try_for_each(|offset| { let value_bytes = slice_from_slice(value_buffer, offset..)?; @@ -351,21 +356,11 @@ impl<'m, 'v> VariantObject<'m, 'v> { // Attempts to retrieve the ith field value from the value region of the byte buffer; it // performs only basic (constant-cost) validation. fn try_field_with_shallow_validation(&self, i: usize) -> Result, ArrowError> { - let value_bytes = slice_from_slice(self.value, self.first_value_byte as _..)?; - let value_bytes = slice_from_slice(value_bytes, self.get_offset(i)? as _..)?; - Variant::try_new_with_metadata_and_shallow_validation(self.metadata.clone(), value_bytes) + let value = self.view().field_bytes(i)?; + Variant::try_new_with_metadata_and_shallow_validation(self.metadata.clone(), value) .map(|child| child.inherit_validation(self.validated)) } - // Attempts to retrieve the ith offset from the field offset region of the byte buffer. - fn get_offset(&self, i: usize) -> Result { - let byte_range = self.first_field_offset_byte as _..self.first_value_byte as _; - let field_offsets = slice_from_slice(self.value, byte_range)?; - self.header - .field_offset_size - .unpack_u32_at_offset(field_offsets, 0, i) - } - /// Get a field's name by index in `0..self.len()` /// /// # Panics @@ -380,13 +375,7 @@ impl<'m, 'v> VariantObject<'m, 'v> { /// Fallible version of `field_name`. Returns field name by index, capturing validation errors fn try_field_name(&self, i: usize) -> Result<&'m str, ArrowError> { - let byte_range = self.header.field_ids_start_byte() as _..self.first_field_offset_byte as _; - let field_id_bytes = slice_from_slice(self.value, byte_range)?; - let field_id = self - .header - .field_id_size - .unpack_u32_at_offset(field_id_bytes, 0, i)?; - self.metadata.get(field_id as _) + self.metadata.get(self.view().field_id(i)? as _) } /// Returns an iterator of (name, value) pairs over the fields of this object. @@ -395,8 +384,12 @@ impl<'m, 'v> VariantObject<'m, 'v> { /// /// Panics if this object is invalid. Use [`Self::iter_try`] for a fallible version. pub fn iter(&self) -> impl Iterator)> + '_ { - self.iter_try_with_shallow_validation() - .map(|result| result.expect("Invalid variant object field value")) + // One view serves every field, and the range bounds each field index. + let view = self.view(); + (0..self.len()).map(move |i| { + self.read_name_and_field(&view, i) + .expect("Invalid variant object field value") + }) } /// Fallible iteration over the fields of this object. @@ -409,8 +402,26 @@ impl<'m, 'v> VariantObject<'m, 'v> { }) } + // Reads field `i`, which the caller has bounded by `self.len()`, through `view`. + #[inline] + fn read_name_and_field( + &self, + view: &VariantObjectView<'m, 'v>, + i: usize, + ) -> Result<(&'m str, Variant<'m, 'v>), ArrowError> { + let field = Variant::try_new_with_metadata_and_shallow_validation( + self.metadata.clone(), + view.read_field_bytes(i)?, + )? + .inherit_validation(self.validated); + Ok((self.metadata.get(view.read_field_id(i)? as _)?, field)) + } + // Fallible iteration over the fields of this object that performs only shallow (constant-cost) // validation of field values. + // + // Unlike `iter`, this calls the out-of-line field accessors. That keeps `next` small enough to + // inline into callers of `iter_try`, such as the builder, which also validate each field. fn iter_try_with_shallow_validation( &self, ) -> impl Iterator), ArrowError>> + '_ { @@ -424,13 +435,13 @@ impl<'m, 'v> VariantObject<'m, 'v> { /// /// Returns `Some(Variant)` if the field exists, or `None` if the field does not exist. pub fn get(&self, name: &str) -> Option> { - // 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()) + .expect("Invalid variant object field name")?; self.field(i) } } @@ -717,9 +728,11 @@ mod tests { Variant::Int32(count - 1) ); assert_eq!( - obj.header.field_id_size, expected_field_id_size, + obj.header.field_id_size_bytes(), + expected_field_id_size, "Expected {}-byte field IDs, got {}-byte field IDs", - expected_field_id_size as usize, obj.header.field_id_size as usize + expected_field_id_size as usize, + obj.header.field_id_size() as usize ); } else { panic!("Expected object variant"); @@ -772,9 +785,11 @@ mod tests { if let Variant::Object(obj) = variant { assert_eq!(obj.len(), num_fields); assert_eq!( - obj.header.field_offset_size, expected_field_offset_size, + obj.header.field_offset_size_bytes(), + expected_field_offset_size, "Expected {}-byte field offsets, got {}-byte field offsets", - expected_field_offset_size as usize, obj.header.field_offset_size as usize + expected_field_offset_size as usize, + obj.header.field_offset_size() as usize ); } else { panic!("Expected object variant"); diff --git a/parquet-variant/src/variant/view.rs b/parquet-variant/src/variant/view.rs new file mode 100644 index 000000000000..8dc9fc9c736b --- /dev/null +++ b/parquet-variant/src/variant/view.rs @@ -0,0 +1,783 @@ +// 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_range_by, +}; +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, what: &str) -> Result { + 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 { + let header = VariantMetadataHeader::try_new(first_byte_from_slice(bytes)?)?; + let dictionary_size = + header + .offset_size_bytes() + .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, ArrowError> { + if self.is_sorted() && self.len() > 10 { + let found = + try_binary_search_range_by(0..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) + } + + /// Attempts to interpret this view as an [unvalidated](VariantMetadata#validation) + /// [`VariantMetadata`], which checks the first and last offsets. + #[inline] + pub fn try_into_metadata(self) -> Result, 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 { + self.header.offset_size_bytes().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. +/// +/// Views such as [`VariantView`], [`VariantMetadataView`], [`VariantObjectView`] and +/// [`VariantListView`] do the minimum parsing work needed, and defer as much validation as possible +/// to when a value is accessed. Each accessor bounds-checks only the bytes that it reads, and returns +/// an error on malformed input instead of panicking. Field names are compared as bytes, which orders +/// them as `str` does, so a search does not check UTF-8. 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. [`Self::try_to_variant`] and the +/// `try_into_*` methods of the other views convert a view to these types. +/// +/// # 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.try_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 { + 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>, 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>, 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, 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, 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 try_to_variant(&self) -> Result, ArrowError> { + let metadata = match self.basic_type() { + VariantBasicType::Object | VariantBasicType::Array => { + self.metadata.try_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 { + let header = VariantObjectHeader::new(first_byte_from_slice(value)?); + let num_elements = header.num_elements_size_bytes().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`. + #[inline] + pub fn field_id(&self, i: usize) -> Result { + 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, ArrowError> { + self.check_index(i)?; + self.read_field(i) + } + + // The bytes from the start of field `i`'s value to the end of the object, without the + // throwaway view that `field` would build. + #[inline] + pub(crate) fn field_bytes(&self, i: usize) -> Result<&'v [u8], ArrowError> { + self.check_index(i)?; + self.read_field_bytes(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, ArrowError> { + try_binary_search_range_by(0..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>, 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 { + let end = checked( + self.read_offset(self.len())? + .checked_add(self.first_value_byte), + "variant object size", + )?; + Ok(end as _) + } + + /// Attempts to interpret this view and `metadata` as an [unvalidated](VariantObject#validation) + /// [`VariantObject`], which checks the last field offset. + #[inline] + pub fn try_into_object( + self, + metadata: VariantMetadata<'m>, + ) -> Result, 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 { + self.header.field_id_size_bytes().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 { + self.header.field_offset_size_bytes().unpack_u32_at_offset( + self.value, + self.first_field_offset_byte as _, + i, + ) + } + + #[inline] + pub(crate) fn read_field(&self, i: usize) -> Result, ArrowError> { + VariantView::try_new(self.metadata, self.read_field_bytes(i)?) + } + + #[inline] + pub(crate) fn read_field_bytes(&self, i: usize) -> Result<&'v [u8], ArrowError> { + let start = checked( + self.read_offset(i)?.checked_add(self.first_value_byte), + "variant object field start", + )?; + 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 { + let header = VariantListHeader::try_new(first_byte_from_slice(value)?)?; + let num_elements = header.num_elements_size_bytes().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>, 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 { + let end = checked( + self.read_offset(self.len())? + .checked_add(self.first_value_byte), + "variant array size", + )?; + Ok(end as _) + } + + /// Attempts to interpret this view and `metadata` as an [unvalidated](VariantList#validation) + /// [`VariantList`], which checks the first and last offsets. + #[inline] + pub fn try_into_list( + self, + metadata: VariantMetadata<'m>, + ) -> Result, ArrowError> { + VariantList::try_from_view(self, metadata) + } + + /// Entry `i` of the offset array, for `i` in `0..=self.len()`. + #[inline] + pub(crate) fn read_offset(&self, i: usize) -> Result { + self.header.offset_size_bytes().unpack_u32_at_offset( + self.value, + self.header.first_offset_byte() as _, + i, + ) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::VariantBuilder; + + const LONG_STRING: &str = + "a string that is longer than the sixty-three bytes that a short string can hold"; + + /// `{"a": 1, "b": "short", "list": [1, "two", {"x": true}], "nested": {"k": LONG_STRING}}` + fn sample() -> (Vec, Vec) { + let mut builder = VariantBuilder::new(); + let mut object = builder.new_object(); + object.insert("a", 1i8); + object.insert("b", "short"); + let mut list = object.new_list("list"); + list.append_value(1i8); + list.append_value("two"); + list.new_object().with_field("x", true).finish(); + list.finish(); + object + .new_object("nested") + .with_field("k", LONG_STRING) + .finish(); + object.finish(); + builder.finish() + } + + fn view<'a>(metadata: &'a [u8], value: &'a [u8]) -> VariantView<'a, 'a> { + VariantView::try_new(VariantMetadataView::try_new(metadata).unwrap(), value).unwrap() + } + + fn metadata_with_names(names: &[&str]) -> Vec { + let mut builder = VariantBuilder::new().with_field_names(names.iter().copied()); + builder.append_value(1i8); + builder.finish().0 + } + + fn assert_metadata_view_matches(bytes: &[u8]) { + let metadata = VariantMetadata::try_new(bytes).unwrap(); + let view = VariantMetadataView::try_new(bytes).unwrap(); + assert_eq!(view.len(), metadata.len()); + assert_eq!(view.is_empty(), metadata.is_empty()); + assert_eq!(view.is_sorted(), metadata.is_sorted()); + for id in 0..metadata.len() { + let name = metadata.get(id).unwrap(); + assert_eq!(view.entry(id).unwrap(), name.as_bytes()); + assert_eq!(view.entry_str(id).unwrap(), name); + assert_eq!(view.find(name.as_bytes()).unwrap(), Some(id as u32)); + } + assert_eq!(view.find(b"no such name").unwrap(), None); + assert!(view.entry(view.len()).is_err()); + assert!(view.entry_str(view.len()).is_err()); + // Promotion gives the unvalidated form. + assert_eq!( + view.try_into_metadata().unwrap(), + VariantMetadata::new(bytes) + ); + } + + #[test] + fn test_metadata_view_sorted() { + // More than 10 entries, so `find` uses its binary search. + let names: Vec = (0..64).map(|i| format!("field_{i:03}")).collect(); + let names: Vec<&str> = names.iter().map(String::as_str).collect(); + let bytes = metadata_with_names(&names); + assert!(VariantMetadataView::try_new(&bytes).unwrap().is_sorted()); + assert_metadata_view_matches(&bytes); + } + + #[test] + fn test_metadata_view_unsorted() { + let bytes = metadata_with_names(&["zebra", "apple", "mango", "kiwi"]); + assert!(!VariantMetadataView::try_new(&bytes).unwrap().is_sorted()); + assert_metadata_view_matches(&bytes); + } + + #[test] + fn test_metadata_view_empty() { + let view = VariantMetadataView::try_new(crate::EMPTY_VARIANT_METADATA_BYTES).unwrap(); + assert!(view.is_empty()); + assert_eq!(view.find(b"a").unwrap(), None); + assert!(view.entry(0).is_err()); + } + + #[test] + fn test_metadata_view_entry_is_not_utf8_validated() { + // Dictionary with one entry, the invalid UTF-8 byte 0xFF. + let bytes = [0b0000_0001, 1, 0, 1, 0xFF]; + let view = VariantMetadataView::try_new(&bytes).unwrap(); + assert_eq!(view.entry(0).unwrap(), &[0xFF]); + assert_eq!(view.find(&[0xFF]).unwrap(), Some(0)); + assert!(view.entry_str(0).is_err()); + } + + #[test] + fn test_object_view_matches_object() { + let (metadata, value) = sample(); + let variant = Variant::try_new(&metadata, &value).unwrap(); + let object = variant.as_object().unwrap(); + let root = view(&metadata, &value); + let object_view = root.as_object().unwrap().unwrap(); + + assert_eq!(object_view.len(), object.len()); + assert!(!object_view.is_empty()); + for i in 0..object.len() { + let name = object.field_name(i).unwrap(); + assert_eq!(object_view.field_name(i).unwrap(), name.as_bytes()); + let field_id = object_view.field_id(i).unwrap(); + assert_eq!(root.metadata().entry_str(field_id as _).unwrap(), name); + assert_eq!( + object_view.field(i).unwrap().try_to_variant().unwrap(), + object.field(i).unwrap() + ); + assert_eq!(object_view.find(name.as_bytes()).unwrap(), Some(i)); + let found = object_view.get(name.as_bytes()).unwrap().unwrap(); + assert_eq!(found.try_to_variant().unwrap(), object.get(name).unwrap()); + } + + assert_eq!(object_view.find(b"missing").unwrap(), None); + assert!(object_view.get(b"missing").unwrap().is_none()); + assert!(object_view.field(object.len()).is_err()); + assert!(object_view.field_id(object.len()).is_err()); + assert!(object_view.field_name(object.len()).is_err()); + + assert_eq!(object_view.byte_len().unwrap(), value.len()); + let metadata = root.metadata().try_into_metadata().unwrap(); + assert_eq!(&object_view.try_into_object(metadata).unwrap(), object); + } + + #[test] + fn test_list_view_matches_list() { + let (metadata, value) = sample(); + let variant = Variant::try_new(&metadata, &value).unwrap(); + let variant = variant.get_object_field("list").unwrap(); + let list = variant.as_list().unwrap(); + let element = view(&metadata, &value).get_field(b"list").unwrap().unwrap(); + let list_view = element.as_list().unwrap().unwrap(); + + assert_eq!(list_view.len(), list.len()); + assert!(!list_view.is_empty()); + for i in 0..list.len() { + let found = list_view.get(i).unwrap().unwrap(); + assert_eq!(found.try_to_variant().unwrap(), list.get(i).unwrap()); + } + assert!(list_view.get(list.len()).unwrap().is_none()); + + let metadata = element.metadata().try_into_metadata().unwrap(); + assert_eq!(&list_view.try_into_list(metadata).unwrap(), list); + } + + #[test] + fn test_value_view_types() { + let (metadata, value) = sample(); + let root = view(&metadata, &value); + assert_eq!(root.basic_type(), VariantBasicType::Object); + assert!(root.as_object().unwrap().is_some()); + assert!(root.as_list().unwrap().is_none()); + assert!(root.get_index(0).unwrap().is_none()); + + let list = root.get_field(b"list").unwrap().unwrap(); + assert_eq!(list.basic_type(), VariantBasicType::Array); + assert!(list.as_list().unwrap().is_some()); + assert!(list.as_object().unwrap().is_none()); + assert!(list.get_field(b"a").unwrap().is_none()); + + let primitive = root.get_field(b"a").unwrap().unwrap(); + assert_eq!(primitive.basic_type(), VariantBasicType::Primitive); + assert!(primitive.as_object().unwrap().is_none()); + assert!(primitive.as_list().unwrap().is_none()); + + let short_string = root.get_field(b"b").unwrap().unwrap(); + assert_eq!(short_string.basic_type(), VariantBasicType::ShortString); + } + + /// Reads everything reachable from `value` through the views, ignoring errors. + fn walk(value: VariantView<'_, '_>) { + // Malformed input may declare more children than its bytes can hold. + const MAX_CHILDREN: usize = 64; + + let _ = value.try_to_variant(); + let metadata = value.metadata(); + for id in 0..metadata.len().min(MAX_CHILDREN) { + let _ = metadata.entry(id); + let _ = metadata.entry_str(id); + } + let _ = metadata.find(b"k"); + let _ = metadata.try_into_metadata(); + + if let Ok(Some(object)) = value.as_object() { + let _ = object.byte_len(); + let _ = object.find(b"k"); + let _ = object.get(b"k"); + for i in 0..object.len().min(MAX_CHILDREN) { + let _ = object.field_id(i); + let _ = object.field_name(i); + if let Ok(field) = object.field(i) { + walk(field); + } + } + if let Ok(metadata) = metadata.try_into_metadata() { + let _ = object.try_into_object(metadata); + } + } + if let Ok(Some(list)) = value.as_list() { + let _ = list.byte_len(); + for i in 0..list.len().min(MAX_CHILDREN) { + if let Ok(Some(element)) = list.get(i) { + walk(element); + } + } + if let Ok(metadata) = metadata.try_into_metadata() { + let _ = list.try_into_list(metadata); + } + } + } + + fn walk_bytes(metadata: &[u8], value: &[u8]) { + let Ok(metadata) = VariantMetadataView::try_new(metadata) else { + return; + }; + if let Ok(value) = VariantView::try_new(metadata, value) { + walk(value); + } + } + + #[test] + fn test_truncated_input_does_not_panic() { + let (metadata, value) = sample(); + for len in 0..metadata.len() { + walk_bytes(&metadata[..len], &value); + } + for len in 0..value.len() { + walk_bytes(&metadata, &value[..len]); + } + } + + #[test] + fn test_corrupt_input_does_not_panic() { + let (metadata, value) = sample(); + for corrupt in [0x00, 0x7F, 0xFF] { + for i in 0..metadata.len() { + let mut metadata = metadata.clone(); + metadata[i] = corrupt; + walk_bytes(&metadata, &value); + } + for i in 0..value.len() { + let mut value = value.clone(); + value[i] = corrupt; + walk_bytes(&metadata, &value); + } + } + } +}