Skip to main content

parquet_variant/
utils.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17use std::{array::TryFromSliceError, ops::Range, str};
18
19use crate::VariantPathElement;
20use arrow_schema::ArrowError;
21
22use std::cmp::Ordering;
23use std::fmt::Debug;
24use std::slice::SliceIndex;
25
26/// Helper for reporting integer overflow errors in a consistent way.
27pub(crate) fn overflow_error(msg: &str) -> ArrowError {
28    ArrowError::InvalidArgumentError(format!("Integer overflow computing {msg}"))
29}
30
31#[inline]
32pub(crate) fn slice_from_slice<I: SliceIndex<[u8]> + Clone + Debug>(
33    bytes: &[u8],
34    index: I,
35) -> Result<&I::Output, ArrowError> {
36    bytes.get(index.clone()).ok_or_else(|| {
37        ArrowError::InvalidArgumentError(format!(
38            "Tried to extract byte(s) {index:?} from {}-byte buffer",
39            bytes.len(),
40        ))
41    })
42}
43
44/// Helper to safely slice bytes with offset calculations.
45///
46/// Equivalent to `slice_from_slice(bytes, (base_offset + range.start)..(base_offset + range.end))`
47/// but using checked addition to prevent integer overflow panics on 32-bit systems.
48#[inline]
49pub(crate) fn slice_from_slice_at_offset(
50    bytes: &[u8],
51    base_offset: usize,
52    range: Range<usize>,
53) -> Result<&[u8], ArrowError> {
54    let start_byte = base_offset
55        .checked_add(range.start)
56        .ok_or_else(|| overflow_error("slice start"))?;
57    let end_byte = base_offset
58        .checked_add(range.end)
59        .ok_or_else(|| overflow_error("slice end"))?;
60    slice_from_slice(bytes, start_byte..end_byte)
61}
62
63pub(crate) fn array_from_slice<const N: usize>(
64    bytes: &[u8],
65    offset: usize,
66) -> Result<[u8; N], ArrowError> {
67    slice_from_slice_at_offset(bytes, offset, 0..N)?
68        .try_into()
69        .map_err(|e: TryFromSliceError| ArrowError::InvalidArgumentError(e.to_string()))
70}
71
72pub(crate) fn first_byte_from_slice(slice: &[u8]) -> Result<u8, ArrowError> {
73    slice
74        .first()
75        .copied()
76        .ok_or_else(|| ArrowError::InvalidArgumentError("Received empty bytes".to_string()))
77}
78
79/// Helper to get a &str from a slice at the given offset and range, or an error if it contains invalid UTF-8 data.
80#[inline]
81pub(crate) fn string_from_slice(
82    slice: &[u8],
83    offset: usize,
84    range: Range<usize>,
85) -> Result<&str, ArrowError> {
86    let offset_buffer = slice_from_slice_at_offset(slice, offset, range)?;
87
88    //Use simdutf8 by default
89    #[cfg(feature = "simdutf8")]
90    {
91        simdutf8::basic::from_utf8(offset_buffer).map_err(|_| {
92            // Use simdutf8::compat to return details about the decoding error
93            let e = simdutf8::compat::from_utf8(offset_buffer).unwrap_err();
94            ArrowError::InvalidArgumentError(format!("encountered non UTF-8 data: {e}"))
95        })
96    }
97
98    //Use std::str if simdutf8 is not enabled
99    #[cfg(not(feature = "simdutf8"))]
100    str::from_utf8(offset_buffer)
101        .map_err(|_| ArrowError::InvalidArgumentError("invalid UTF-8 string".to_string()))
102}
103
104/// Performs a binary search over a range using a fallible key extraction function; a failed key
105/// extraction immediately terminats the search.
106///
107/// This is similar to the standard library's `binary_search_by`, but generalized to ranges instead
108/// of slices.
109///
110/// # Arguments
111/// * `range` - The range to search in
112/// * `target` - The target value to search for
113/// * `key_extractor` - A function that extracts a comparable key from slice elements.
114///   This function can fail and return None.
115///
116/// # Returns
117/// * `Some(Ok(index))` - Element found at the given index
118/// * `Some(Err(index))` - Element not found, but would be inserted at the given index
119/// * `None` - Key extraction failed
120pub(crate) fn try_binary_search_range_by<F>(
121    range: Range<usize>,
122    cmp: F,
123) -> Option<Result<usize, usize>>
124where
125    F: Fn(usize) -> Option<Ordering>,
126{
127    let Range { mut start, mut end } = range;
128    while start < end {
129        let mid = start + (end - start) / 2;
130        match cmp(mid)? {
131            Ordering::Equal => return Some(Ok(mid)),
132            Ordering::Greater => end = mid,
133            Ordering::Less => start = mid + 1,
134        }
135    }
136
137    Some(Err(start))
138}
139
140/// Verifies the expected size of type T, for a type that should only grow if absolutely necessary.
141pub(crate) const fn expect_size_of<T>(expected: usize) {
142    let size = std::mem::size_of::<T>();
143    if size != expected {
144        let _ = [""; 0][size];
145    }
146}
147
148/// Parse a path string into a vector of [`VariantPathElement`].
149///
150/// # Syntax
151/// - `.field` or `field` - access object field (do not support special char)
152/// - `[index]` - access array element by index
153/// - `[field]` - access object field (support special char with escape `\`)
154///
155/// # Escape Rules
156/// Inside brackets `[...]`:
157/// - `\\` -> literal `\`
158/// - `\]` -> literal `]`
159/// - Any other `\x` -> literal `x`
160///
161/// Outside brackets, no escaping is supported.
162///
163/// # Examples
164/// - `""` -> empty path
165/// - `"foo"` -> single field `foo`
166/// - `"foo.bar"` -> nested fields `foo`, `bar`
167/// - `"[1]"` -> array index 1
168/// - `"['1']"` or `"["1"]"`-> field `1`
169/// - `"foo[1].bar"` -> field `foo`, index 1, field `bar`
170/// - `"['a.b']"` -> field `a.b` (dot is literal inside bracket)
171/// - `"['a\]b']"` -> field `a]b` (escaped `]`
172/// - etc.
173///
174/// # Errors
175/// - Leading `.` (e.g., `".foo"`)
176/// - Trailing `.` (e.g., `"foo."`)
177/// - Unclosed '[' (e.g., `"foo[1"`)
178/// - Unexpected ']' (e.g., `"foo]"`)
179/// - Trailing `\` inside bracket (treated as unclosed bracket)
180#[inline]
181pub(crate) fn parse_path(s: &str) -> Result<Vec<VariantPathElement<'_>>, ArrowError> {
182    let scan_field = |start: usize| {
183        s[start..]
184            .find(['.', '[', ']'])
185            .map_or_else(|| s.len(), |p| start + p)
186    };
187
188    let bytes = s.as_bytes();
189    if bytes.first() == Some(&b'.') {
190        return Err(ArrowError::ParseError("Unexpected leading '.'".into()));
191    }
192
193    let mut elements = Vec::new();
194    let mut i = 0;
195
196    while i < bytes.len() {
197        let (elem, end) = match bytes[i] {
198            b'.' => {
199                i += 1; // skip the dot; a field must follow
200                let end = scan_field(i);
201                if end == i {
202                    return Err(ArrowError::ParseError(match bytes.get(i) {
203                        None => "Unexpected trailing '.'".into(),
204                        Some(&c) => format!("Unexpected '{}' at byte {i}", c as char),
205                    }));
206                }
207                (VariantPathElement::field(&s[i..end]), end)
208            }
209            b'[' => {
210                let (element, end) = parse_in_bracket(s, i)?;
211                (element, end)
212            }
213            b']' => {
214                return Err(ArrowError::ParseError(format!(
215                    "Unexpected ']' at byte {i}"
216                )));
217            }
218            _ => {
219                let end = scan_field(i);
220                (VariantPathElement::field(&s[i..end]), end)
221            }
222        };
223        elements.push(elem);
224        i = end;
225    }
226
227    Ok(elements)
228}
229
230/// Parse `[digits | field]` starting at `i` (which points to `[`).
231/// Returns (VariantPathElement, position after `]`).
232fn parse_in_bracket(s: &str, i: usize) -> Result<(VariantPathElement<'_>, usize), ArrowError> {
233    let start = i + 1; // skip '['
234
235    let mut unescaped = String::new();
236    let mut chars = s[start..].char_indices();
237    let mut end = None;
238
239    while let Some((offset, c)) = chars.next() {
240        match c {
241            // Escape: take next char literally
242            '\\' => {
243                if let Some((_, next)) = chars.next() {
244                    unescaped.push(next);
245                }
246                // Trailing backslash will be handled as 'unclosed [' below
247            }
248            ']' => {
249                // Unescaped ']' ends the bracket
250                end = Some(start + offset);
251                break;
252            }
253            _ => {
254                unescaped.push(c);
255            }
256        }
257    }
258
259    let Some(end) = end else {
260        return Err(ArrowError::ParseError(format!("Unclosed '[' at byte {i}")));
261    };
262
263    let element = if let Some(inner) = unescaped
264        .strip_prefix('\'')
265        .and_then(|s| s.strip_suffix('\''))
266        .or_else(|| unescaped.strip_prefix('"')?.strip_suffix('"'))
267    {
268        // Quoted field name, e.g., ['field'] or ['123'] or ["123"]
269        VariantPathElement::field(inner.to_string())
270    } else {
271        let Ok(idx) = unescaped.parse() else {
272            return Err(ArrowError::ParseError(format!(
273                "Invalid token in bracket request: `{unescaped}`. Expected a quoted string or a number(e.g., `['field']` or `[123]`)"
274            )));
275        };
276        VariantPathElement::index(idx)
277    };
278
279    Ok((element, end + 1))
280}