Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions parquet-variant/src/builder/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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`].
Expand Down Expand Up @@ -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()
}
Expand Down
4 changes: 1 addition & 3 deletions parquet-variant/src/builder/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
12 changes: 12 additions & 0 deletions parquet-variant/src/decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions parquet-variant/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
//!
Expand Down
32 changes: 8 additions & 24 deletions parquet-variant/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ pub(crate) fn array_from_slice<const N: usize>(
.map_err(|e: TryFromSliceError| ArrowError::InvalidArgumentError(e.to_string()))
}

#[inline]
pub(crate) fn first_byte_from_slice(slice: &[u8]) -> Result<u8, ArrowError> {
slice
.first()
Expand Down Expand Up @@ -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<F>(
/// Returns the index for which `cmp` returns [`Ordering::Equal`], if any.
pub(crate) fn try_binary_search_range_by(
range: Range<usize>,
cmp: F,
) -> Option<Result<usize, usize>>
where
F: Fn(usize) -> Option<Ordering>,
{
cmp: impl Fn(usize) -> Result<Ordering, ArrowError>,
) -> Result<Option<usize>, 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.
Expand Down
12 changes: 8 additions & 4 deletions parquet-variant/src/variant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be nice to list VariantView here too:

Screenshot 2026-11-20 at 7 37 11 AM

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added VariantView to the main APIs in the crate docs in e913e33, and a paragraph on views to the validation section of the Variant docs.


// 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;
Expand All @@ -27,6 +27,7 @@ mod decimal;
mod list;
mod metadata;
mod object;
mod view;

const MAX_SHORT_STRING_BYTES: usize = 0x3F;

Expand Down Expand Up @@ -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.
///
Expand Down Expand Up @@ -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<Self, ArrowError> {
Expand Down
113 changes: 63 additions & 50 deletions parquet-variant/src/variant/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -14,26 +13,33 @@ 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,
}

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<Self, ArrowError> {
// 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
Expand Down Expand Up @@ -153,46 +159,45 @@ impl<'m, 'v> VariantList<'m, 'v> {
metadata: VariantMetadata<'m>,
value: &'v [u8],
) -> Result<Self, ArrowError> {
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<Self, ArrowError> {
let first_offset = view.read_offset(0)?;
if first_offset != 0 {
return Err(ArrowError::InvalidArgumentError(format!(
"First offset is not zero: {first_offset}"
)));
}

// 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.
Expand Down Expand Up @@ -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<Variant<'m, 'v>, 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<Variant<'m, 'v>, 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)
Expand Down Expand Up @@ -321,16 +341,9 @@ impl<'m, 'v> VariantList<'m, 'v> {
fn iter_try_with_shallow_validation(
&self,
) -> impl Iterator<Item = Result<Variant<'m, 'v>, 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<u32, ArrowError> {
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))
}
}

Expand Down
Loading