Skip to main content

vortex_array/arrays/varbin/
array.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Display;
5use std::fmt::Formatter;
6
7use num_traits::AsPrimitive;
8use vortex_buffer::BufferAllocatorRef;
9use vortex_buffer::ByteBuffer;
10use vortex_error::VortexExpect;
11use vortex_error::VortexResult;
12use vortex_error::vortex_bail;
13use vortex_error::vortex_ensure;
14use vortex_error::vortex_ensure_eq;
15use vortex_error::vortex_err;
16use vortex_mask::Mask;
17
18use crate::ArrayRef;
19use crate::ArraySlots;
20use crate::ExecutionCtx;
21use crate::array::Array;
22use crate::array::ArrayParts;
23use crate::array::TypedArrayRef;
24use crate::array::child_to_validity;
25use crate::array::validity_to_child;
26use crate::array_slots;
27use crate::arrays::PrimitiveArray;
28use crate::arrays::VarBin;
29use crate::arrays::varbin::builder::VarBinBuilder;
30use crate::buffer::BufferHandle;
31use crate::dtype::DType;
32use crate::dtype::IntegerPType;
33use crate::dtype::Nullability;
34use crate::dtype::OffsetBuilderPType;
35use crate::match_each_integer_ptype;
36use crate::scalar::ScalarValue;
37use crate::stats::Precision;
38use crate::stats::Stat;
39use crate::validity::Validity;
40
41/// Returns `true` if `index` is the end of `bytes` or the start of a UTF-8 char in it.
42fn is_char_boundary_at(bytes: &[u8], index: usize) -> bool {
43    // Continuation bytes have the form `0b10xx_xxxx`.
44    index == bytes.len() || bytes[index] & 0b1100_0000 != 0b1000_0000
45}
46
47/// Returns `true` if `offsets` never decrease, end within `bytes`, and delimit valid UTF-8
48/// strings, including the strings at null rows.
49///
50/// When the offsets never decrease, the strings tile `bytes[first..last]`. If that range is valid
51/// UTF-8 as a whole, every string is valid UTF-8 if and only if every offset falls on a char
52/// boundary. This costs one UTF-8 pass over the range instead of one call per string.
53pub(crate) fn offsets_tile_utf8<O: AsPrimitive<usize> + PartialOrd>(
54    offsets: &[O],
55    bytes: &[u8],
56) -> bool {
57    let (Some(first), Some(last)) = (offsets.first(), offsets.last()) else {
58        return false;
59    };
60    let (first, last): (usize, usize) = (first.as_(), last.as_());
61
62    first <= last
63        && last <= bytes.len()
64        && offsets.windows(2).all(|pair| pair[0] <= pair[1])
65        && simdutf8::basic::from_utf8(&bytes[first..last]).is_ok()
66        && offsets
67            .iter()
68            .all(|&offset| is_char_boundary_at(bytes, offset.as_()))
69}
70
71#[array_slots(VarBin)]
72pub struct VarBinSlots {
73    /// The offsets array defining the start/end of each variable-length binary element.
74    #[slot(0)]
75    pub offsets: ArrayRef,
76    /// The validity bitmap indicating which elements are non-null.
77    #[slot(1)]
78    pub validity_child: Option<ArrayRef>,
79}
80
81#[derive(Clone, Debug)]
82pub struct VarBinData {
83    pub(super) bytes: BufferHandle,
84}
85
86impl Display for VarBinData {
87    fn fmt(&self, _f: &mut Formatter<'_>) -> std::fmt::Result {
88        Ok(())
89    }
90}
91
92pub struct VarBinDataParts {
93    pub dtype: DType,
94    pub bytes: BufferHandle,
95    pub offsets: ArrayRef,
96    pub validity: Validity,
97}
98
99impl VarBinData {
100    /// Creates a new `VarBinArray`.
101    ///
102    /// # Panics
103    ///
104    /// Panics if the provided components do not satisfy the invariants documented
105    /// in `VarBinArray::new_unchecked`.
106    pub fn build(
107        offsets: ArrayRef,
108        bytes: ByteBuffer,
109        dtype: DType,
110        validity: Validity,
111        ctx: &mut ExecutionCtx,
112    ) -> Self {
113        Self::try_build(offsets, bytes, dtype, validity, ctx).vortex_expect("VarBinArray new")
114    }
115
116    /// Creates a new `VarBinArray`.
117    ///
118    /// # Panics
119    ///
120    /// Panics if the provided components do not satisfy the invariants documented
121    /// in `VarBinArray::new_unchecked`.
122    pub fn build_from_handle(
123        offset: ArrayRef,
124        bytes: BufferHandle,
125        dtype: DType,
126        validity: Validity,
127        ctx: &mut ExecutionCtx,
128    ) -> Self {
129        Self::try_build_from_handle(offset, bytes, dtype, validity, ctx)
130            .vortex_expect("VarBinArray new")
131    }
132
133    pub(crate) fn make_slots(offsets: ArrayRef, validity: &Validity, len: usize) -> ArraySlots {
134        VarBinSlots {
135            offsets,
136            validity_child: validity_to_child(validity, len),
137        }
138        .into_slots()
139    }
140
141    /// Constructs a new `VarBinArray`.
142    ///
143    /// See `VarBinArray::new_unchecked` for more information.
144    ///
145    /// # Errors
146    ///
147    /// Returns an error if the provided components do not satisfy the invariants documented in
148    /// `VarBinArray::new_unchecked`.
149    pub fn try_build(
150        offsets: ArrayRef,
151        bytes: ByteBuffer,
152        dtype: DType,
153        validity: Validity,
154        ctx: &mut ExecutionCtx,
155    ) -> VortexResult<Self> {
156        let bytes = BufferHandle::new_host(bytes);
157        Self::validate(&offsets, &bytes, &dtype, &validity, ctx)?;
158
159        // SAFETY: validate ensures all invariants are met.
160        Ok(unsafe { Self::new_unchecked_from_handle(bytes) })
161    }
162
163    /// Constructs a new `VarBinArray` from a `BufferHandle` of memory that may exist
164    /// on the CPU or GPU.
165    ///
166    /// See `VarBinArray::new_unchecked` for more information.
167    ///
168    /// # Errors
169    ///
170    /// Returns an error if the provided components do not satisfy the invariants documented in
171    /// `VarBinArray::new_unchecked`.
172    pub fn try_build_from_handle(
173        offsets: ArrayRef,
174        bytes: BufferHandle,
175        dtype: DType,
176        validity: Validity,
177        ctx: &mut ExecutionCtx,
178    ) -> VortexResult<Self> {
179        Self::validate(&offsets, &bytes, &dtype, &validity, ctx)?;
180
181        // SAFETY: validate ensures all invariants are met.
182        Ok(unsafe { Self::new_unchecked_from_handle(bytes) })
183    }
184
185    /// Creates a new `VarBinArray` without validation from these components:
186    ///
187    /// * `offsets` is an array of byte offsets into the `bytes` buffer.
188    /// * `bytes` is a buffer containing all the variable-length data concatenated.
189    /// * `dtype` specifies whether this contains UTF-8 strings or binary data.
190    /// * `validity` holds the null values.
191    ///
192    /// # Safety
193    ///
194    /// The caller must ensure all of the following invariants are satisfied:
195    ///
196    /// ## Offsets Requirements
197    ///
198    /// - `offsets` must be a non-nullable integer array.
199    /// - `offsets` must contain at least 1 element (for empty array, it contains \[0\]).
200    /// - All values in `offsets` must be monotonically non-decreasing.
201    /// - All values in `offsets` must be non-negative.
202    /// - No offset value may exceed `bytes.len()`.
203    ///
204    /// ## Type Requirements
205    ///
206    /// - `dtype` must be exactly [`DType::Binary`] or [`DType::Utf8`].
207    /// - If `dtype` is [`DType::Utf8`], every byte slice `bytes[offsets[i]..offsets[i+1]]` must be valid UTF-8.
208    /// - `dtype.is_nullable()` must match the nullability of `validity`.
209    ///
210    /// ## Validity Requirements
211    ///
212    /// - If `validity` is [`Validity::Array`], its length must exactly equal `offsets.len() - 1`.
213    pub unsafe fn new_unchecked(bytes: ByteBuffer) -> Self {
214        // SAFETY: `new_unchecked_from_handle` has same invariants which should be checked
215        //  by caller.
216        unsafe { Self::new_unchecked_from_handle(BufferHandle::new_host(bytes)) }
217    }
218
219    /// Creates a new `VarBinArray` without validation from its components, with string data
220    /// stored in a `BufferHandle` (CPU or GPU).
221    ///
222    /// # Safety
223    ///
224    /// The caller must ensure all the invariants documented in `new_unchecked` are satisfied.
225    pub unsafe fn new_unchecked_from_handle(bytes: BufferHandle) -> Self {
226        Self { bytes }
227    }
228
229    /// Validates the components that would be used to create a `VarBinArray`.
230    ///
231    /// This function checks all the invariants required by `VarBinArray::new_unchecked`.
232    pub fn validate(
233        offsets: &ArrayRef,
234        bytes: &BufferHandle,
235        dtype: &DType,
236        validity: &Validity,
237        ctx: &mut ExecutionCtx,
238    ) -> VortexResult<()> {
239        // Check offsets are non-nullable integer
240        vortex_ensure!(
241            offsets.dtype().is_int() && !offsets.dtype().is_nullable(),
242            "expected type: non nullable int but instead got {}",
243            offsets.dtype()
244        );
245
246        // Check dtype is Binary or Utf8
247        vortex_ensure!(
248            matches!(dtype, DType::Binary(_) | DType::Utf8(_)),
249            "expected type: utf8 or binary but instead got {}",
250            dtype
251        );
252
253        // Check nullability matches
254        vortex_ensure!(
255            dtype.is_nullable() != matches!(validity, Validity::NonNullable),
256            "incorrect validity {:?} for dtype {}",
257            validity,
258            dtype
259        );
260
261        // Check offsets has at least one element
262        vortex_ensure!(
263            !offsets.is_empty(),
264            "Offsets must have at least one element"
265        );
266
267        // Check validity length
268        if let Some(validity_len) = validity.maybe_len() {
269            vortex_ensure_eq!(
270                validity_len,
271                offsets.len() - 1,
272                "Validity length doesn't match array length",
273            );
274        }
275
276        // Validate UTF-8 for Utf8 dtype, which also validates the offsets. Skip when offsets/bytes
277        // are not host-resident. Offsets on a device cannot be read here.
278        if offsets.is_host()
279            && bytes.is_on_host()
280            && matches!(dtype, DType::Utf8(_))
281            && let Some(bytes) = bytes.as_host_opt()
282        {
283            Self::validate_utf8(offsets, bytes.as_ref(), validity, ctx)?;
284        } else if offsets.is_host() {
285            Self::validate_offsets(offsets, bytes.len(), ctx)?;
286        }
287
288        Ok(())
289    }
290
291    /// Validates that the offsets are sorted, non-negative and do not exceed `bytes_len`.
292    fn validate_offsets(
293        offsets: &ArrayRef,
294        bytes_len: usize,
295        ctx: &mut ExecutionCtx,
296    ) -> VortexResult<()> {
297        // Read the offset values and do not use the statistics of `offsets`. Statistics can come
298        // from untrusted input, for example a serialized file.
299        let primitive_offsets = offsets.clone().execute::<PrimitiveArray>(ctx)?;
300
301        match_each_integer_ptype!(primitive_offsets.dtype().as_ptype(), |P| {
302            Self::validate_offset_slice(offsets, primitive_offsets.as_slice::<P>(), bytes_len)
303        })
304    }
305
306    fn validate_offset_slice<P>(
307        offsets: &ArrayRef,
308        offsets_slice: &[P],
309        bytes_len: usize,
310    ) -> VortexResult<()>
311    where
312        P: IntegerPType + TryFrom<usize> + Into<ScalarValue>,
313    {
314        // Offsets must be sorted (but not strictly sorted, empty values are allowed).
315        if let Some(idx) = offsets_slice.windows(2).position(|w| w[0] > w[1]) {
316            vortex_bail!(
317                "offsets must be sorted, but offset {} at index {idx} is greater than \
318                 offset {} at index {}",
319                offsets_slice[idx],
320                offsets_slice[idx + 1],
321                idx + 1
322            );
323        }
324
325        // The offsets are sorted, thus the first offset is the minimum and the last
326        // offset is the maximum.
327        if let (Some(&min), Some(&max)) = (offsets_slice.first(), offsets_slice.last()) {
328            vortex_ensure!(
329                min >= P::zero(),
330                "offsets minimum {min} outside valid range [0, {max}]"
331            );
332
333            // An offset type too narrow for the bytes length cannot exceed it.
334            vortex_ensure!(
335                P::try_from(bytes_len).ok().is_none_or(|len| max <= len),
336                "Max offset {max} is beyond the length of the bytes buffer {bytes_len}"
337            );
338
339            // The checked values are exact, so keep them as statistics. This replaces any
340            // untrusted statistics on `offsets` and saves later scans.
341            let stats = offsets.statistics();
342            stats.set(Stat::IsSorted, Precision::exact(true));
343            stats.set(Stat::Min, Precision::exact(min));
344            stats.set(Stat::Max, Precision::exact(max));
345        }
346
347        Ok(())
348    }
349
350    /// Validates that every non-null value is valid UTF-8.
351    fn validate_utf8(
352        offsets: &ArrayRef,
353        bytes: &[u8],
354        validity: &Validity,
355        ctx: &mut ExecutionCtx,
356    ) -> VortexResult<()> {
357        // TODO(joe): update the created VarBin with this decompressed Array.
358        let primitive_offsets = offsets.clone().execute::<PrimitiveArray>(ctx)?;
359
360        // Array-backed validity is the only variant that needs an execution context: execute it into
361        // a mask once. The constant variants resolve null-ness without one. Resolving this before
362        // the per-type dispatch keeps the dtype loop simple.
363        let mask = match validity {
364            Validity::Array(_) => {
365                Some(validity.execute_mask(primitive_offsets.len().saturating_sub(1), ctx)?)
366            }
367            _ => None,
368        };
369        let all_invalid = validity.definitely_all_null();
370
371        match_each_integer_ptype!(primitive_offsets.dtype().as_ptype(), |O| {
372            Self::validate_utf8_offsets(
373                offsets,
374                primitive_offsets.as_slice::<O>(),
375                bytes,
376                mask.as_ref(),
377                all_invalid,
378            )
379        })
380    }
381
382    fn validate_utf8_offsets<
383        O: IntegerPType + AsPrimitive<usize> + TryFrom<usize> + Into<ScalarValue>,
384    >(
385        offsets: &ArrayRef,
386        offsets_slice: &[O],
387        bytes: &[u8],
388        mask: Option<&Mask>,
389        all_invalid: bool,
390    ) -> VortexResult<()> {
391        let last_offset: usize = offsets_slice[offsets_slice.len() - 1].as_();
392        vortex_ensure!(
393            last_offset <= bytes.len(),
394            "Last offset {} exceeds bytes length {}",
395            last_offset,
396            bytes.len()
397        );
398
399        if offsets_tile_utf8(offsets_slice, bytes) {
400            // The fast path checked that the offsets are sorted and in bounds, so keep the
401            // checked values as statistics. This replaces any untrusted statistics on `offsets`.
402            let stats = offsets.statistics();
403            stats.set(Stat::IsSorted, Precision::exact(true));
404            stats.set(Stat::Min, Precision::exact(offsets_slice[0]));
405            stats.set(
406                Stat::Max,
407                Precision::exact(offsets_slice[offsets_slice.len() - 1]),
408            );
409
410            return Ok(());
411        }
412
413        // The fast path proves the offsets are valid. The per-string check below skips null
414        // rows, so it cannot find bad offsets at those rows.
415        Self::validate_offset_slice(offsets, offsets_slice, bytes.len())?;
416
417        let validate_at = |i: usize, start: usize, end: usize| -> VortexResult<()> {
418            let string_bytes = bytes.get(start..end).ok_or_else(|| {
419                vortex_err!(
420                    "offsets {start}..{end} at index {i} are out of order or out of bounds for bytes of length {}",
421                    bytes.len()
422                )
423            })?;
424            simdutf8::basic::from_utf8(string_bytes).map_err(|_| {
425                #[expect(clippy::unwrap_used)]
426                // run validation using `compat` package to get more detailed error message
427                let err = simdutf8::compat::from_utf8(string_bytes).unwrap_err();
428                vortex_err!("invalid utf-8: {err} at index {i}")
429            })?;
430            Ok(())
431        };
432
433        // Invalid bytes at a null row fail the check above, so check valid strings one by one.
434        for (i, (start, end)) in offsets_slice
435            .windows(2)
436            .map(|o| (o[0].as_(), o[1].as_()))
437            .enumerate()
438        {
439            let valid = mask.map_or(!all_invalid, |mask| mask.value(i));
440            if valid {
441                validate_at(i, start, end)?;
442            }
443        }
444        Ok(())
445    }
446
447    /// Access the value bytes child buffer
448    ///
449    /// # Note
450    ///
451    /// Bytes child buffer is never sliced when the array is sliced so this can include values
452    /// that are not logically present in the array. Users should prefer `sliced_bytes`
453    /// unless they're resolving values via the offset child array.
454    #[inline]
455    pub fn bytes(&self) -> &ByteBuffer {
456        self.bytes.as_host()
457    }
458
459    /// Access the value bytes buffer handle.
460    #[inline]
461    pub fn bytes_handle(&self) -> &BufferHandle {
462        &self.bytes
463    }
464}
465
466pub trait VarBinArrayExt: TypedArrayRef<VarBin> {
467    fn dtype_parts(&self) -> (bool, Nullability) {
468        match self.dtype() {
469            DType::Utf8(nullability) => (true, *nullability),
470            DType::Binary(nullability) => (false, *nullability),
471            _ => unreachable!("VarBinArrayExt requires a utf8 or binary dtype"),
472        }
473    }
474
475    fn is_utf8(&self) -> bool {
476        self.dtype_parts().0
477    }
478
479    fn nullability(&self) -> Nullability {
480        self.dtype_parts().1
481    }
482
483    fn varbin_validity(&self) -> Validity {
484        child_to_validity(self.validity_child(), self.nullability())
485    }
486
487    fn offset_at(&self, index: usize, ctx: &mut ExecutionCtx) -> usize {
488        assert!(
489            index <= self.len(),
490            "Index {index} out of bounds 0..={}",
491            self.len()
492        );
493
494        (&self
495            .offsets()
496            .execute_scalar(index, ctx)
497            .vortex_expect("offsets must support execute_scalar"))
498            .try_into()
499            .vortex_expect("Failed to convert offset to usize")
500    }
501
502    fn bytes_at(&self, index: usize, ctx: &mut ExecutionCtx) -> ByteBuffer {
503        let start = self.offset_at(index, ctx);
504        let end = self.offset_at(index + 1, ctx);
505        self.bytes().slice(start..end)
506    }
507
508    fn sliced_bytes(&self, ctx: &mut ExecutionCtx) -> ByteBuffer {
509        let first_offset: usize = self.offset_at(0, ctx);
510        let last_offset = self.offset_at(self.len(), ctx);
511        self.bytes().slice(first_offset..last_offset)
512    }
513}
514impl<T: TypedArrayRef<VarBin>> VarBinArrayExt for T {}
515
516/// Forwarding constructors for `VarBinArray` (= `Array<VarBin>`).
517impl Array<VarBin> {
518    pub fn from_vec<T: AsRef<[u8]>>(vec: Vec<T>, dtype: DType) -> Self {
519        let size: usize = vec.iter().map(|v| v.as_ref().len()).sum();
520        if size < u32::MAX as usize {
521            Self::from_vec_sized::<u32, T>(vec, dtype)
522        } else {
523            Self::from_vec_sized::<u64, T>(vec, dtype)
524        }
525    }
526
527    #[expect(
528        clippy::same_name_method,
529        reason = "intentionally named from_iter like Iterator::from_iter"
530    )]
531    pub fn from_iter<T: AsRef<[u8]>, I: IntoIterator<Item = Option<T>>>(
532        iter: I,
533        dtype: DType,
534    ) -> Self {
535        let iter = iter.into_iter();
536        let mut builder = VarBinBuilder::<u32>::with_capacity_in(
537            dtype,
538            iter.size_hint().0,
539            BufferAllocatorRef::static_ref(),
540        );
541        for v in iter {
542            builder.append(v.as_ref().map(|o| o.as_ref()));
543        }
544        builder.finish_into_varbin()
545    }
546
547    pub fn from_iter_nonnull<T: AsRef<[u8]>, I: IntoIterator<Item = T>>(
548        iter: I,
549        dtype: DType,
550    ) -> Self {
551        let iter = iter.into_iter();
552        let mut builder = VarBinBuilder::<u32>::with_capacity_in(
553            dtype,
554            iter.size_hint().0,
555            BufferAllocatorRef::static_ref(),
556        );
557        for v in iter {
558            builder.append_value(v);
559        }
560        builder.finish_into_varbin()
561    }
562
563    fn from_vec_sized<O, T>(vec: Vec<T>, dtype: DType) -> Self
564    where
565        O: OffsetBuilderPType,
566        T: AsRef<[u8]>,
567    {
568        let mut builder = VarBinBuilder::<O>::with_capacity_in(
569            dtype,
570            vec.len(),
571            BufferAllocatorRef::static_ref(),
572        );
573        for v in vec {
574            builder.append_value(v.as_ref());
575        }
576        builder.finish_into_varbin()
577    }
578
579    /// Create from a vector of string slices.
580    pub fn from_strs(value: Vec<&str>) -> Self {
581        Self::from_vec(value, DType::Utf8(Nullability::NonNullable))
582    }
583
584    /// Create from a vector of optional string slices.
585    pub fn from_nullable_strs(value: Vec<Option<&str>>) -> Self {
586        Self::from_iter(value, DType::Utf8(Nullability::Nullable))
587    }
588
589    /// Create from a vector of byte slices.
590    pub fn from_bytes(value: Vec<&[u8]>) -> Self {
591        Self::from_vec(value, DType::Binary(Nullability::NonNullable))
592    }
593
594    /// Create from a vector of optional byte slices.
595    pub fn from_nullable_bytes(value: Vec<Option<&[u8]>>) -> Self {
596        Self::from_iter(value, DType::Binary(Nullability::Nullable))
597    }
598
599    pub fn into_data_parts(self) -> VarBinDataParts {
600        let dtype = self.dtype().clone();
601        let validity = self.varbin_validity();
602        let offsets = self.offsets().clone();
603        let data = self.into_data();
604        VarBinDataParts {
605            dtype,
606            bytes: data.bytes,
607            offsets,
608            validity,
609        }
610    }
611}
612
613impl Array<VarBin> {
614    /// Creates a new `VarBinArray`.
615    pub fn new(
616        offsets: ArrayRef,
617        bytes: ByteBuffer,
618        dtype: DType,
619        validity: Validity,
620        ctx: &mut ExecutionCtx,
621    ) -> Self {
622        let len = offsets.len().saturating_sub(1);
623        let slots = VarBinData::make_slots(offsets, &validity, len);
624        let data = VarBinData::build(
625            slots[VarBinSlots::OFFSETS]
626                .as_ref()
627                .vortex_expect("VarBinArray offsets slot")
628                .clone(),
629            bytes,
630            dtype.clone(),
631            validity,
632            ctx,
633        );
634        unsafe { Array::from_parts_unchecked(ArrayParts::new(VarBin, dtype, len, data, slots)) }
635    }
636
637    /// Creates a new `VarBinArray` without validation.
638    ///
639    /// # Safety
640    ///
641    /// See [`VarBinData::new_unchecked`].
642    pub unsafe fn new_unchecked(
643        offsets: ArrayRef,
644        bytes: ByteBuffer,
645        dtype: DType,
646        validity: Validity,
647    ) -> Self {
648        let len = offsets.len().saturating_sub(1);
649        let slots = VarBinData::make_slots(offsets, &validity, len);
650        let data = unsafe { VarBinData::new_unchecked(bytes) };
651        unsafe { Array::from_parts_unchecked(ArrayParts::new(VarBin, dtype, len, data, slots)) }
652    }
653
654    /// Creates a new `VarBinArray` without validation from a [`BufferHandle`].
655    ///
656    /// # Safety
657    ///
658    /// See [`VarBinData::new_unchecked_from_handle`].
659    pub unsafe fn new_unchecked_from_handle(
660        offsets: ArrayRef,
661        bytes: BufferHandle,
662        dtype: DType,
663        validity: Validity,
664    ) -> Self {
665        let len = offsets.len().saturating_sub(1);
666        let slots = VarBinData::make_slots(offsets, &validity, len);
667        let data = unsafe { VarBinData::new_unchecked_from_handle(bytes) };
668        unsafe { Array::from_parts_unchecked(ArrayParts::new(VarBin, dtype, len, data, slots)) }
669    }
670
671    /// Constructs a new `VarBinArray`, using `ctx` to validate the offsets and, for UTF-8 arrays,
672    /// the string data.
673    pub fn try_new(
674        offsets: ArrayRef,
675        bytes: ByteBuffer,
676        dtype: DType,
677        validity: Validity,
678        ctx: &mut ExecutionCtx,
679    ) -> VortexResult<Self> {
680        let len = offsets.len() - 1;
681        let bytes = BufferHandle::new_host(bytes);
682        VarBinData::validate(&offsets, &bytes, &dtype, &validity, ctx)?;
683        let slots = VarBinData::make_slots(offsets, &validity, len);
684        // SAFETY: validate ensures all invariants are met.
685        let data = unsafe { VarBinData::new_unchecked_from_handle(bytes) };
686        Ok(
687            unsafe {
688                Array::from_parts_unchecked(ArrayParts::new(VarBin, dtype, len, data, slots))
689            },
690        )
691    }
692}
693
694impl From<Vec<&[u8]>> for Array<VarBin> {
695    fn from(value: Vec<&[u8]>) -> Self {
696        Self::from_vec(value, DType::Binary(Nullability::NonNullable))
697    }
698}
699
700impl From<Vec<Vec<u8>>> for Array<VarBin> {
701    fn from(value: Vec<Vec<u8>>) -> Self {
702        Self::from_vec(value, DType::Binary(Nullability::NonNullable))
703    }
704}
705
706impl From<Vec<String>> for Array<VarBin> {
707    fn from(value: Vec<String>) -> Self {
708        Self::from_vec(value, DType::Utf8(Nullability::NonNullable))
709    }
710}
711
712impl From<Vec<&str>> for Array<VarBin> {
713    fn from(value: Vec<&str>) -> Self {
714        Self::from_vec(value, DType::Utf8(Nullability::NonNullable))
715    }
716}
717
718impl From<Vec<Option<&[u8]>>> for Array<VarBin> {
719    fn from(value: Vec<Option<&[u8]>>) -> Self {
720        Self::from_iter(value, DType::Binary(Nullability::Nullable))
721    }
722}
723
724impl From<Vec<Option<Vec<u8>>>> for Array<VarBin> {
725    fn from(value: Vec<Option<Vec<u8>>>) -> Self {
726        Self::from_iter(value, DType::Binary(Nullability::Nullable))
727    }
728}
729
730impl From<Vec<Option<String>>> for Array<VarBin> {
731    fn from(value: Vec<Option<String>>) -> Self {
732        Self::from_iter(value, DType::Utf8(Nullability::Nullable))
733    }
734}
735
736impl From<Vec<Option<&str>>> for Array<VarBin> {
737    fn from(value: Vec<Option<&str>>) -> Self {
738        Self::from_iter(value, DType::Utf8(Nullability::Nullable))
739    }
740}
741
742impl<'a> FromIterator<Option<&'a [u8]>> for Array<VarBin> {
743    fn from_iter<T: IntoIterator<Item = Option<&'a [u8]>>>(iter: T) -> Self {
744        Self::from_iter(iter, DType::Binary(Nullability::Nullable))
745    }
746}
747
748impl FromIterator<Option<Vec<u8>>> for Array<VarBin> {
749    fn from_iter<T: IntoIterator<Item = Option<Vec<u8>>>>(iter: T) -> Self {
750        Self::from_iter(iter, DType::Binary(Nullability::Nullable))
751    }
752}
753
754impl FromIterator<Option<String>> for Array<VarBin> {
755    fn from_iter<T: IntoIterator<Item = Option<String>>>(iter: T) -> Self {
756        Self::from_iter(iter, DType::Utf8(Nullability::Nullable))
757    }
758}
759
760impl<'a> FromIterator<Option<&'a str>> for Array<VarBin> {
761    fn from_iter<T: IntoIterator<Item = Option<&'a str>>>(iter: T) -> Self {
762        Self::from_iter(iter, DType::Utf8(Nullability::Nullable))
763    }
764}