Skip to main content

vortex_array/arrays/varbinview/
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;
6use std::mem::size_of;
7use std::sync::Arc;
8
9use smallvec::smallvec;
10use vortex_buffer::Alignment;
11use vortex_buffer::Buffer;
12use vortex_buffer::BufferAllocatorRef;
13use vortex_buffer::ByteBuffer;
14use vortex_error::VortexExpect;
15use vortex_error::VortexResult;
16use vortex_error::vortex_bail;
17use vortex_error::vortex_ensure;
18use vortex_error::vortex_ensure_eq;
19use vortex_error::vortex_err;
20use vortex_error::vortex_panic;
21use vortex_mask::AllOr;
22use vortex_mask::Mask;
23
24use crate::ArrayRef;
25use crate::ArraySlots;
26use crate::ExecutionCtx;
27use crate::array::Array;
28use crate::array::ArrayParts;
29use crate::array::TypedArrayRef;
30use crate::array::child_to_validity;
31use crate::array::validity_to_child;
32use crate::array_slots;
33use crate::arrays::VarBinView;
34use crate::arrays::varbinview::BinaryView;
35use crate::arrays::varbinview::ResolvedViews;
36use crate::buffer::BufferHandle;
37use crate::builders::ArrayBuilder;
38use crate::builders::VarBinViewBuilder;
39use crate::dtype::DType;
40use crate::dtype::Nullability;
41use crate::validity::Validity;
42
43#[array_slots(VarBinView)]
44pub struct VarBinViewSlots {
45    /// The validity bitmap indicating which elements are non-null.
46    #[slot(0)]
47    pub validity_child: Option<ArrayRef>,
48}
49
50/// A variable-length binary view array that stores strings and binary data efficiently.
51///
52/// This mirrors the Apache Arrow StringView/BinaryView array encoding and provides
53/// an optimized representation for variable-length data with excellent performance
54/// characteristics for both short and long strings.
55///
56/// ## Data Layout
57///
58/// The array uses a hybrid storage approach with two main components:
59/// - **Views buffer**: Array of 16-byte `BinaryView` entries (one per logical element)
60/// - **Data buffers**: Shared backing storage for strings longer than 12 bytes
61///
62/// ## View Structure
63///
64/// Commonly referred to as "German Strings", each 16-byte view entry contains either:
65/// - **Inlined data**: For strings ≤ 12 bytes, the entire string is stored directly in the view
66/// - **Reference data**: For strings > 12 bytes, contains:
67///   - String length (4 bytes)
68///   - First 4 bytes of string as prefix (4 bytes)
69///   - Buffer index and offset (8 bytes total)
70///
71/// The following ASCII graphic is reproduced verbatim from the Arrow documentation:
72///
73/// ```text
74///                         ┌──────┬────────────────────────┐
75///                         │length│      string value      │
76///    Strings (len <= 12)  │      │    (padded with 0)     │
77///                         └──────┴────────────────────────┘
78///                          0    31                      127
79///
80///                         ┌───────┬───────┬───────┬───────┐
81///                         │length │prefix │  buf  │offset │
82///    Strings (len > 12)   │       │       │ index │       │
83///                         └───────┴───────┴───────┴───────┘
84///                          0    31       63      95    127
85/// ```
86///
87/// # Examples
88///
89/// ```
90/// use vortex_array::arrays::VarBinViewArray;
91/// use vortex_array::dtype::{DType, Nullability};
92/// use vortex_array::IntoArray;
93///
94/// // Create from an Iterator<Item = &str>
95/// let array = VarBinViewArray::from_iter_str([
96///         "inlined",
97///         "this string is outlined"
98/// ]);
99///
100/// assert_eq!(array.len(), 2);
101///
102/// // Access individual strings
103/// let first = array.bytes_at(0);
104/// assert_eq!(first.as_slice(), b"inlined"); // "short"
105///
106/// let second = array.bytes_at(1);
107/// assert_eq!(second.as_slice(), b"this string is outlined"); // Long string
108/// ```
109#[derive(Clone, Debug)]
110pub struct VarBinViewData {
111    pub(super) buffers: Arc<[BufferHandle]>,
112    pub(super) views: BufferHandle,
113}
114
115impl Display for VarBinViewData {
116    fn fmt(&self, _f: &mut Formatter<'_>) -> std::fmt::Result {
117        Ok(())
118    }
119}
120
121pub struct VarBinViewDataParts {
122    pub dtype: DType,
123    pub buffers: Arc<[BufferHandle]>,
124    pub views: BufferHandle,
125    pub validity: Validity,
126}
127
128// Walk invalid (null) runs of "mask" as [start, end) ranges
129fn for_each_invalid_range(mask: &Mask, len: usize, mut f: impl FnMut(usize, usize)) {
130    match mask.bit_buffer() {
131        AllOr::All => {}
132        AllOr::None => f(0, len),
133        AllOr::Some(buffer) => {
134            let mut prev = 0;
135            for (start, end) in buffer.set_slices() {
136                if start > prev {
137                    f(prev, start);
138                }
139                prev = end;
140            }
141            if prev < len {
142                f(prev, len);
143            }
144        }
145    }
146}
147
148/// Returns `true` if all the inlined bytes of `view` are ASCII.
149fn is_inlined_ascii(view: &BinaryView) -> bool {
150    const HIGH_BITS: u128 = u128::from_le_bytes([0x80; 16]);
151
152    // The first 4 bytes hold the length, and the inlined bytes follow.
153    let data_bits = ((1u128 << (8 * view.len())) - 1) << 32;
154    view.as_u128() & data_bits & HIGH_BITS == 0
155}
156
157/// Returns `true` if `byte` starts a UTF-8 char, that is, it is not a continuation byte.
158fn is_char_boundary(byte: u8) -> bool {
159    // Continuation bytes have the form `0b10xx_xxxx`.
160    byte & 0b1100_0000 != 0b1000_0000
161}
162
163impl VarBinViewData {
164    fn dtype_parts(dtype: &DType) -> VortexResult<(bool, Nullability)> {
165        match dtype {
166            DType::Utf8(nullability) => Ok((true, *nullability)),
167            DType::Binary(nullability) => Ok((false, *nullability)),
168            _ => vortex_bail!("invalid DType {dtype} for `VarBinViewArray`"),
169        }
170    }
171
172    /// Build the slots vector for this array.
173    pub(super) fn make_slots(validity: &Validity, len: usize) -> ArraySlots {
174        smallvec![validity_to_child(validity, len)]
175    }
176
177    /// Creates a new `VarBinViewArray`.
178    ///
179    /// # Panics
180    ///
181    /// Panics if the provided components do not satisfy the invariants documented
182    /// in `VarBinViewArray::new_unchecked`.
183    pub fn new(
184        views: Buffer<BinaryView>,
185        buffers: Arc<[ByteBuffer]>,
186        dtype: DType,
187        validity: Validity,
188        ctx: &mut ExecutionCtx,
189    ) -> Self {
190        Self::try_new(views, buffers, dtype, validity, ctx)
191            .vortex_expect("VarBinViewArray construction failed")
192    }
193
194    /// Creates a new `VarBinViewArray` with device or host memory.
195    ///
196    /// # Panics
197    ///
198    /// Panics if the provided components do not satisfy the invariants documented
199    /// in `VarBinViewArray::new_unchecked`.
200    pub fn new_handle(
201        views: BufferHandle,
202        buffers: Arc<[BufferHandle]>,
203        dtype: DType,
204        validity: Validity,
205    ) -> Self {
206        Self::try_new_handle(views, buffers, dtype, validity)
207            .vortex_expect("VarbinViewArray construction failed")
208    }
209
210    /// Constructs a new `VarBinViewArray`.
211    ///
212    /// See `VarBinViewArray::new_unchecked` for more information.
213    ///
214    /// # Errors
215    ///
216    /// Returns an error if the provided components do not satisfy the invariants documented in
217    /// `VarBinViewArray::new_unchecked`.
218    pub fn try_new(
219        views: Buffer<BinaryView>,
220        buffers: Arc<[ByteBuffer]>,
221        dtype: DType,
222        validity: Validity,
223        ctx: &mut ExecutionCtx,
224    ) -> VortexResult<Self> {
225        let views = Self::validate_and_fix(views, &buffers, &dtype, &validity, ctx)?;
226
227        // SAFETY: validate ensures all invariants are met.
228        Ok(unsafe { Self::new_unchecked(views, buffers, dtype, validity) })
229    }
230
231    /// Constructs a new `VarBinViewArray`.
232    ///
233    /// See `VarBinViewArray::new_unchecked` for more information.
234    ///
235    /// # Errors
236    ///
237    /// Returns an error if the provided components do not satisfy the invariants documented in
238    /// `VarBinViewArray::new_unchecked`.
239    pub fn try_new_handle(
240        views: BufferHandle,
241        buffers: Arc<[BufferHandle]>,
242        dtype: DType,
243        validity: Validity,
244    ) -> VortexResult<Self> {
245        let views_nbytes = views.len();
246        vortex_ensure!(
247            views_nbytes.is_multiple_of(size_of::<BinaryView>()),
248            "Expected views buffer length ({views_nbytes}) to be a multiple of {}",
249            size_of::<BinaryView>()
250        );
251
252        // TODO(aduffy): device validation.
253        if let Some(host) = views.as_host_opt() {
254            vortex_ensure!(
255                host.is_aligned(Alignment::of::<BinaryView>()),
256                "Views on host must be 16 byte aligned"
257            );
258        }
259
260        // SAFETY: validate ensures all invariants are met.
261        Ok(unsafe { Self::new_handle_unchecked(views, buffers, dtype, validity) })
262    }
263
264    /// Creates a new `VarBinViewArray` without validation from these components:
265    ///
266    /// * `views` is a buffer of 16-byte view entries (one per logical element).
267    /// * `buffers` contains the backing storage for strings longer than 12 bytes.
268    /// * `dtype` specifies whether this contains UTF-8 strings or binary data.
269    /// * `validity` holds the null values.
270    ///
271    /// # Safety
272    ///
273    /// The caller must ensure all of the following invariants are satisfied:
274    ///
275    /// ## View Requirements
276    ///
277    /// - Views must be properly formatted 16-byte [`BinaryView`] entries.
278    /// - Inlined views (length ≤ 12) must have valid data in the first `length` bytes.
279    /// - Reference views (length > 12) must:
280    ///   - Have a valid buffer index < `buffers.len()`.
281    ///   - Have valid offsets that don't exceed the referenced buffer's bounds.
282    ///   - Have a 4-byte prefix that matches the actual data at the referenced location.
283    ///
284    /// ## Type Requirements
285    ///
286    /// - `dtype` must be either [`DType::Utf8`] or [`DType::Binary`].
287    /// - For [`DType::Utf8`], all string data (both inlined and referenced) must be valid UTF-8.
288    ///
289    /// ## Validity Requirements
290    ///
291    /// - The validity must have the same nullability as the dtype.
292    /// - If validity is an array, its length must match `views.len()`.
293    pub unsafe fn new_unchecked(
294        views: Buffer<BinaryView>,
295        buffers: Arc<[ByteBuffer]>,
296        dtype: DType,
297        validity: Validity,
298    ) -> Self {
299        let handles: Vec<BufferHandle> = buffers
300            .iter()
301            .cloned()
302            .map(BufferHandle::new_host)
303            .collect();
304
305        let handles = Arc::from(handles);
306        let view_handle = BufferHandle::new_host(views.into_byte_buffer());
307        unsafe { Self::new_handle_unchecked(view_handle, handles, dtype, validity) }
308    }
309
310    /// Construct a new array from `BufferHandle`s without validation.
311    ///
312    /// # Safety
313    ///
314    /// See documentation in `new_unchecked`.
315    pub unsafe fn new_handle_unchecked(
316        views: BufferHandle,
317        buffers: Arc<[BufferHandle]>,
318        dtype: DType,
319        _validity: Validity,
320    ) -> Self {
321        let _ =
322            Self::dtype_parts(&dtype).vortex_expect("VarBinViewArray dtype must be utf8 or binary");
323        Self { buffers, views }
324    }
325
326    /// Validates the components that would be used to create a `VarBinViewArray`.
327    ///
328    /// This function checks all the invariants required by `VarBinViewArray::new_unchecked`,
329    /// validating only the views at non-null slots.
330    pub fn validate(
331        views: &Buffer<BinaryView>,
332        buffers: &Arc<[ByteBuffer]>,
333        dtype: &DType,
334        validity: &Validity,
335        ctx: &mut ExecutionCtx,
336    ) -> VortexResult<()> {
337        let check_utf8 = Self::check_nullability(dtype, validity)?;
338        let mask = validity.execute_mask(views.len(), ctx)?;
339        Self::validate_views(views, &mask, buffers, check_utf8)
340    }
341
342    /// Validates components like validate() and replaces views at null slots to empty views
343    pub(crate) fn validate_and_fix(
344        views: Buffer<BinaryView>,
345        buffers: &Arc<[ByteBuffer]>,
346        dtype: &DType,
347        validity: &Validity,
348        ctx: &mut ExecutionCtx,
349    ) -> VortexResult<Buffer<BinaryView>> {
350        let check_utf8 = Self::check_nullability(dtype, validity)?;
351        let mask = validity.execute_mask(views.len(), ctx)?;
352
353        // With nulls and views we own, validate and replace in a single pass: a second pass over
354        // many short null runs costs more than a branch per view.
355        let views = match (mask.bit_buffer(), views.try_into_mut()) {
356            (AllOr::Some(bits), Ok(mut views)) => {
357                let buffers_utf8 = Self::buffers_utf8(&mask, buffers, check_utf8);
358                let buffers_utf8 = buffers_utf8.as_deref();
359                let empty = BinaryView::empty_view();
360                let slice = views.as_mut_slice();
361                for (idx, (view, valid)) in slice.iter_mut().zip(bits.iter()).enumerate() {
362                    if valid {
363                        Self::validate_view(idx, view, buffers, buffers_utf8)?;
364                    } else {
365                        *view = empty;
366                    }
367                }
368                return Ok(views.freeze());
369            }
370            (_, Ok(views)) => views.freeze(),
371            (_, Err(views)) => views,
372        };
373
374        Self::validate_views(&views, &mask, buffers, check_utf8)?;
375        Ok(Self::replace_null_views(views, &mask))
376    }
377
378    fn check_nullability(dtype: &DType, validity: &Validity) -> VortexResult<bool> {
379        let (is_utf8, nullability) = Self::dtype_parts(dtype)?;
380        vortex_ensure_eq!(
381            validity.nullability(),
382            nullability,
383            "validity nullability is incompatible with dtype nullability",
384        );
385        Ok(is_utf8)
386    }
387
388    /// Replaces the views at null slots with empty views. Copies the views only if a null slot
389    /// holds a non-empty view and the buffer is shared.
390    fn replace_null_views(views: Buffer<BinaryView>, mask: &Mask) -> Buffer<BinaryView> {
391        if mask.all_true() {
392            return views;
393        }
394
395        let empty = BinaryView::empty_view();
396        let len = views.len();
397
398        let mut views = match views.try_into_mut() {
399            Ok(views) => views,
400            Err(views) => {
401                let mut needs_replace = false;
402                for_each_invalid_range(mask, len, |start, end| {
403                    needs_replace |= views[start..end].iter().any(|view| *view != empty);
404                });
405                if !needs_replace {
406                    return views;
407                }
408                views.into_mut()
409            }
410        };
411
412        let slice = views.as_mut_slice();
413        for_each_invalid_range(mask, len, |start, end| slice[start..end].fill(empty));
414        views.freeze()
415    }
416
417    /// Validates the views at the valid slots of `mask`.
418    ///
419    /// A per-view UTF-8 check costs a function call per view, which dominates for short strings.
420    /// To avoid it, each data buffer is first checked once as a whole. If a buffer is valid UTF-8,
421    /// a view into it is valid UTF-8 if and only if it starts and ends on a char boundary.
422    ///
423    /// A buffer can hold bytes that no valid view references, for example after a slice, after a
424    /// filter, or at null views. So the whole-buffer check is only done while the total size of
425    /// the checked buffers stays within a fixed cost per valid view. The views into a buffer that
426    /// is not checked, or that is not valid UTF-8, are checked one by one.
427    fn validate_views(
428        views: &[BinaryView],
429        mask: &Mask,
430        buffers: &[ByteBuffer],
431        check_utf8: bool,
432    ) -> VortexResult<()> {
433        let buffers_utf8 = Self::buffers_utf8(mask, buffers, check_utf8);
434        let buffers_utf8 = buffers_utf8.as_deref();
435
436        let validate = |idx: usize| Self::validate_view(idx, &views[idx], buffers, buffers_utf8);
437        match mask.bit_buffer() {
438            AllOr::All => (0..mask.len()).try_for_each(validate),
439            AllOr::None => Ok(()),
440            AllOr::Some(bits) => bits.try_for_each_set_index(validate),
441        }
442    }
443
444    /// The approximate cost of a per-view UTF-8 check, in bytes of a whole-buffer check.
445    const PER_VIEW_UTF8_COST: usize = 64;
446
447    /// Returns `None` if the UTF-8 check is off. Otherwise, returns for each buffer `true` if the
448    /// whole buffer was checked and is valid UTF-8.
449    ///
450    /// The budget only counts a fixed cost per valid view, not the bytes the views reference: for
451    /// long strings, the call per view is cheap next to the string, and checking a buffer larger
452    /// than the cache and then reading it again for the char boundaries is slower.
453    fn buffers_utf8(mask: &Mask, buffers: &[ByteBuffer], check_utf8: bool) -> Option<Vec<bool>> {
454        if !check_utf8 {
455            return None;
456        }
457
458        let mut budget = mask.true_count().saturating_mul(Self::PER_VIEW_UTF8_COST);
459
460        Some(
461            buffers
462                .iter()
463                .map(|buf| {
464                    if buf.len() > budget {
465                        return false;
466                    }
467
468                    budget -= buf.len();
469                    simdutf8::basic::from_utf8(buf).is_ok()
470                })
471                .collect(),
472        )
473    }
474
475    /// Checks the bounds, the prefix, and the UTF-8 of a view.
476    ///
477    /// `buffers_utf8` is `None` if the UTF-8 check is off. Otherwise, it tells which buffers are
478    /// valid UTF-8 as a whole.
479    fn validate_view(
480        idx: usize,
481        view: &BinaryView,
482        buffers: &[ByteBuffer],
483        buffers_utf8: Option<&[bool]>,
484    ) -> VortexResult<()> {
485        if view.is_inlined() {
486            if buffers_utf8.is_some() && !is_inlined_ascii(view) {
487                let bytes = view.as_inlined().value();
488                vortex_ensure!(
489                    simdutf8::basic::from_utf8(bytes).is_ok(),
490                    "view at index {idx}: inlined bytes failed utf-8 validation"
491                );
492            }
493            return Ok(());
494        }
495
496        let view = view.as_view();
497        let buf_index = view.buffer_index as usize;
498        let start_offset = view.offset as usize;
499        let end_offset = start_offset.saturating_add(view.size as usize);
500
501        let buf = buffers.get(buf_index).ok_or_else(||
502            vortex_err!("view at index {idx} references invalid buffer: {buf_index} out of bounds for VarBinViewData with {} buffers",
503                buffers.len()))?;
504
505        vortex_ensure!(
506            start_offset < buf.len(),
507            "start offset {start_offset} out of bounds for buffer {buf_index} with size {}",
508            buf.len(),
509        );
510
511        vortex_ensure!(
512            end_offset <= buf.len(),
513            "end offset {end_offset} out of bounds for buffer {buf_index} with size {}",
514            buf.len(),
515        );
516
517        // Make sure the prefix data matches the buffer data.
518        vortex_ensure!(
519            view.prefix == buf[start_offset..start_offset + 4],
520            "VarBinView prefix does not match full string"
521        );
522
523        let Some(buffers_utf8) = buffers_utf8 else {
524            return Ok(());
525        };
526
527        let valid_utf8 = if buffers_utf8[buf_index] {
528            is_char_boundary(buf[start_offset])
529                && (end_offset == buf.len() || is_char_boundary(buf[end_offset]))
530        } else {
531            simdutf8::basic::from_utf8(&buf[start_offset..end_offset]).is_ok()
532        };
533
534        vortex_ensure!(
535            valid_utf8,
536            "view at index {idx}: outlined bytes fails utf-8 validation"
537        );
538
539        Ok(())
540    }
541
542    /// Returns the length of this array.
543    pub fn len(&self) -> usize {
544        self.views.len() / size_of::<BinaryView>()
545    }
546
547    /// Returns `true` if this array is empty.
548    pub fn is_empty(&self) -> bool {
549        self.len() == 0
550    }
551
552    /// Access to the primitive views buffer.
553    ///
554    /// Variable-sized binary view buffer contain a "view" child array, with 16-byte entries that
555    /// contain either a pointer into one of the array's owned `buffer`s OR an inlined copy of
556    /// the string (if the string has 12 bytes or fewer).
557    #[inline]
558    pub fn views(&self) -> &[BinaryView] {
559        let host_views = self.views.as_host();
560        let len = host_views.len() / size_of::<BinaryView>();
561
562        // SAFETY: data alignment is checked for host buffers on construction
563        unsafe { std::slice::from_raw_parts(host_views.as_ptr().cast(), len) }
564    }
565
566    /// Return the buffer handle backing the views.
567    pub fn views_handle(&self) -> &BufferHandle {
568        &self.views
569    }
570
571    /// Access value bytes at a given index
572    ///
573    /// Will return a `ByteBuffer` containing the data without performing a copy.
574    #[inline]
575    pub fn bytes_at(&self, index: usize) -> ByteBuffer {
576        let views = self.views();
577        let view = &views[index];
578        // Expect this to be the common case: strings > 12 bytes.
579        if !view.is_inlined() {
580            let view_ref = view.as_view();
581            self.buffer(view_ref.buffer_index as usize)
582                .slice(view_ref.as_range())
583        } else {
584            // Return access to the range of bytes around it.
585            self.views_handle()
586                .as_host()
587                .clone()
588                .into_byte_buffer()
589                .slice_ref(view.as_inlined().value())
590        }
591    }
592
593    /// Access one of the backing data buffers.
594    ///
595    /// # Panics
596    ///
597    /// This method panics if the provided index is out of bounds for the set of buffers provided
598    /// at construction time.
599    #[inline]
600    pub fn buffer(&self, idx: usize) -> &ByteBuffer {
601        if idx >= self.data_buffers().len() {
602            vortex_panic!(
603                "{idx} buffer index out of bounds, there are {} buffers",
604                self.data_buffers().len()
605            );
606        }
607        self.buffers[idx].as_host()
608    }
609
610    /// The underlying raw data buffers, not including the views buffer.
611    #[inline]
612    pub fn data_buffers(&self) -> &Arc<[BufferHandle]> {
613        &self.buffers
614    }
615
616    /// Accumulate an iterable set of values into our type here.
617    #[expect(
618        clippy::same_name_method,
619        reason = "intentionally named from_iter like Iterator::from_iter"
620    )]
621    pub fn from_iter<T: AsRef<[u8]>, I: IntoIterator<Item = Option<T>>>(
622        iter: I,
623        dtype: DType,
624    ) -> Self {
625        let iter = iter.into_iter();
626        let mut builder = VarBinViewBuilder::with_capacity_in(
627            dtype,
628            iter.size_hint().0,
629            BufferAllocatorRef::statically_allocated(),
630        );
631
632        for item in iter {
633            match item {
634                None => builder.append_null(),
635                Some(v) => builder.append_value(v),
636            }
637        }
638
639        builder.finish_into_varbinview().into_data()
640    }
641
642    pub fn from_iter_str<T: AsRef<str>, I: IntoIterator<Item = T>>(iter: I) -> Self {
643        let iter = iter.into_iter();
644        let mut builder = VarBinViewBuilder::with_capacity_in(
645            DType::Utf8(Nullability::NonNullable),
646            iter.size_hint().0,
647            BufferAllocatorRef::statically_allocated(),
648        );
649
650        for item in iter {
651            builder.append_value(item.as_ref());
652        }
653
654        builder.finish_into_varbinview().into_data()
655    }
656
657    pub fn from_iter_nullable_str<T: AsRef<str>, I: IntoIterator<Item = Option<T>>>(
658        iter: I,
659    ) -> Self {
660        let iter = iter.into_iter();
661        let mut builder = VarBinViewBuilder::with_capacity_in(
662            DType::Utf8(Nullability::Nullable),
663            iter.size_hint().0,
664            BufferAllocatorRef::statically_allocated(),
665        );
666
667        for item in iter {
668            match item {
669                None => builder.append_null(),
670                Some(v) => builder.append_value(v.as_ref()),
671            }
672        }
673
674        builder.finish_into_varbinview().into_data()
675    }
676
677    pub fn from_iter_bin<T: AsRef<[u8]>, I: IntoIterator<Item = T>>(iter: I) -> Self {
678        let iter = iter.into_iter();
679        let mut builder = VarBinViewBuilder::with_capacity_in(
680            DType::Binary(Nullability::NonNullable),
681            iter.size_hint().0,
682            BufferAllocatorRef::statically_allocated(),
683        );
684
685        for item in iter {
686            builder.append_value(item.as_ref());
687        }
688
689        builder.finish_into_varbinview().into_data()
690    }
691
692    pub fn from_iter_nullable_bin<T: AsRef<[u8]>, I: IntoIterator<Item = Option<T>>>(
693        iter: I,
694    ) -> Self {
695        let iter = iter.into_iter();
696        let mut builder = VarBinViewBuilder::with_capacity_in(
697            DType::Binary(Nullability::Nullable),
698            iter.size_hint().0,
699            BufferAllocatorRef::statically_allocated(),
700        );
701
702        for item in iter {
703            match item {
704                None => builder.append_null(),
705                Some(v) => builder.append_value(v.as_ref()),
706            }
707        }
708
709        builder.finish_into_varbinview().into_data()
710    }
711}
712
713pub trait VarBinViewArrayExt: TypedArrayRef<VarBinView> {
714    fn dtype_parts(&self) -> (bool, Nullability) {
715        match self.dtype() {
716            DType::Utf8(nullability) => (true, *nullability),
717            DType::Binary(nullability) => (false, *nullability),
718            _ => unreachable!("VarBinViewArrayExt requires a utf8 or binary dtype"),
719        }
720    }
721
722    fn varbinview_validity(&self) -> Validity {
723        child_to_validity(self.validity_child(), self.dtype_parts().1)
724    }
725}
726impl<T: TypedArrayRef<VarBinView>> VarBinViewArrayExt for T {}
727
728impl Array<VarBinView> {
729    /// Resolve the data buffers of this array for per-row access.
730    pub fn resolved_views(&self) -> ResolvedViews<'_> {
731        ResolvedViews::new(self)
732    }
733
734    #[inline]
735    fn from_prevalidated_data(dtype: DType, data: VarBinViewData, slots: ArraySlots) -> Self {
736        let len = data.len();
737        unsafe { Array::from_parts_unchecked(ArrayParts::new(VarBinView, dtype, len, data, slots)) }
738    }
739
740    /// Construct a `VarBinViewArray` from an iterator of optional byte slices.
741    #[expect(
742        clippy::same_name_method,
743        reason = "intentionally named from_iter like Iterator::from_iter"
744    )]
745    pub fn from_iter<T: AsRef<[u8]>, I: IntoIterator<Item = Option<T>>>(
746        iter: I,
747        dtype: DType,
748    ) -> Self {
749        let iter = iter.into_iter();
750        let mut builder = VarBinViewBuilder::with_capacity_in(
751            dtype,
752            iter.size_hint().0,
753            BufferAllocatorRef::statically_allocated(),
754        );
755        for value in iter {
756            match value {
757                Some(value) => builder.append_value(value),
758                None => builder.append_null(),
759            }
760        }
761        builder.finish_into_varbinview()
762    }
763
764    pub fn from_iter_str<T: AsRef<str>, I: IntoIterator<Item = T>>(iter: I) -> Self {
765        let iter = iter.into_iter();
766        let mut builder = VarBinViewBuilder::with_capacity_in(
767            DType::Utf8(Nullability::NonNullable),
768            iter.size_hint().0,
769            BufferAllocatorRef::statically_allocated(),
770        );
771        for value in iter {
772            builder.append_value(value.as_ref());
773        }
774        builder.finish_into_varbinview()
775    }
776
777    pub fn from_iter_nullable_str<T: AsRef<str>, I: IntoIterator<Item = Option<T>>>(
778        iter: I,
779    ) -> Self {
780        let iter = iter.into_iter();
781        let mut builder = VarBinViewBuilder::with_capacity_in(
782            DType::Utf8(Nullability::Nullable),
783            iter.size_hint().0,
784            BufferAllocatorRef::statically_allocated(),
785        );
786        for value in iter {
787            match value {
788                Some(value) => builder.append_value(value.as_ref()),
789                None => builder.append_null(),
790            }
791        }
792        builder.finish_into_varbinview()
793    }
794
795    pub fn from_iter_bin<T: AsRef<[u8]>, I: IntoIterator<Item = T>>(iter: I) -> Self {
796        let iter = iter.into_iter();
797        let mut builder = VarBinViewBuilder::with_capacity_in(
798            DType::Binary(Nullability::NonNullable),
799            iter.size_hint().0,
800            BufferAllocatorRef::statically_allocated(),
801        );
802        for value in iter {
803            builder.append_value(value.as_ref());
804        }
805        builder.finish_into_varbinview()
806    }
807
808    pub fn from_iter_nullable_bin<T: AsRef<[u8]>, I: IntoIterator<Item = Option<T>>>(
809        iter: I,
810    ) -> Self {
811        let iter = iter.into_iter();
812        let mut builder = VarBinViewBuilder::with_capacity_in(
813            DType::Binary(Nullability::Nullable),
814            iter.size_hint().0,
815            BufferAllocatorRef::statically_allocated(),
816        );
817        for value in iter {
818            match value {
819                Some(value) => builder.append_value(value.as_ref()),
820                None => builder.append_null(),
821            }
822        }
823        builder.finish_into_varbinview()
824    }
825
826    /// Creates a new `VarBinViewArray`.
827    pub fn try_new(
828        views: Buffer<BinaryView>,
829        buffers: Arc<[ByteBuffer]>,
830        dtype: DType,
831        validity: Validity,
832        ctx: &mut ExecutionCtx,
833    ) -> VortexResult<Self> {
834        let data = VarBinViewData::try_new(views, buffers, dtype.clone(), validity.clone(), ctx)?;
835        let slots = VarBinViewData::make_slots(&validity, data.len());
836        Ok(Self::from_prevalidated_data(dtype, data, slots))
837    }
838
839    /// Creates a new `VarBinViewArray` without validation.
840    ///
841    /// # Safety
842    ///
843    /// See [`VarBinViewData::new_unchecked`].
844    pub unsafe fn new_unchecked(
845        views: Buffer<BinaryView>,
846        buffers: Arc<[ByteBuffer]>,
847        dtype: DType,
848        validity: Validity,
849    ) -> Self {
850        let data = unsafe {
851            VarBinViewData::new_unchecked(views, buffers, dtype.clone(), validity.clone())
852        };
853        let slots = VarBinViewData::make_slots(&validity, data.len());
854        Self::from_prevalidated_data(dtype, data, slots)
855    }
856
857    /// Creates a new `VarBinViewArray` with device or host memory.
858    pub fn new_handle(
859        views: BufferHandle,
860        buffers: Arc<[BufferHandle]>,
861        dtype: DType,
862        validity: Validity,
863    ) -> Self {
864        let data = VarBinViewData::new_handle(views, buffers, dtype.clone(), validity.clone());
865        let slots = VarBinViewData::make_slots(&validity, data.len());
866        Self::from_prevalidated_data(dtype, data, slots)
867    }
868
869    /// Construct a new array from `BufferHandle`s without validation.
870    ///
871    /// # Safety
872    ///
873    /// See [`VarBinViewData::new_handle_unchecked`].
874    pub unsafe fn new_handle_unchecked(
875        views: BufferHandle,
876        buffers: Arc<[BufferHandle]>,
877        dtype: DType,
878        validity: Validity,
879    ) -> Self {
880        let data = unsafe {
881            VarBinViewData::new_handle_unchecked(views, buffers, dtype.clone(), validity.clone())
882        };
883        let slots = VarBinViewData::make_slots(&validity, data.len());
884        Self::from_prevalidated_data(dtype, data, slots)
885    }
886
887    pub fn into_data_parts(self) -> VarBinViewDataParts {
888        let dtype = self.dtype().clone();
889        let validity = self.varbinview_validity();
890        let data = self.into_data();
891        VarBinViewDataParts {
892            dtype,
893            buffers: data.buffers,
894            views: data.views,
895            validity,
896        }
897    }
898}
899
900impl<'a> FromIterator<Option<&'a [u8]>> for VarBinViewData {
901    fn from_iter<T: IntoIterator<Item = Option<&'a [u8]>>>(iter: T) -> Self {
902        Self::from_iter_nullable_bin(iter)
903    }
904}
905
906impl FromIterator<Option<Vec<u8>>> for VarBinViewData {
907    fn from_iter<T: IntoIterator<Item = Option<Vec<u8>>>>(iter: T) -> Self {
908        Self::from_iter_nullable_bin(iter)
909    }
910}
911
912impl FromIterator<Option<String>> for VarBinViewData {
913    fn from_iter<T: IntoIterator<Item = Option<String>>>(iter: T) -> Self {
914        Self::from_iter_nullable_str(iter)
915    }
916}
917
918impl<'a> FromIterator<Option<&'a str>> for VarBinViewData {
919    fn from_iter<T: IntoIterator<Item = Option<&'a str>>>(iter: T) -> Self {
920        Self::from_iter_nullable_str(iter)
921    }
922}
923
924// --- FromIterator forwarding for Array<VarBinView> ---
925
926impl<'a> FromIterator<Option<&'a [u8]>> for Array<VarBinView> {
927    fn from_iter<T: IntoIterator<Item = Option<&'a [u8]>>>(iter: T) -> Self {
928        Self::from_iter(iter, DType::Binary(Nullability::Nullable))
929    }
930}
931
932impl FromIterator<Option<Vec<u8>>> for Array<VarBinView> {
933    fn from_iter<T: IntoIterator<Item = Option<Vec<u8>>>>(iter: T) -> Self {
934        Self::from_iter(iter, DType::Binary(Nullability::Nullable))
935    }
936}
937
938impl FromIterator<Option<String>> for Array<VarBinView> {
939    fn from_iter<T: IntoIterator<Item = Option<String>>>(iter: T) -> Self {
940        Self::from_iter_nullable_str(iter)
941    }
942}
943
944impl<'a> FromIterator<Option<&'a str>> for Array<VarBinView> {
945    fn from_iter<T: IntoIterator<Item = Option<&'a str>>>(iter: T) -> Self {
946        Self::from_iter_nullable_str(iter)
947    }
948}