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.
141#[allow(unused)]
142pub(crate) const fn expect_size_of<T>(expected: usize) {
143    let size = std::mem::size_of::<T>();
144    if size != expected {
145        let _ = [""; 0][size];
146    }
147}
148
149/// Parse a path string into a vector of [`VariantPathElement`].
150///
151/// # Syntax
152/// - `.field` or `field` - access object field (do not support special char)
153/// - `[index]` - access array element by index
154/// - `[field]` - access object field (support special char with escape `\`)
155///
156/// # Escape Rules
157/// Inside brackets `[...]`:
158/// - `\\` -> literal `\`
159/// - `\]` -> literal `]`
160/// - Any other `\x` -> literal `x`
161///
162/// Outside brackets, no escaping is supported.
163///
164/// # Examples
165/// - `""` -> empty path
166/// - `"foo"` -> single field `foo`
167/// - `"foo.bar"` -> nested fields `foo`, `bar`
168/// - `"[1]"` -> array index 1
169/// - `"['1']"` or `"["1"]"`-> field `1`
170/// - `"foo[1].bar"` -> field `foo`, index 1, field `bar`
171/// - `"['a.b']"` -> field `a.b` (dot is literal inside bracket)
172/// - `"['a\]b']"` -> field `a]b` (escaped `]`
173/// - etc.
174///
175/// # Errors
176/// - Leading `.` (e.g., `".foo"`)
177/// - Trailing `.` (e.g., `"foo."`)
178/// - Unclosed '[' (e.g., `"foo[1"`)
179/// - Unexpected ']' (e.g., `"foo]"`)
180/// - Trailing '`' inside bracket (treated as unclosed bracket)
181#[inline]
182pub(crate) fn parse_path(s: &str) -> Result<Vec<VariantPathElement<'_>>, ArrowError> {
183    let scan_field = |start: usize| {
184        s[start..]
185            .find(['.', '[', ']'])
186            .map_or_else(|| s.len(), |p| start + p)
187    };
188
189    let bytes = s.as_bytes();
190    if let Some(b'.') = bytes.first() {
191        return Err(ArrowError::ParseError("Unexpected leading '.'".into()));
192    }
193
194    let mut elements = Vec::new();
195    let mut i = 0;
196
197    while i < bytes.len() {
198        let (elem, end) = match bytes[i] {
199            b'.' => {
200                i += 1; // skip the dot; a field must follow
201                let end = scan_field(i);
202                if end == i {
203                    return Err(ArrowError::ParseError(match bytes.get(i) {
204                        None => "Unexpected trailing '.'".into(),
205                        Some(&c) => format!("Unexpected '{}' at byte {i}", c as char),
206                    }));
207                }
208                (VariantPathElement::field(&s[i..end]), end)
209            }
210            b'[' => {
211                let (element, end) = parse_in_bracket(s, i)?;
212                (element, end)
213            }
214            b']' => {
215                return Err(ArrowError::ParseError(format!(
216                    "Unexpected ']' at byte {i}"
217                )));
218            }
219            _ => {
220                let end = scan_field(i);
221                (VariantPathElement::field(&s[i..end]), end)
222            }
223        };
224        elements.push(elem);
225        i = end;
226    }
227
228    Ok(elements)
229}
230
231/// Parse `[digits | field]` starting at `i` (which points to `[`).
232/// Returns (VariantPathElement, position after `]`).
233fn parse_in_bracket(s: &str, i: usize) -> Result<(VariantPathElement<'_>, usize), ArrowError> {
234    let start = i + 1; // skip '['
235
236    let mut unescaped = String::new();
237    let mut chars = s[start..].char_indices().peekable();
238    let mut end = None;
239
240    while let Some((offset, c)) = chars.next() {
241        match c {
242            // Escape: take next char literally
243            '\\' => {
244                if let Some((_, next)) = chars.next() {
245                    unescaped.push(next);
246                }
247                // Trailing backslash will be handled as 'unclosed [' below
248            }
249            ']' => {
250                // Unescaped ']' ends the bracket
251                end = Some(start + offset);
252                break;
253            }
254            _ => {
255                unescaped.push(c);
256            }
257        }
258    }
259
260    let end = match end {
261        Some(e) => e,
262        None => {
263            return Err(ArrowError::ParseError(format!("Unclosed '[' at byte {i}")));
264        }
265    };
266
267    let element = if let Some(inner) = unescaped
268        .strip_prefix('\'')
269        .and_then(|s| s.strip_suffix('\''))
270        .or_else(|| {
271            unescaped
272                .strip_prefix('"')
273                .and_then(|s| s.strip_suffix('"'))
274        }) {
275        // Quoted field name, e.g., ['field'] or ['123'] or ["123"]
276        VariantPathElement::field(inner.to_string())
277    } else {
278        let Ok(idx) = unescaped.parse() else {
279            return Err(ArrowError::ParseError(format!(
280                "Invalid token in bracket request: `{unescaped}`. Expected a quoted string or a number(e.g., `['field']` or `[123]`)"
281            )));
282        };
283        VariantPathElement::index(idx)
284    };
285
286    Ok((element, end + 1))
287}