Skip to main content

vortex_array/arrays/varbin/
builder.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::any::Any;
5use std::mem::MaybeUninit;
6
7use num_traits::AsPrimitive;
8use vortex_buffer::Alignment;
9use vortex_buffer::BitBufferMut;
10use vortex_buffer::BufferAllocatorRef;
11use vortex_buffer::BufferMut;
12use vortex_buffer::ByteBuffer;
13use vortex_buffer::ByteBufferMut;
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_panic;
20use vortex_mask::AllOr;
21use vortex_mask::Mask;
22
23use crate::ArrayRef;
24use crate::ArrayView;
25use crate::Canonical;
26use crate::ExecutionCtx;
27use crate::IntoArray;
28use crate::arrays::PrimitiveArray;
29use crate::arrays::VarBin;
30use crate::arrays::VarBinArray;
31use crate::arrays::VarBinView;
32use crate::arrays::varbin::VarBinArrayExt;
33use crate::arrays::varbin::VarBinArraySlotsExt;
34use crate::arrays::varbinview::VarBinViewArrayExt;
35use crate::builders::ArrayBuilder;
36use crate::dtype::DType;
37use crate::dtype::OffsetBuilderPType;
38use crate::match_each_integer_ptype;
39use crate::scalar::Scalar;
40use crate::stats::Precision;
41use crate::stats::Stat;
42use crate::validity::Validity;
43
44/// Builder for [`VarBinArray`] values with `O`-typed offsets.
45///
46/// This is the offset-based counterpart to
47/// [`VarBinViewBuilder`](crate::builders::VarBinViewBuilder): values are laid out contiguously in
48/// a single byte buffer described by a monotonically increasing offsets buffer. An `i32` or `i64`
49/// builder can therefore be handed straight to Arrow as a `Utf8`/`LargeUtf8`/`Binary`/
50/// `LargeBinary` array without re-laying out the bytes.
51///
52/// Encodings that can decode into this layout should specialize
53/// [`append_to_builder`](crate::vtable::VTable::append_to_builder) with
54/// [`match_each_varbin_builder!`](crate::match_each_varbin_builder), which recovers the concrete
55/// offset type from a `&mut dyn ArrayBuilder` so the decode loop is monomorphized over it.
56pub struct VarBinBuilder<O: OffsetBuilderPType> {
57    dtype: DType,
58    offsets: BufferMut<O>,
59    data: ByteBufferMut,
60    validity: BitBufferMut,
61}
62
63impl<O: OffsetBuilderPType> VarBinBuilder<O> {
64    /// Creates an empty builder for `dtype`.
65    #[deprecated(note = "use `new_in` with an explicit allocator")]
66    pub fn new(dtype: DType) -> Self {
67        Self::new_in(dtype, BufferAllocatorRef::static_ref())
68    }
69
70    /// Creates an empty builder for `dtype` using `allocator`.
71    pub fn new_in(dtype: DType, allocator: &BufferAllocatorRef) -> Self {
72        Self::with_capacity_in(dtype, 0, allocator)
73    }
74
75    /// Creates a builder for `dtype` with room for `capacity` values.
76    #[deprecated(note = "use `with_capacity_in` with an explicit allocator")]
77    pub fn with_capacity(dtype: DType, capacity: usize) -> Self {
78        Self::with_capacity_in(dtype, capacity, BufferAllocatorRef::static_ref())
79    }
80
81    /// Creates a builder for `dtype` with room for `capacity` values using `allocator`.
82    pub fn with_capacity_in(dtype: DType, capacity: usize, allocator: &BufferAllocatorRef) -> Self {
83        assert!(
84            matches!(dtype, DType::Utf8(_) | DType::Binary(_)),
85            "VarBinBuilder dtype must be Utf8 or Binary, got {dtype}"
86        );
87        let mut offsets = BufferMut::with_capacity_in(capacity + 1, allocator.clone());
88        offsets.push(O::zero());
89        Self {
90            dtype,
91            offsets,
92            data: BufferMut::empty_aligned_in(Alignment::of::<u8>(), allocator.clone()),
93            validity: BitBufferMut::with_capacity_in(capacity, allocator.clone()),
94        }
95    }
96
97    /// Creates a builder for `dtype` with room for `capacity` values totalling `bytes` bytes.
98    #[deprecated(note = "use `with_capacity_bytes_in` with an explicit allocator")]
99    pub fn with_capacity_bytes(dtype: DType, capacity: usize, bytes: usize) -> Self {
100        Self::with_capacity_bytes_in(dtype, capacity, bytes, BufferAllocatorRef::static_ref())
101    }
102
103    /// Creates a builder using `allocator` with room for `capacity` values and `bytes` bytes.
104    pub fn with_capacity_bytes_in(
105        dtype: DType,
106        capacity: usize,
107        bytes: usize,
108        allocator: &BufferAllocatorRef,
109    ) -> Self {
110        let mut builder = Self::with_capacity_in(dtype, capacity, allocator);
111        builder.reserve_data(bytes);
112        builder
113    }
114
115    /// Reserves room for `additional` value bytes.
116    ///
117    /// [`reserve_exact`](ArrayBuilder::reserve_exact) takes a row count and so cannot size the
118    /// value bytes; callers that know the byte total should use this to size the buffer once
119    /// instead of letting it grow.
120    pub fn reserve_data(&mut self, additional: usize) {
121        self.data.reserve(additional);
122    }
123
124    /// Appends one value, or a null when it is `None`.
125    ///
126    /// # Panics
127    ///
128    /// Panics if the resulting end offset does not fit in `O`. See
129    /// [`append_value`](Self::append_value).
130    #[inline]
131    pub fn append(&mut self, value: Option<&[u8]>) {
132        match value {
133            Some(v) => self.append_value(v),
134            None => self.push_null(),
135        }
136    }
137
138    /// Appends one non-null value.
139    ///
140    /// # Panics
141    ///
142    /// Panics if the resulting end offset does not fit in `O`. The bulk appends report that as an
143    /// error instead; use [`append_n_values`](Self::append_n_values) for a fallible single append,
144    /// or an `i64` builder for byte totals past `i32::MAX`.
145    #[inline]
146    pub fn append_value(&mut self, value: impl AsRef<[u8]>) {
147        self.push_value(value.as_ref());
148        self.validity.append_true();
149    }
150
151    /// Appends the same non-null value `n` times.
152    ///
153    /// # Errors
154    ///
155    /// Returns an error, leaving the builder unchanged, if the resulting end offsets do not fit
156    /// in `O`.
157    pub fn append_n_values(&mut self, value: impl AsRef<[u8]>, n: usize) -> VortexResult<()> {
158        let value = value.as_ref();
159        let Some(num_bytes) = value.len().checked_mul(n) else {
160            vortex_bail!("Byte count overflow: {} values of {} bytes", n, value.len());
161        };
162        // Checking the total up front is what keeps `push_value` below from panicking.
163        self.check_offset_limit(self.data.len(), num_bytes)?;
164        self.offsets.reserve(n);
165        self.data.reserve(num_bytes);
166        for _ in 0..n {
167            self.push_value(value);
168        }
169        self.validity.append_n(true, n);
170        Ok(())
171    }
172
173    /// Appends a null value.
174    ///
175    /// Unlike [`append_null`](ArrayBuilder::append_null) this does not check that the builder is
176    /// nullable; the offsets and validity stay consistent either way, and a non-nullable `dtype`
177    /// discards the validity bits on [`finish_into_varbin`](Self::finish_into_varbin).
178    #[inline]
179    pub fn push_null(&mut self) {
180        self.push_nulls(1)
181    }
182
183    /// Appends `n` null values. See [`push_null`](Self::push_null).
184    #[inline]
185    pub fn push_nulls(&mut self, n: usize) {
186        self.offsets.push_n(self.last_offset(), n);
187        self.validity.append_n(false, n);
188    }
189
190    /// Appends the same UTF-8 or binary scalar `n` times.
191    ///
192    /// # Errors
193    ///
194    /// Returns an error if `scalar` has a different dtype than the builder, or if the resulting
195    /// end offsets do not fit in `O`.
196    pub fn append_scalar_repeated(&mut self, scalar: &Scalar, n: usize) -> VortexResult<()> {
197        vortex_ensure_eq!(
198            scalar.dtype(),
199            &self.dtype,
200            "VarBinBuilder scalar dtype does not match builder dtype",
201        );
202        match &self.dtype {
203            DType::Utf8(_) => match scalar.as_utf8().value() {
204                Some(value) => self.append_n_values(value, n)?,
205                None => self.push_nulls(n),
206            },
207            DType::Binary(_) => match scalar.as_binary().value() {
208                Some(value) => self.append_n_values(value, n)?,
209                None => self.push_nulls(n),
210            },
211            dtype => {
212                vortex_bail!("VarBinBuilder cannot append scalar of dtype {dtype}")
213            }
214        }
215        Ok(())
216    }
217
218    /// Appends values from one contiguous byte buffer described by relative end offsets.
219    ///
220    /// Each entry of `end_offsets` marks the end of one value relative to the start of `values`,
221    /// and there must be exactly one per entry in `validity`.
222    #[inline]
223    pub fn append_values<P>(
224        &mut self,
225        values: &[u8],
226        end_offsets: impl Iterator<Item = P>,
227        validity: &Mask,
228    ) -> VortexResult<()>
229    where
230        P: AsPrimitive<usize>,
231        usize: AsPrimitive<O>,
232    {
233        // Offsets are committed first: they are the only fallible part, and failing before the
234        // bytes are appended leaves the builder untouched.
235        self.extend_offsets(values.len(), validity.len(), end_offsets)?;
236        self.data.extend_from_slice(values);
237        self.append_validity(validity);
238        Ok(())
239    }
240
241    /// Appends values whose bytes `decode` writes straight into the builder's byte storage.
242    ///
243    /// `decode` is handed at least `num_bytes + slack` bytes of uninitialized storage and returns
244    /// the number of bytes it initialized, which must be exactly `num_bytes`. Each entry of
245    /// `lengths` is the byte length of one value — including nulls, which are zero-length — so
246    /// there must be one per entry in `validity`.
247    ///
248    /// `slack` is spare headroom past the values themselves. It exists so that a decoder which
249    /// stores in wide fixed-size chunks can keep using them through the final value instead of
250    /// dropping into a byte-at-a-time tail; a decoder must still never write past the slice it is
251    /// handed, so `0` is correct for one that is already exact.
252    ///
253    /// Decoding in place saves staging the decoded heap in a temporary buffer and copying it in.
254    ///
255    /// `decode` is taken as a `dyn` reference so a caller that resolves the `lengths` type with
256    /// [`match_each_integer_ptype!`](crate::match_each_integer_ptype) can build the closure once
257    /// outside that match rather than inlining a whole decoder into each of its arms.
258    ///
259    /// # Errors
260    ///
261    /// Returns an error, leaving the builder unchanged, if `num_bytes` would push an offset past
262    /// what `O` can hold — checked before `decode` runs — or if `decode` reports a different byte
263    /// count than `num_bytes`, or if `lengths` does not describe those bytes.
264    ///
265    /// # Safety
266    ///
267    /// `decode` must initialize the first `n` bytes of the slice it is passed, where `n` is the
268    /// value it returns. Those bytes are published as initialized without ever being read first,
269    /// so a `decode` that over-reports leaves the builder holding uninitialized memory.
270    pub unsafe fn append_decoded<P>(
271        &mut self,
272        num_bytes: usize,
273        slack: usize,
274        lengths: &[P],
275        validity: &Mask,
276        decode: &mut dyn FnMut(&mut [MaybeUninit<u8>]) -> VortexResult<usize>,
277    ) -> VortexResult<()>
278    where
279        P: AsPrimitive<usize>,
280        usize: AsPrimitive<O>,
281    {
282        let Some(capacity) = num_bytes.checked_add(slack) else {
283            vortex_bail!("Decoded size overflow: {num_bytes} + {slack}");
284        };
285        // Checked before decoding: an `i32` builder that the decoded bytes would overflow should
286        // not pay for the decompression first.
287        self.check_offset_limit(self.data.len(), num_bytes)?;
288        self.data.reserve(capacity);
289
290        let data_len = self.data.len();
291        let written = decode(self.data.spare_capacity_mut())?;
292        vortex_ensure_eq!(
293            written,
294            num_bytes,
295            "Decoded byte count does not match expected byte count",
296        );
297
298        // The decoded bytes live in spare capacity until `set_len` below, so an invalid `lengths`
299        // still leaves the builder unchanged.
300        self.extend_offsets(num_bytes, validity.len(), prefix_sums(lengths))?;
301
302        // SAFETY: `decode` reported initializing `written` spare bytes, and the caller guarantees
303        // that report is accurate; `written == num_bytes` was checked above.
304        unsafe { self.data.set_len(data_len + num_bytes) };
305        self.append_validity(validity);
306        Ok(())
307    }
308
309    /// Appends `validity.len()` values, taking each valid row's bytes from `value`.
310    ///
311    /// `value` is called once per valid row in ascending row order and the slices it returns must
312    /// total `num_bytes` bytes. Null rows consume no bytes and repeat the preceding offset.
313    ///
314    /// The valid rows are walked a `u64` word at a time rather than pulled one at a time through
315    /// an iterator, and both buffers are sized once up front, so the copy loop costs one offset
316    /// store plus one `memcpy` per value. A caller whose values only exist as a stream can still
317    /// use this by pulling from the stream inside `value`: the rows are visited in ascending
318    /// order.
319    pub fn append_valid_slices<'a, F>(
320        &mut self,
321        num_bytes: usize,
322        validity: &Mask,
323        value: F,
324    ) -> VortexResult<()>
325    where
326        F: FnMut(usize) -> &'a [u8],
327        usize: AsPrimitive<O>,
328    {
329        let data_start = self.data.len();
330        match self.gather_valid_slices(num_bytes, validity, value) {
331            Ok(()) => {
332                self.append_validity(validity);
333                Ok(())
334            }
335            Err(error) => {
336                // The offsets are never committed on failure, so only the copied bytes need to go.
337                self.data.truncate(data_start);
338                Err(error)
339            }
340        }
341    }
342
343    /// Appends a [`VarBinArray`], reusing its offsets instead of walking its values.
344    pub fn append_varbin(
345        &mut self,
346        array: ArrayView<'_, VarBin>,
347        ctx: &mut ExecutionCtx,
348    ) -> VortexResult<()>
349    where
350        usize: AsPrimitive<O>,
351    {
352        let offsets = array.offsets().clone().execute::<PrimitiveArray>(ctx)?;
353        let bytes: ByteBuffer = array.sliced_bytes(ctx);
354        let validity = array
355            .varbin_validity()
356            .execute_mask(array.as_ref().len(), ctx)?;
357        match_each_integer_ptype!(offsets.ptype(), |P| {
358            let offsets = offsets.as_slice::<P>();
359            let first: usize = offsets[0].as_();
360            self.append_values(
361                bytes.as_slice(),
362                // Wrapping keeps a corrupt offsets child from panicking here; `append_values`
363                // rejects the resulting non-monotonic offsets.
364                offsets[1..]
365                    .iter()
366                    .map(|offset| AsPrimitive::<usize>::as_(*offset).wrapping_sub(first)),
367                &validity,
368            )
369        })
370    }
371
372    /// Appends a [`VarBinViewArray`](crate::arrays::VarBinViewArray), compacting its values.
373    pub fn append_varbinview(
374        &mut self,
375        array: ArrayView<'_, VarBinView>,
376        ctx: &mut ExecutionCtx,
377    ) -> VortexResult<()>
378    where
379        usize: AsPrimitive<O>,
380    {
381        let len = array.as_ref().len();
382        let validity = array.varbinview_validity().execute_mask(len, ctx)?;
383
384        // Resolve the views slice and the data buffers once. Reading them per row costs a buffer
385        // handle clone, and the byte total needs only the fixed-width view headers.
386        let views = array.views();
387        let buffers = array
388            .data_buffers()
389            .iter()
390            .map(|buffer| buffer.as_host().as_slice())
391            .collect::<Vec<_>>();
392
393        let num_bytes = match validity.bit_buffer() {
394            AllOr::All => views.iter().map(|view| view.len() as usize).sum(),
395            AllOr::None => 0,
396            AllOr::Some(bits) => {
397                let mut total = 0;
398                bits.for_each_set_index(|index| total += views[index].len() as usize);
399                total
400            }
401        };
402
403        self.append_valid_slices(num_bytes, &validity, |index| views[index].bytes(&buffers))
404    }
405
406    /// Finishes the appended values into a [`VarBinArray`] and resets the builder.
407    pub fn finish_into_varbin(&mut self) -> VarBinArray {
408        assert_eq!(
409            self.offsets.len() - 1,
410            self.validity.len(),
411            "The offset count must be one more than the validity length"
412        );
413
414        let offsets = self.offsets.take();
415        self.offsets.push(O::zero());
416        // SAFETY: a non-nullable validity carries no length to match against the offsets.
417        let offsets =
418            unsafe { PrimitiveArray::new_unchecked(offsets.freeze(), Validity::NonNullable) };
419        let data = self.data.take();
420        let nulls = self.validity.take().freeze();
421
422        let validity = Validity::from_bit_buffer(nulls, self.dtype.nullability());
423
424        // The builder adds offsets in monotonically increasing order. Store this statistic to
425        // prevent VarBinArray::validate from recomputing it after deserialization.
426        debug_assert!(
427            offsets.as_slice::<O>().is_sorted(),
428            "VarBinBuilder offsets must be sorted"
429        );
430        offsets
431            .statistics()
432            .set(Stat::IsSorted, Precision::Exact(true.into()));
433
434        // SAFETY: The builder maintains all invariants:
435        // - Offsets are monotonically increasing starting from 0 (guaranteed by builder logic).
436        // - Bytes buffer contains exactly the data referenced by offsets.
437        // - Validity matches the dtype nullability.
438        // - UTF-8 validity is ensured by the caller when using DType::Utf8.
439        unsafe {
440            VarBinArray::new_unchecked(
441                offsets.into_array(),
442                data.freeze(),
443                self.dtype.clone(),
444                validity,
445            )
446        }
447    }
448
449    #[inline]
450    fn last_offset(&self) -> O {
451        self.offsets[self.offsets.len() - 1]
452    }
453
454    /// Appends `value`'s bytes and its end offset, leaving the validity bits to the caller.
455    #[inline]
456    fn push_value(&mut self, value: &[u8]) {
457        self.offsets
458            .push(O::from(self.data.len() + value.len()).unwrap_or_else(|| {
459                offset_overflow(self.data.len(), value.len(), std::any::type_name::<O>())
460            }));
461        self.data.extend_from_slice(value);
462    }
463
464    fn append_validity(&mut self, validity: &Mask) {
465        match validity {
466            Mask::AllTrue(len) => self.validity.append_n(true, *len),
467            Mask::AllFalse(len) => self.validity.append_n(false, *len),
468            Mask::Values(values) => self.validity.append_buffer(values.bit_buffer()),
469        }
470    }
471
472    /// Appends `count` end offsets derived from `end_offsets`, shifted past the current data end.
473    ///
474    /// `end_offsets` must be monotonically non-decreasing and end at exactly `num_bytes`. Offsets
475    /// are written through the reserved spare capacity and committed with a single `set_len`, so a
476    /// rejected input leaves the buffer untouched and the caller can propagate the error.
477    fn extend_offsets<P>(
478        &mut self,
479        num_bytes: usize,
480        count: usize,
481        end_offsets: impl Iterator<Item = P>,
482    ) -> VortexResult<()>
483    where
484        P: AsPrimitive<usize>,
485        usize: AsPrimitive<O>,
486    {
487        let data_start = self.data.len();
488        let offsets_len = self.offsets.len();
489        self.check_offset_limit(data_start, num_bytes)?;
490        self.offsets.reserve(count);
491
492        // Writing into the spare capacity keeps the output cursor in a register: `push` rewrites
493        // the buffer length on every value, which the optimizer cannot hoist out of the loop.
494        let spare = &mut self.offsets.spare_capacity_mut()[..count];
495        let mut end_offsets = end_offsets;
496        let mut previous = 0usize;
497        for slot in spare.iter_mut() {
498            let Some(end) = end_offsets.next() else {
499                vortex_bail!("End offset count is less than the validity length {count}");
500            };
501            let end = end.as_();
502            vortex_ensure!(
503                end >= previous && end <= num_bytes,
504                "End offsets must be monotonically increasing within {num_bytes} bytes, \
505                 got {end} after {previous}"
506            );
507            slot.write((data_start + end).as_());
508            previous = end;
509        }
510        vortex_ensure!(
511            end_offsets.next().is_none(),
512            "End offset count exceeds the validity length {count}"
513        );
514        vortex_ensure_eq!(
515            previous,
516            num_bytes,
517            "Final end offset does not match the value byte count",
518        );
519
520        // SAFETY: the loop initialized the first `count` spare slots.
521        unsafe { self.offsets.set_len(offsets_len + count) };
522        Ok(())
523    }
524
525    /// Copies each valid row's bytes from `value` into the byte storage and records the offsets.
526    /// See [`append_valid_slices`](Self::append_valid_slices); the validity bits are the caller's
527    /// job so that a failure here can be unwound.
528    fn gather_valid_slices<'a, F>(
529        &mut self,
530        num_bytes: usize,
531        validity: &Mask,
532        mut value: F,
533    ) -> VortexResult<()>
534    where
535        F: FnMut(usize) -> &'a [u8],
536        usize: AsPrimitive<O>,
537    {
538        let count = validity.len();
539        let data_start = self.data.len();
540        let offsets_len = self.offsets.len();
541        self.check_offset_limit(data_start, num_bytes)?;
542        self.offsets.reserve(count);
543        self.data.reserve(num_bytes);
544
545        // Disjoint field borrows: the offsets spare capacity stays valid while the byte buffer
546        // grows, since the two are separate allocations.
547        let Self { offsets, data, .. } = self;
548        let spare = &mut offsets.spare_capacity_mut()[..count];
549
550        match validity.bit_buffer() {
551            AllOr::All => {
552                for (row, slot) in spare.iter_mut().enumerate() {
553                    data.extend_from_slice(value(row));
554                    slot.write(data.len().as_());
555                }
556            }
557            AllOr::None => {
558                spare.fill(MaybeUninit::new(data_start.as_()));
559            }
560            AllOr::Some(bits) => {
561                let mut row = 0;
562                bits.for_each_set_index(|index| {
563                    // Null rows between the previous valid row and this one repeat its end offset.
564                    spare[row..index].fill(MaybeUninit::new(data.len().as_()));
565                    data.extend_from_slice(value(index));
566                    spare[index].write(data.len().as_());
567                    row = index + 1;
568                });
569                spare[row..].fill(MaybeUninit::new(data.len().as_()));
570            }
571        }
572
573        // A caller whose slices overrun `num_bytes` only grows the byte buffer past the reservation,
574        // so the overrun is caught here rather than per value. The offsets are still uncommitted, so
575        // rejecting it now leaves them untouched.
576        vortex_ensure_eq!(
577            data.len(),
578            data_start + num_bytes,
579            "Value slices byte count does not match expected byte count",
580        );
581
582        // SAFETY: every branch above initialized all `count` spare slots.
583        unsafe { self.offsets.set_len(offsets_len + count) };
584        Ok(())
585    }
586
587    /// Checks that an offset past `num_bytes` more bytes is representable as an `O`.
588    fn check_offset_limit(&self, data_start: usize, num_bytes: usize) -> VortexResult<()> {
589        let Some(limit) = data_start.checked_add(num_bytes) else {
590            vortex_bail!("Byte offset overflow: {data_start} + {num_bytes}");
591        };
592        vortex_ensure!(
593            u64::try_from(limit).is_ok_and(|limit| limit <= O::max_value_as_u64()),
594            "Byte offset {limit} does not fit in {}",
595            std::any::type_name::<O>()
596        );
597        Ok(())
598    }
599}
600
601impl<O: OffsetBuilderPType> ArrayBuilder for VarBinBuilder<O> {
602    fn as_any(&self) -> &dyn Any {
603        self
604    }
605
606    fn as_any_mut(&mut self) -> &mut dyn Any {
607        self
608    }
609
610    fn dtype(&self) -> &DType {
611        &self.dtype
612    }
613
614    fn len(&self) -> usize {
615        self.validity.len()
616    }
617
618    fn append_zeros(&mut self, n: usize) {
619        self.offsets.push_n(self.last_offset(), n);
620        self.validity.append_n(true, n);
621    }
622
623    unsafe fn append_nulls_unchecked(&mut self, n: usize) {
624        self.push_nulls(n);
625    }
626
627    fn append_scalar(&mut self, scalar: &Scalar) -> VortexResult<()> {
628        self.append_scalar_repeated(scalar, 1)
629    }
630
631    fn reserve_exact(&mut self, additional: usize) {
632        self.offsets.reserve(additional);
633        self.validity.reserve(additional);
634    }
635
636    fn finish(&mut self) -> ArrayRef {
637        self.finish_into_varbin().into_array()
638    }
639
640    fn finish_into_canonical(&mut self, ctx: &mut ExecutionCtx) -> Canonical {
641        self.finish()
642            .execute::<Canonical>(ctx)
643            .vortex_expect("varbin builder should canonicalize")
644    }
645}
646
647/// Recovers a concrete [`VarBinBuilder`] from a `&mut dyn ArrayBuilder`.
648///
649/// Evaluates to `Some($body)` with `$typed` bound to the `&mut VarBinBuilder<O>` when the builder
650/// is one, and `None` otherwise, so an encoding can fall through to its other output paths:
651///
652/// ```ignore
653/// if let Some(result) = match_each_varbin_builder!(builder, |builder| {
654///     append_my_encoding(array, builder, ctx)
655/// }) {
656///     return result;
657/// }
658/// ```
659#[macro_export]
660macro_rules! match_each_varbin_builder {
661    ($builder:expr, | $typed:ident | $body:expr) => {
662        $crate::__match_varbin_builder_widths!($builder, |$typed| $body, [u32, u64, i32, i64])
663    };
664}
665
666/// Expands `$body` once per listed offset width, guarded by a downcast. See
667/// [`match_each_varbin_builder!`].
668#[doc(hidden)]
669#[macro_export]
670macro_rules! __match_varbin_builder_widths {
671    ($builder:expr, | $typed:ident | $body:expr, [$($width:ty),+ $(,)?]) => {{
672        let __varbin_builder: &mut dyn $crate::builders::ArrayBuilder = $builder;
673        $crate::__match_varbin_builder_arms!(__varbin_builder, |$typed| $body, [$($width),+])
674    }};
675}
676
677/// The `if`/`else if` chain behind [`__match_varbin_builder_widths!`], one arm per width.
678#[doc(hidden)]
679#[macro_export]
680macro_rules! __match_varbin_builder_arms {
681    ($builder:expr, | $typed:ident | $body:expr, []) => {
682        None
683    };
684    ($builder:expr, | $typed:ident | $body:expr, [$head:ty $(, $tail:ty)*]) => {
685        if $builder
686            .as_any()
687            .is::<$crate::builders::VarBinBuilder<$head>>()
688        {
689            let $typed = match $builder
690                .as_any_mut()
691                .downcast_mut::<$crate::builders::VarBinBuilder<$head>>()
692            {
693                Some(typed) => typed,
694                None => unreachable!("builder type checked above"),
695            };
696            Some($body)
697        } else {
698            $crate::__match_varbin_builder_arms!($builder, |$typed| $body, [$($tail),*])
699        }
700    };
701}
702
703#[cold]
704#[inline(never)]
705fn offset_overflow(data_len: usize, value_len: usize, offset_type: &'static str) -> ! {
706    vortex_panic!(
707        "Failed to convert sum of {data_len} and {value_len} to offset of type {offset_type}"
708    )
709}
710
711/// Running totals of `lengths`, wrapping so a corrupt lengths child is rejected rather than
712/// panicking; [`VarBinBuilder::extend_offsets`] catches the resulting non-monotonic offsets.
713#[inline]
714fn prefix_sums<P: AsPrimitive<usize>>(lengths: &[P]) -> impl Iterator<Item = usize> {
715    lengths.iter().scan(0usize, |end, length| {
716        *end = end.wrapping_add(length.as_());
717        Some(*end)
718    })
719}
720
721#[cfg(test)]
722mod tests {
723    use std::mem::MaybeUninit;
724    use std::sync::LazyLock;
725
726    use rstest::rstest;
727    use vortex_error::VortexResult;
728    use vortex_mask::Mask;
729    use vortex_session::VortexSession;
730
731    use crate::IntoArray;
732    use crate::VortexSessionExecute;
733    use crate::arrays::ConstantArray;
734    use crate::arrays::VarBinArray;
735    use crate::arrays::VarBinViewArray;
736    use crate::arrays::varbin::VarBinArraySlotsExt;
737    use crate::arrays::varbin::builder::VarBinBuilder;
738    use crate::assert_arrays_eq;
739    use crate::builders::ArrayBuilder;
740    use crate::dtype::DType;
741    use crate::dtype::Nullability::Nullable;
742    use crate::scalar::Scalar;
743    use crate::stats::Precision;
744    use crate::stats::Stat;
745    use crate::stats::StatsProviderExt;
746
747    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
748
749    #[test]
750    fn test_builder() {
751        let mut builder = VarBinBuilder::<i32>::with_capacity_in(
752            DType::Utf8(Nullable),
753            0,
754            vortex_buffer::BufferAllocatorRef::static_ref(),
755        );
756        builder.append(Some(b"hello"));
757        builder.append(None);
758        builder.append(Some(b"world"));
759        let array = builder.finish_into_varbin();
760
761        assert_eq!(array.len(), 3);
762        assert_eq!(array.dtype().nullability(), Nullable);
763        assert_eq!(
764            array
765                .execute_scalar(0, &mut SESSION.create_execution_ctx())
766                .unwrap(),
767            Scalar::utf8("hello".to_string(), Nullable)
768        );
769        assert!(
770            array
771                .execute_scalar(1, &mut SESSION.create_execution_ctx())
772                .unwrap()
773                .is_null()
774        );
775        assert_arrays_eq!(
776            array,
777            VarBinViewArray::from_iter_nullable_str([Some("hello"), None, Some("world")]),
778            &mut SESSION.create_execution_ctx()
779        );
780    }
781
782    #[rstest]
783    #[case(false)]
784    #[case(true)]
785    fn test_append_varbin_to_builder(#[case] large_offsets: bool) -> VortexResult<()> {
786        let source = VarBinArray::from_iter(
787            [
788                Some("prefix"),
789                Some("hello"),
790                None,
791                Some("world"),
792                Some("suffix"),
793            ],
794            DType::Utf8(Nullable),
795        )
796        .into_array()
797        .slice(1..4)?;
798        let mut ctx = SESSION.create_execution_ctx();
799
800        let actual = with_offsets(large_offsets, source.dtype().clone(), |builder| {
801            source.append_to_builder(builder, &mut ctx)
802        })?;
803
804        assert_arrays_eq!(
805            actual,
806            VarBinViewArray::from_iter_nullable_str([Some("hello"), None, Some("world")]),
807            &mut ctx
808        );
809        Ok(())
810    }
811
812    #[test]
813    fn append_n_values_offset_overflow_returns_error() {
814        let mut builder = VarBinBuilder::<i32>::new_in(
815            DType::Utf8(Nullable),
816            vortex_buffer::BufferAllocatorRef::static_ref(),
817        );
818
819        // The limit is checked before anything is reserved, so the huge byte total is free.
820        let result = builder.append_n_values(b"hello", i32::MAX as usize / 5 + 1);
821
822        assert!(result.is_err());
823        assert_eq!(builder.offsets.len(), 1);
824        assert!(builder.data.is_empty());
825        assert_eq!(builder.validity.len(), 0);
826    }
827
828    #[test]
829    fn append_values_rejects_a_short_offset_count() {
830        let mut builder = VarBinBuilder::<i32>::new_in(
831            DType::Utf8(Nullable),
832            vortex_buffer::BufferAllocatorRef::static_ref(),
833        );
834
835        let result = builder.append_values(b"ab", [1usize, 2].into_iter(), &Mask::new_true(3));
836
837        assert!(result.is_err());
838        assert_eq!(builder.offsets.len(), 1);
839        assert!(builder.data.is_empty());
840    }
841
842    #[test]
843    fn append_values_rejects_non_monotonic_offsets() {
844        let mut builder = VarBinBuilder::<i32>::new_in(
845            DType::Utf8(Nullable),
846            vortex_buffer::BufferAllocatorRef::static_ref(),
847        );
848
849        let result = builder.append_values(b"ab", [2usize, 1].into_iter(), &Mask::new_true(2));
850
851        assert!(result.is_err());
852        assert_eq!(builder.offsets.len(), 1);
853    }
854
855    #[test]
856    fn append_decoded_writes_into_the_builder_storage() -> VortexResult<()> {
857        let mut ctx = SESSION.create_execution_ctx();
858        let mut builder = VarBinBuilder::<i32>::new_in(
859            DType::Utf8(Nullable),
860            vortex_buffer::BufferAllocatorRef::static_ref(),
861        );
862
863        // SAFETY: the closure initializes exactly the 6 bytes it reports.
864        unsafe {
865            builder.append_decoded(
866                6,
867                4,
868                &[3usize, 0, 3],
869                &Mask::from_iter([true, false, true]),
870                &mut |spare: &mut [MaybeUninit<u8>]| {
871                    for (slot, byte) in spare.iter_mut().zip(b"foobar") {
872                        slot.write(*byte);
873                    }
874                    Ok(6)
875                },
876            )?;
877        }
878
879        let expected =
880            VarBinViewArray::from_iter([Some("foo"), None, Some("bar")], DType::Utf8(Nullable));
881        assert_arrays_eq!(builder.finish_into_varbin(), expected, &mut ctx);
882        Ok(())
883    }
884
885    /// The offset width has to be checked before `decode` runs: an overflowing `i32` builder
886    /// should not pay for a full decompression first.
887    #[test]
888    fn append_decoded_rejects_an_offset_overflow_without_decoding() {
889        let mut builder = VarBinBuilder::<i32>::new_in(
890            DType::Utf8(Nullable),
891            vortex_buffer::BufferAllocatorRef::static_ref(),
892        );
893        let num_bytes = i32::MAX as usize + 1;
894        let mut decoded = false;
895
896        // SAFETY: the closure is never called, and reports only what it initializes if it were.
897        let result = unsafe {
898            builder.append_decoded(num_bytes, 0, &[num_bytes], &Mask::new_true(1), &mut |_| {
899                decoded = true;
900                Ok(0)
901            })
902        };
903
904        assert!(result.is_err());
905        assert!(!decoded, "decode ran before the offset width was checked");
906        assert_eq!(builder.offsets.len(), 1);
907        assert_eq!(builder.validity.len(), 0);
908    }
909
910    /// `append_scalar_repeated` reports an offset overflow rather than panicking, so a constant
911    /// column wider than the offset type errors like the bulk appends do.
912    #[test]
913    fn append_scalar_repeated_rejects_an_offset_overflow() {
914        let mut builder = VarBinBuilder::<i32>::new_in(
915            DType::Utf8(Nullable),
916            vortex_buffer::BufferAllocatorRef::static_ref(),
917        );
918
919        let result = builder
920            .append_scalar_repeated(&Scalar::utf8("hello", Nullable), i32::MAX as usize / 5 + 1);
921
922        assert!(result.is_err());
923        assert_eq!(builder.offsets.len(), 1);
924        assert!(builder.data.is_empty());
925        assert_eq!(builder.validity.len(), 0);
926    }
927
928    #[test]
929    fn append_decoded_rejects_a_short_decode() {
930        let mut builder = VarBinBuilder::<i32>::new_in(
931            DType::Utf8(Nullable),
932            vortex_buffer::BufferAllocatorRef::static_ref(),
933        );
934
935        // SAFETY: the closure initializes the 3 bytes it reports (none, and it reports 3 — but the
936        // length mismatch is rejected before anything is published).
937        let result = unsafe {
938            builder.append_decoded(6, 0, &[3usize, 3], &Mask::new_true(2), &mut |spare| {
939                spare[..3].fill(MaybeUninit::new(b'x'));
940                Ok(3)
941            })
942        };
943
944        assert!(result.is_err());
945        assert_eq!(builder.offsets.len(), 1);
946        assert_eq!(builder.validity.len(), 0);
947    }
948
949    /// Slices that overrun the declared byte count are rejected, and the builder is left exactly
950    /// as it was — the overrun bytes are copied before the total can be checked, so the unwind has
951    /// to put them back.
952    #[rstest]
953    #[case::all_valid(Mask::new_true(2))]
954    #[case::some_valid(Mask::from_iter([true, false, true]))]
955    fn append_valid_slices_rejects_a_byte_count_mismatch(#[case] validity: Mask) {
956        let mut builder = VarBinBuilder::<i32>::new_in(
957            DType::Utf8(Nullable),
958            vortex_buffer::BufferAllocatorRef::static_ref(),
959        );
960        let values = [b"foo".as_slice(), b"quux".as_slice()];
961
962        let mut next = 0;
963        let result = builder.append_valid_slices(6, &validity, |_| {
964            next += 1;
965            values[next - 1]
966        });
967
968        assert!(result.is_err());
969        assert_eq!(builder.offsets.len(), 1);
970        assert!(builder.data.is_empty());
971        assert_eq!(builder.validity.len(), 0);
972    }
973
974    #[test]
975    #[should_panic(expected = "The offset count must be one more than the validity length")]
976    fn finish_rejects_mismatched_validity() {
977        let mut builder = VarBinBuilder::<i32>::new_in(
978            DType::Utf8(Nullable),
979            vortex_buffer::BufferAllocatorRef::static_ref(),
980        );
981        builder.validity.append_true();
982        drop(builder.finish_into_varbin());
983    }
984
985    #[rstest]
986    #[case(false)]
987    #[case(true)]
988    fn test_array_builder_methods(#[case] large_offsets: bool) -> VortexResult<()> {
989        let mut ctx = SESSION.create_execution_ctx();
990        let result = with_offsets(large_offsets, DType::Utf8(Nullable), |builder| {
991            builder.reserve_exact(3);
992            builder.append_zero();
993            builder.append_scalar(&Scalar::utf8("hello", Nullable))?;
994            builder.append_null();
995            assert_eq!(builder.len(), 3);
996            Ok(())
997        })?;
998
999        assert_eq!(
1000            result.validity()?.execute_mask(3, &mut ctx)?,
1001            Mask::from_iter([true, true, false])
1002        );
1003        assert_arrays_eq!(
1004            result,
1005            VarBinViewArray::from_iter_nullable_str([Some(""), Some("hello"), None]),
1006            &mut ctx
1007        );
1008        Ok(())
1009    }
1010
1011    #[rstest]
1012    #[case(false)]
1013    #[case(true)]
1014    fn test_append_varbinview_validity_to_builder(#[case] large_offsets: bool) -> VortexResult<()> {
1015        let long = "a value that does not fit inline";
1016        let all_null = VarBinViewArray::from_iter([None::<&str>, None], DType::Utf8(Nullable));
1017        let mixed =
1018            VarBinViewArray::from_iter([Some("hello"), None, Some(long)], DType::Utf8(Nullable));
1019        let expected = VarBinViewArray::from_iter(
1020            [None, None, Some("hello"), None, Some(long)],
1021            DType::Utf8(Nullable),
1022        );
1023        let mut ctx = SESSION.create_execution_ctx();
1024
1025        let actual = with_offsets(large_offsets, expected.dtype().clone(), |builder| {
1026            all_null
1027                .clone()
1028                .into_array()
1029                .append_to_builder(builder, &mut ctx)?;
1030            mixed
1031                .clone()
1032                .into_array()
1033                .append_to_builder(builder, &mut ctx)
1034        })?;
1035
1036        assert_arrays_eq!(actual, expected, &mut ctx);
1037        Ok(())
1038    }
1039
1040    /// `match_each_varbin_builder!` covers every offset width a `VarBinBuilder` can be built with,
1041    /// so both canonical appends must reach their specialization for all of them. A macro that
1042    /// only matched the signed pair would send an unsigned builder down a downcast that assumes
1043    /// `VarBinViewBuilder` and panic.
1044    #[rstest]
1045    #[case::u32(VarBinBuilder::<u32>::new_in(DType::Utf8(Nullable), vortex_buffer::BufferAllocatorRef::static_ref()))]
1046    #[case::u64(VarBinBuilder::<u64>::new_in(DType::Utf8(Nullable), vortex_buffer::BufferAllocatorRef::static_ref()))]
1047    #[case::i32(VarBinBuilder::<i32>::new_in(DType::Utf8(Nullable), vortex_buffer::BufferAllocatorRef::static_ref()))]
1048    #[case::i64(VarBinBuilder::<i64>::new_in(DType::Utf8(Nullable), vortex_buffer::BufferAllocatorRef::static_ref()))]
1049    fn append_to_every_offset_width(#[case] mut builder: impl ArrayBuilder) -> VortexResult<()> {
1050        let mut ctx = SESSION.create_execution_ctx();
1051        let long = "a string that is far too long to be inlined in a view";
1052        let values = [Some("hello"), None, Some(long), Some("")];
1053
1054        let view = VarBinViewArray::from_iter(values, DType::Utf8(Nullable)).into_array();
1055        let varbin = VarBinArray::from_iter(values, DType::Utf8(Nullable)).into_array();
1056        let constant = ConstantArray::new(Scalar::from("hello").into_nullable(), 2).into_array();
1057
1058        for chunk in [&view, &varbin, &constant] {
1059            chunk.append_to_builder(&mut builder, &mut ctx)?;
1060        }
1061
1062        let expected = VarBinViewArray::from_iter_nullable_str([
1063            Some("hello"),
1064            None,
1065            Some(long),
1066            Some(""),
1067            Some("hello"),
1068            None,
1069            Some(long),
1070            Some(""),
1071            Some("hello"),
1072            Some("hello"),
1073        ]);
1074        assert_arrays_eq!(builder.finish(), expected, &mut ctx);
1075        Ok(())
1076    }
1077
1078    #[test]
1079    fn offsets_have_is_sorted_stat() -> VortexResult<()> {
1080        let mut builder = VarBinBuilder::<i32>::with_capacity_in(
1081            DType::Utf8(Nullable),
1082            0,
1083            vortex_buffer::BufferAllocatorRef::static_ref(),
1084        );
1085        builder.append_value(b"aaa");
1086        builder.push_null();
1087        builder.append_value(b"bbb");
1088        let array = builder.finish_into_varbin();
1089
1090        let is_sorted = array
1091            .offsets()
1092            .statistics()
1093            .with_typed_stats_set(|s| s.get_as::<bool>(Stat::IsSorted));
1094        assert_eq!(is_sorted, Precision::Exact(true));
1095        Ok(())
1096    }
1097
1098    #[test]
1099    fn empty_builder_offsets_have_is_sorted_stat() -> VortexResult<()> {
1100        let mut builder = VarBinBuilder::<i32>::new_in(
1101            DType::Utf8(Nullable),
1102            vortex_buffer::BufferAllocatorRef::static_ref(),
1103        );
1104        let array = builder.finish_into_varbin();
1105
1106        let is_sorted = array
1107            .offsets()
1108            .statistics()
1109            .with_typed_stats_set(|s| s.get_as::<bool>(Stat::IsSorted));
1110        assert_eq!(is_sorted, Precision::Exact(true));
1111        Ok(())
1112    }
1113
1114    /// Runs `f` against an `i32` or `i64` builder and returns the finished array.
1115    fn with_offsets(
1116        large_offsets: bool,
1117        dtype: DType,
1118        f: impl FnOnce(&mut dyn ArrayBuilder) -> VortexResult<()>,
1119    ) -> VortexResult<VarBinArray> {
1120        if large_offsets {
1121            let mut builder = VarBinBuilder::<i64>::with_capacity_in(
1122                dtype,
1123                8,
1124                vortex_buffer::BufferAllocatorRef::static_ref(),
1125            );
1126            f(&mut builder)?;
1127            Ok(builder.finish_into_varbin())
1128        } else {
1129            let mut builder = VarBinBuilder::<i32>::with_capacity_in(
1130                dtype,
1131                8,
1132                vortex_buffer::BufferAllocatorRef::static_ref(),
1133            );
1134            f(&mut builder)?;
1135            Ok(builder.finish_into_varbin())
1136        }
1137    }
1138}