Skip to main content

vortex_array/builders/
varbinview.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::any::Any;
5use std::ops::Range;
6use std::sync::Arc;
7
8use itertools::Itertools;
9use num_traits::AsPrimitive;
10use vortex_buffer::Alignment;
11use vortex_buffer::Buffer;
12use vortex_buffer::BufferAllocatorRef;
13use vortex_buffer::BufferMut;
14use vortex_buffer::ByteBuffer;
15use vortex_buffer::ByteBufferMut;
16use vortex_error::VortexExpect;
17use vortex_error::VortexResult;
18use vortex_error::vortex_bail;
19use vortex_error::vortex_ensure_eq;
20use vortex_mask::AllOr;
21use vortex_mask::Mask;
22use vortex_mask::MaskValues;
23use vortex_utils::aliases::hash_map::Entry;
24use vortex_utils::aliases::hash_map::HashMap;
25
26use crate::ArrayRef;
27use crate::ExecutionCtx;
28use crate::IntoArray;
29use crate::array::ArrayView;
30use crate::arrays::VarBinView;
31use crate::arrays::VarBinViewArray;
32use crate::arrays::filter::append_filtered_slice;
33use crate::arrays::varbinview::VarBinViewArrayExt;
34use crate::arrays::varbinview::build_views::BinaryView;
35use crate::arrays::varbinview::build_views::MAX_BUFFER_LEN;
36use crate::arrays::varbinview::build_views::extend_views;
37use crate::arrays::varbinview::compact::BufferUtilization;
38use crate::arrays::varbinview::compact::VarBinViewCompactExt;
39use crate::builders::ArrayBuilder;
40use crate::builders::LazyBitBufferBuilder;
41use crate::canonical::Canonical;
42use crate::dtype::DType;
43use crate::dtype::NativePType;
44use crate::scalar::Scalar;
45
46/// The builder for building a [`VarBinViewArray`].
47pub struct VarBinViewBuilder {
48    dtype: DType,
49    views_builder: BufferMut<BinaryView>,
50    nulls: LazyBitBufferBuilder,
51    completed: CompletedBuffers,
52    in_progress: Option<ByteBufferMut>,
53    growth_strategy: BufferGrowthStrategy,
54    compaction_threshold: f64,
55    allocator: BufferAllocatorRef,
56}
57
58impl VarBinViewBuilder {
59    /// Creates a builder with room for `capacity` values.
60    #[deprecated(note = "use `with_capacity_in` with an explicit allocator")]
61    pub fn with_capacity(dtype: DType, capacity: usize) -> Self {
62        Self::with_capacity_in(dtype, capacity, BufferAllocatorRef::statically_allocated())
63    }
64
65    /// Creates a builder with room for `capacity` values using `allocator`.
66    pub fn with_capacity_in(dtype: DType, capacity: usize, allocator: BufferAllocatorRef) -> Self {
67        Self::new_in(
68            dtype,
69            capacity,
70            Default::default(),
71            Default::default(),
72            0.0,
73            allocator,
74        )
75    }
76
77    /// Creates a builder that deduplicates completed buffers.
78    #[deprecated(note = "use `with_buffer_deduplication_in` with an explicit allocator")]
79    pub fn with_buffer_deduplication(dtype: DType, capacity: usize) -> Self {
80        Self::with_buffer_deduplication_in(
81            dtype,
82            capacity,
83            BufferAllocatorRef::statically_allocated(),
84        )
85    }
86
87    /// Creates a builder that deduplicates completed buffers using `allocator`.
88    pub fn with_buffer_deduplication_in(
89        dtype: DType,
90        capacity: usize,
91        allocator: BufferAllocatorRef,
92    ) -> Self {
93        Self::new_in(
94            dtype,
95            capacity,
96            CompletedBuffers::Deduplicated(Default::default()),
97            Default::default(),
98            0.0,
99            allocator,
100        )
101    }
102
103    /// Creates a builder that compacts buffers below `compaction_threshold` utilization.
104    #[deprecated(note = "use `with_compaction_in` with an explicit allocator")]
105    pub fn with_compaction(dtype: DType, capacity: usize, compaction_threshold: f64) -> Self {
106        Self::with_compaction_in(
107            dtype,
108            capacity,
109            compaction_threshold,
110            BufferAllocatorRef::statically_allocated(),
111        )
112    }
113
114    /// Creates a compacting builder using `allocator`.
115    pub fn with_compaction_in(
116        dtype: DType,
117        capacity: usize,
118        compaction_threshold: f64,
119        allocator: BufferAllocatorRef,
120    ) -> Self {
121        Self::new_in(
122            dtype,
123            capacity,
124            Default::default(),
125            Default::default(),
126            compaction_threshold,
127            allocator,
128        )
129    }
130
131    /// Creates a builder with explicit buffer policies.
132    #[deprecated(note = "use `new_in` with an explicit allocator")]
133    pub fn new(
134        dtype: DType,
135        capacity: usize,
136        completed: CompletedBuffers,
137        growth_strategy: BufferGrowthStrategy,
138        compaction_threshold: f64,
139    ) -> Self {
140        Self::new_in(
141            dtype,
142            capacity,
143            completed,
144            growth_strategy,
145            compaction_threshold,
146            BufferAllocatorRef::statically_allocated(),
147        )
148    }
149
150    /// Creates a builder with explicit buffer policies and `allocator`.
151    pub fn new_in(
152        dtype: DType,
153        capacity: usize,
154        completed: CompletedBuffers,
155        growth_strategy: BufferGrowthStrategy,
156        compaction_threshold: f64,
157        allocator: BufferAllocatorRef,
158    ) -> Self {
159        assert!(
160            matches!(dtype, DType::Utf8(_) | DType::Binary(_)),
161            "VarBinViewBuilder DType must be Utf8 or Binary."
162        );
163        Self {
164            views_builder: BufferMut::with_capacity_preferred_aligned_in(
165                capacity,
166                Alignment::of::<BinaryView>(),
167                None,
168                allocator.clone(),
169            ),
170            nulls: LazyBitBufferBuilder::new(capacity, allocator.clone()),
171            completed,
172            in_progress: None,
173            dtype,
174            growth_strategy,
175            compaction_threshold,
176            allocator,
177        }
178    }
179
180    fn append_value_view(&mut self, value: &[u8]) {
181        let length =
182            u32::try_from(value.len()).vortex_expect("cannot have a single string >2^32 in length");
183        if length <= 12 {
184            self.views_builder.push(BinaryView::make_view(value, 0, 0));
185            return;
186        }
187
188        let (buffer_idx, offset) = self.append_value_to_buffer(value);
189        let view = BinaryView::make_view(value, buffer_idx, offset);
190        self.views_builder.push(view);
191    }
192
193    /// Appends a value to the builder.
194    pub fn append_value<S: AsRef<[u8]>>(&mut self, value: S) {
195        self.append_value_view(value.as_ref());
196        self.nulls.append_non_null();
197    }
198
199    /// Appends `n` copies of `value` as non-null entries.
200    pub fn append_n_values<S: AsRef<[u8]>>(&mut self, value: S, n: usize) {
201        if n == 0 {
202            return;
203        }
204        let bytes = value.as_ref();
205        let view = if bytes.len() <= BinaryView::MAX_INLINED_SIZE {
206            BinaryView::make_view(bytes, 0, 0)
207        } else {
208            let (buffer_idx, offset) = self.append_value_to_buffer(bytes);
209            BinaryView::make_view(bytes, buffer_idx, offset)
210        };
211        self.views_builder.push_n(view, n);
212        self.nulls.append_n_non_nulls(n);
213    }
214
215    fn flush_in_progress(&mut self) {
216        let Some(block) = self.in_progress.take() else {
217            return;
218        };
219
220        assert!(block.len() < u32::MAX as usize, "Block too large");
221
222        let initial_len = self.completed.len();
223        self.completed.push(block.freeze());
224        assert_eq!(
225            self.completed.len(),
226            initial_len + 1,
227            "Invalid state, just completed block already exists"
228        );
229    }
230
231    fn init_in_progress(&mut self, min_len: usize) {
232        let next_buffer_size = self.growth_strategy.next_size() as usize;
233        let to_reserve = next_buffer_size.max(min_len);
234        self.in_progress = Some(ByteBufferMut::with_capacity_preferred_aligned_in(
235            to_reserve,
236            Alignment::of::<u8>(),
237            None,
238            self.allocator.clone(),
239        ));
240    }
241
242    /// append a non inlined value to self.in_progress.
243    fn append_value_to_buffer(&mut self, value: &[u8]) -> (u32, u32) {
244        assert!(
245            value.len() > BinaryView::MAX_INLINED_SIZE,
246            "must inline small strings"
247        );
248
249        if let Some(in_progress) = &mut self.in_progress {
250            let required_cap = in_progress.len() + value.len();
251            if in_progress.capacity() < required_cap {
252                self.flush_in_progress();
253                self.init_in_progress(value.len());
254            }
255        } else {
256            self.init_in_progress(value.len())
257        };
258
259        let in_progress = self
260            .in_progress
261            .as_mut()
262            .vortex_expect("in_progress just set");
263
264        let buffer_idx = self.completed.len();
265        let offset = u32::try_from(in_progress.len()).vortex_expect("too many buffers");
266        in_progress.extend_from_slice(value);
267
268        (buffer_idx, offset)
269    }
270
271    pub fn completed_block_count(&self) -> u32 {
272        self.completed.len()
273    }
274
275    /// Whether this builder compacts the data buffers it is handed. The lengths-driven and
276    /// gather appends use this to gate their utilization measurement; the buffer-adopting escape
277    /// hatches ([`append_views_built_at`](Self::append_views_built_at) and
278    /// [`push_buffers`](Self::push_buffers)) always bypass it.
279    fn compacts_buffers(&self) -> bool {
280        self.compaction_threshold > 0.0
281    }
282
283    /// Adopts the buffers and views that `build` produces against the index its first buffer
284    /// will land at.
285    ///
286    /// The builder flushes its staged bytes, then hands `build` the index the next data buffer
287    /// will occupy; `build` returns data buffers — which land contiguously from that index — and
288    /// one view per entry of `validity`, already referencing them. This is the escape hatch for
289    /// an encoding that only discovers its views while walking its own byte format (e.g.
290    /// length-prefixed frames), where the lengths-driven appends cannot apply; keeping the
291    /// numbering inside this call is what makes the views come out right without a rebase pass.
292    ///
293    /// # Warning
294    ///
295    /// This method does not check utilization of the returned buffers. `build` must return
296    /// buffers that are fully utilized by its views.
297    ///
298    /// # Panics
299    ///
300    /// Panics if `build` returns a different view count than `validity.len()`, or if this
301    /// builder deduplicates buffers and already holds one of the returned buffers.
302    pub fn append_views_built_at(
303        &mut self,
304        validity: &Mask,
305        build: impl FnOnce(u32) -> VortexResult<(Vec<ByteBuffer>, Buffer<BinaryView>)>,
306    ) -> VortexResult<()> {
307        self.flush_in_progress();
308
309        let start_index = self.completed.len();
310        let (buffers, views) = build(start_index)?;
311        assert_eq!(
312            views.len(),
313            validity.len(),
314            "Must build one view per validity entry"
315        );
316
317        let expected_completed_len = start_index as usize + buffers.len();
318        self.completed.extend_from_slice_unchecked(&buffers);
319        assert_eq!(
320            self.completed.len() as usize,
321            expected_completed_len,
322            "Some buffers already exist",
323        );
324        self.views_builder.extend_trusted(views.iter().copied());
325        self.nulls.append_validity_mask(validity);
326
327        debug_assert_eq!(self.nulls.len(), self.views_builder.len());
328        Ok(())
329    }
330
331    /// Adopts `buffers` as completed data buffers, returning the index each landed at.
332    ///
333    /// Views appended afterwards (e.g. via [`append_views_gathered`](Self::append_views_gathered)
334    /// or [`append_views_scattered`](Self::append_views_scattered)) reference values through the
335    /// returned indices. A deduplicating builder returns the existing index for a buffer it
336    /// already holds, so repeated appends over shared storage — chunks gathered through one
337    /// dictionary, slices of one array — adopt it once.
338    ///
339    /// # Warning
340    ///
341    /// Buffers are taken as they are, without utilization measurement; like
342    /// [`append_views_built_at`](Self::append_views_built_at), this bypasses any compaction the
343    /// builder was configured for. Scattered appends deliberately have these semantics;
344    /// compacting paths that measure utilization use
345    /// [`push_buffers_compacted`](Self::push_buffers_compacted) instead.
346    fn push_buffers(&mut self, buffers: impl IntoIterator<Item = ByteBuffer>) -> Vec<u32> {
347        self.flush_in_progress();
348        buffers
349            .into_iter()
350            .map(|buffer| self.completed.push(buffer))
351            .collect()
352    }
353
354    /// The compacting counterpart of [`push_buffers`](Self::push_buffers): adopts each buffer
355    /// according to the [`CompactionStrategy`] its measured utilization earns — whole, sliced to
356    /// its referenced range, or not at all. Views into the buffers must then be rebased through
357    /// [`remap_view_compacted`](Self::remap_view_compacted), which routes views into unadopted
358    /// buffers through the builder's own storage.
359    fn push_buffers_compacted(
360        &mut self,
361        buffers: Vec<ByteBuffer>,
362        utilizations: &[BufferUtilization],
363    ) -> Vec<CompactedSlot> {
364        self.flush_in_progress();
365
366        let mut rewritten_bytes = 0usize;
367        let slots = buffers
368            .into_iter()
369            .zip(utilizations)
370            .map(|(buffer, utilization)| {
371                match compaction_strategy(utilization, self.compaction_threshold) {
372                    CompactionStrategy::KeepFull => CompactedSlot::Kept {
373                        index: self.completed.push(buffer),
374                    },
375                    CompactionStrategy::Slice { start, end } => CompactedSlot::Sliced {
376                        index: self
377                            .completed
378                            .push(buffer.slice(start as usize..end as usize)),
379                        shift: start,
380                    },
381                    CompactionStrategy::Rewrite => {
382                        rewritten_bytes += utilization.used() as usize;
383                        CompactedSlot::Rewrite { source: buffer }
384                    }
385                }
386            })
387            .collect();
388
389        // The measured bytes are an upper bound on what the remap copies. One block of that
390        // size replaces the growth strategy's chain of small blocks and per-value capacity
391        // misses.
392        if rewritten_bytes > 0 && rewritten_bytes <= MAX_BUFFER_LEN {
393            self.init_in_progress(rewritten_bytes);
394        }
395
396        slots
397    }
398
399    /// [`remap_view`] against [`CompactedSlot`]s: views into kept or sliced buffers are rebased
400    /// onto the index those landed at, and a view into a rewritten buffer has its bytes copied
401    /// into the builder's own storage. Inlined views pass through unchanged.
402    fn remap_view_compacted(&mut self, view: BinaryView, slots: &[CompactedSlot]) -> BinaryView {
403        if view.is_inlined() {
404            return view;
405        }
406        let view_ref = view.as_view();
407        match &slots[view_ref.buffer_index as usize] {
408            CompactedSlot::Kept { index } => view_ref
409                .with_buffer_and_offset(*index, view_ref.offset)
410                .into(),
411            CompactedSlot::Sliced { index, shift } => view_ref
412                .with_buffer_and_offset(*index, view_ref.offset - shift)
413                .into(),
414            CompactedSlot::Rewrite { source } => {
415                let bytes = &source.as_slice()[view_ref.as_range()];
416                let (buffer_idx, offset) = self.append_value_to_buffer(bytes);
417                view_ref.with_buffer_and_offset(buffer_idx, offset).into()
418            }
419        }
420    }
421
422    /// Appends `validity.len()` values, gathering each valid row's view from `views` through the
423    /// index `view_at` returns for it.
424    ///
425    /// `buffers` — the data buffers the views reference, in the numbering the views use — are
426    /// adopted through the builder's buffer storage, and every gathered view is rebased onto
427    /// the indices they land at as it is written, so the whole append is one view per row with no
428    /// byte copy and no intermediate array. `view_at` is only called for valid rows; null rows get
429    /// an empty view.
430    ///
431    /// When the builder is configured to compact buffers, utilization is measured from the views
432    /// the gather actually references — duplicate indices count once — and each buffer is
433    /// adopted, sliced, or rewritten accordingly, so callers never need a
434    /// canonicalize-and-compact fallback.
435    ///
436    /// # Panics
437    ///
438    /// Panics if `view_at` returns an index out of bounds of `views`, or if a gathered view
439    /// references a buffer index outside `buffers`.
440    pub fn append_views_gathered(
441        &mut self,
442        buffers: impl IntoIterator<Item = ByteBuffer>,
443        views: &[BinaryView],
444        validity: &Mask,
445        view_at: impl Fn(usize) -> usize,
446    ) {
447        if self.compacts_buffers() {
448            return self.append_views_gathered_compacted(
449                buffers.into_iter().collect(),
450                views,
451                validity,
452                view_at,
453            );
454        }
455
456        let mapping = self.push_buffers(buffers);
457
458        self.views_builder.reserve(validity.len());
459        match validity {
460            Mask::AllTrue(len) => self
461                .views_builder
462                .extend_trusted((0..*len).map(|row| remap_view(views[view_at(row)], &mapping))),
463            Mask::AllFalse(len) => self.views_builder.push_n(BinaryView::empty_view(), *len),
464            Mask::Values(values) => {
465                let bits = values.bit_buffer();
466                let start = self.views_builder.len();
467                self.views_builder
468                    .push_n(BinaryView::empty_view(), bits.len());
469                let gathered = &mut self.views_builder[start..];
470                bits.for_each_set_index(|row| {
471                    gathered[row] = remap_view(views[view_at(row)], &mapping);
472                });
473            }
474        }
475
476        self.nulls.append_validity_mask(validity);
477        debug_assert_eq!(self.nulls.len(), self.views_builder.len());
478    }
479
480    /// Appends the views that `selection` selects, with no byte copy and no intermediate array.
481    ///
482    /// `buffers` are the data buffers the views reference, in the numbering the views use.
483    /// `validity` has one entry per selected row. Null rows get an empty view, so their source
484    /// views are never dereferenced and do not count toward buffer utilization.
485    ///
486    /// When the builder compacts buffers, utilization is measured from the selected valid views
487    /// and each buffer is adopted, sliced, or rewritten accordingly.
488    ///
489    /// # Panics
490    ///
491    /// Panics if `selection` is not `views.len()` long, if `validity` is not
492    /// `selection.true_count()` long, or if a selected valid view references a buffer index
493    /// outside `buffers`.
494    pub(crate) fn append_views_filtered(
495        &mut self,
496        buffers: impl IntoIterator<Item = ByteBuffer>,
497        views: &[BinaryView],
498        selection: &MaskValues,
499        validity: &Mask,
500    ) {
501        assert_eq!(selection.len(), views.len());
502        assert_eq!(selection.true_count(), validity.len());
503
504        if validity.all_false() {
505            self.views_builder
506                .push_n(BinaryView::empty_view(), validity.len());
507            self.nulls.append_validity_mask(validity);
508            return;
509        }
510
511        let start = self.views_builder.len();
512        append_filtered_slice(views, selection, &mut self.views_builder);
513        if let AllOr::Some(bits) = validity.bit_buffer() {
514            let selected = &mut self.views_builder[start..];
515            bits.for_each_unset_index(|row| selected[row] = BinaryView::empty_view());
516        }
517
518        if self.compacts_buffers() {
519            let buffers = buffers.into_iter().collect::<Vec<_>>();
520            let mut utilizations = unmeasured_utilizations(&buffers);
521            for view in &self.views_builder[start..] {
522                measure_view(&mut utilizations, view);
523            }
524
525            let slots = self.push_buffers_compacted(buffers, &utilizations);
526            for row in start..self.views_builder.len() {
527                self.views_builder[row] =
528                    self.remap_view_compacted(self.views_builder[row], &slots);
529            }
530        } else {
531            let mapping = self.push_buffers(buffers);
532            let is_identity = mapping
533                .iter()
534                .enumerate()
535                .all(|(index, &landed)| landed as usize == index);
536            if !is_identity {
537                for view in &mut self.views_builder[start..] {
538                    *view = remap_view(*view, &mapping);
539                }
540            }
541        }
542
543        self.nulls.append_validity_mask(validity);
544        debug_assert_eq!(self.nulls.len(), self.views_builder.len());
545    }
546
547    /// The compacting arm of [`append_views_gathered`](Self::append_views_gathered): marks the
548    /// source views the gather references, measures each buffer's utilization from just those —
549    /// so entries gathered by many rows count once — and adopts the buffers through
550    /// [`push_buffers_compacted`](Self::push_buffers_compacted). Each referenced source view is
551    /// remapped once, so rows sharing an entry of a rewritten buffer share one copy of its bytes.
552    fn append_views_gathered_compacted(
553        &mut self,
554        buffers: Vec<ByteBuffer>,
555        views: &[BinaryView],
556        validity: &Mask,
557        view_at: impl Fn(usize) -> usize,
558    ) {
559        let mut referenced = vec![false; views.len()];
560        match validity {
561            Mask::AllTrue(len) => (0..*len).for_each(|row| referenced[view_at(row)] = true),
562            Mask::AllFalse(_) => {}
563            Mask::Values(values) => values
564                .bit_buffer()
565                .for_each_set_index(|row| referenced[view_at(row)] = true),
566        }
567
568        let mut utilizations = unmeasured_utilizations(&buffers);
569        for (view, _) in views.iter().zip(&referenced).filter(|(_, used)| **used) {
570            measure_view(&mut utilizations, view);
571        }
572        let slots = self.push_buffers_compacted(buffers, &utilizations);
573
574        let mut remapped = vec![BinaryView::empty_view(); views.len()];
575        for (idx, view) in views.iter().enumerate() {
576            if referenced[idx] {
577                remapped[idx] = self.remap_view_compacted(*view, &slots);
578            }
579        }
580
581        self.views_builder.reserve(validity.len());
582        match validity {
583            Mask::AllTrue(len) => self
584                .views_builder
585                .extend_trusted((0..*len).map(|row| remapped[view_at(row)])),
586            Mask::AllFalse(len) => self.views_builder.push_n(BinaryView::empty_view(), *len),
587            Mask::Values(values) => {
588                let bits = values.bit_buffer();
589                let start = self.views_builder.len();
590                self.views_builder
591                    .push_n(BinaryView::empty_view(), bits.len());
592                let gathered = &mut self.views_builder[start..];
593                bits.for_each_set_index(|row| gathered[row] = remapped[view_at(row)]);
594            }
595        }
596
597        self.nulls.append_validity_mask(validity);
598        debug_assert_eq!(self.nulls.len(), self.views_builder.len());
599    }
600
601    /// Appends `len` rows that are `fill` everywhere except at the given patch rows.
602    ///
603    /// `buffers` — the data buffers `fill` and the patch views reference, in the numbering they
604    /// use — are adopted through the builder's buffer storage and the views are rebased onto
605    /// the indices they land at. `patches` yields `(row, view)` pairs with rows below `len`; the
606    /// fill rows cost one bulk view fill and each patch one view write, with no byte copy.
607    /// Validity is appended exactly as given — invalid rows keep whichever view they got.
608    ///
609    /// This append deliberately adopts the supplied buffers as-is, even when the builder is
610    /// configured for compaction. Callers should use it only when retaining those buffers is
611    /// acceptable.
612    ///
613    /// # Panics
614    ///
615    /// Panics if `validity` is not `len` long, a patch row is out of bounds, or a view references
616    /// a buffer index outside `buffers`.
617    pub fn append_views_scattered(
618        &mut self,
619        buffers: impl IntoIterator<Item = ByteBuffer>,
620        len: usize,
621        fill: BinaryView,
622        patches: impl Iterator<Item = (usize, BinaryView)>,
623        validity: &Mask,
624    ) {
625        assert_eq!(validity.len(), len, "Must have one validity entry per row");
626        let mapping = self.push_buffers(buffers);
627
628        let start = self.views_builder.len();
629        self.views_builder.push_n(remap_view(fill, &mapping), len);
630        let scattered = &mut self.views_builder[start..];
631        for (row, view) in patches {
632            scattered[row] = remap_view(view, &mapping);
633        }
634
635        self.nulls.append_validity_mask(validity);
636        debug_assert_eq!(self.nulls.len(), self.views_builder.len());
637    }
638
639    /// Appends values laid end-to-end in `bytes`, one per entry of `lengths`.
640    ///
641    /// The builder adopts `bytes` as a data buffer without copying it (splitting it only past the
642    /// `u32` view-offset limit) and builds the views directly into its own storage, so the whole
643    /// append costs one view per row. Every length is consumed, including those for null rows, so
644    /// the lengths must describe `bytes` exactly; bytes belonging to null rows are not retained
645    /// when compaction rewrites the buffer.
646    ///
647    /// When the builder is configured to compact buffers, the utilization is measured from the
648    /// lengths alone — only values too long to inline reference the buffer — and a heap below
649    /// the threshold is rewritten to just those values instead of adopted, so callers never need
650    /// a canonicalize-and-compact fallback.
651    ///
652    /// # Panics
653    ///
654    /// Panics if `lengths` and `validity` disagree in length, if the lengths do not describe
655    /// `bytes` exactly, or if this builder deduplicates buffers and already holds `bytes`.
656    pub fn append_buffer_with_lengths<P: NativePType + AsPrimitive<usize>>(
657        &mut self,
658        bytes: ByteBuffer,
659        lengths: &[P],
660        validity: &Mask,
661    ) {
662        assert_eq!(
663            lengths.len(),
664            validity.len(),
665            "Must have one length per validity entry"
666        );
667        self.append_buffer_views(&bytes, lengths.len(), validity, |i| lengths[i].as_());
668    }
669
670    /// [`append_buffer_with_lengths`](Self::append_buffer_with_lengths) for values described by
671    /// an offsets buffer instead of lengths.
672    ///
673    /// `offsets` are absolute positions into `bytes` — the layout a
674    /// [`VarBinArray`](crate::arrays::VarBinArray) stores — so there is one more offset than there
675    /// are values, and only the `offsets[0]..offsets[last]` range of `bytes` is adopted, again
676    /// without copying.
677    ///
678    /// # Panics
679    ///
680    /// Panics if `offsets` does not hold exactly one more entry than `validity`, or if the offsets
681    /// are not monotonically non-decreasing positions within `bytes`.
682    pub fn append_buffer_with_offsets<P: NativePType + AsPrimitive<usize>>(
683        &mut self,
684        bytes: ByteBuffer,
685        offsets: &[P],
686        validity: &Mask,
687    ) {
688        assert_eq!(
689            offsets.len(),
690            validity.len() + 1,
691            "Must have one more offset than validity entries"
692        );
693        let first: usize = offsets[0].as_();
694        let last: usize = offsets[offsets.len() - 1].as_();
695        let bytes = bytes.slice(first..last);
696        // Wrapping keeps corrupt non-monotonic offsets from panicking on the subtraction itself;
697        // the wrapped length then fails the in-bounds checks of the view-building loop.
698        self.append_buffer_views(&bytes, validity.len(), validity, |i| {
699            AsPrimitive::<usize>::as_(offsets[i + 1])
700                .wrapping_sub(AsPrimitive::<usize>::as_(offsets[i]))
701        });
702    }
703
704    /// Shared tail of the bulk buffer appends: builds the views straight into the builder's views
705    /// storage, then adopts the buffer segments and the validity.
706    fn append_buffer_views(
707        &mut self,
708        bytes: &ByteBuffer,
709        count: usize,
710        validity: &Mask,
711        len_at: impl Fn(usize) -> usize,
712    ) {
713        self.flush_in_progress();
714
715        // A compacting builder measures utilization before adopting the buffer. Only values too
716        // long to inline reference the heap, so the measurement is one pass over the lengths and
717        // never touches the bytes. Heaps past the single-buffer limit are adopted as they are:
718        // they roll over into multiple buffers, and per-segment accounting is not worth the rare
719        // >2GiB case.
720        if self.compacts_buffers() && bytes.len() <= MAX_BUFFER_LEN {
721            let referenced: usize = match validity.bit_buffer() {
722                AllOr::All => (0..count)
723                    .map(&len_at)
724                    .filter(|len| *len > BinaryView::MAX_INLINED_SIZE)
725                    .sum(),
726                AllOr::None => 0,
727                AllOr::Some(b) => {
728                    let mut sum = 0;
729                    b.for_each_set_index(|idx| {
730                        let len = len_at(idx);
731                        if len > BinaryView::MAX_INLINED_SIZE {
732                            sum += len;
733                        }
734                    });
735                    sum
736                }
737            };
738            #[expect(clippy::cast_precision_loss)]
739            if (referenced as f64) < self.compaction_threshold * (bytes.len() as f64) {
740                return self
741                    .append_buffer_views_rewritten(bytes, count, validity, len_at, referenced);
742            }
743        }
744
745        let start_index = self.completed.len();
746        let segments = extend_views(
747            &mut self.views_builder,
748            start_index,
749            MAX_BUFFER_LEN,
750            bytes,
751            count,
752            len_at,
753        );
754
755        let expected_completed_len = start_index as usize + segments.len();
756        self.completed.extend_from_slice_unchecked(&segments);
757        assert_eq!(
758            self.completed.len() as usize,
759            expected_completed_len,
760            "Some buffers already exist",
761        );
762
763        self.nulls.append_validity_mask(validity);
764        debug_assert_eq!(self.nulls.len(), self.views_builder.len());
765    }
766
767    /// The under-utilized arm of [`append_buffer_views`](Self::append_buffer_views): copies only
768    /// the values that actually reference the heap into a compact buffer, sized `referenced`,
769    /// instead of adopting the whole heap. A fully-inlined append pushes no buffer at all.
770    fn append_buffer_views_rewritten(
771        &mut self,
772        bytes: &ByteBuffer,
773        count: usize,
774        validity: &Mask,
775        len_at: impl Fn(usize) -> usize,
776        referenced: usize,
777    ) {
778        let buf_index = self.completed.len();
779        let mut compact = ByteBufferMut::with_capacity_in(referenced, self.allocator.clone());
780        self.views_builder.reserve(count);
781
782        let data = bytes.as_slice();
783        let mut offset = 0usize;
784        for (i, is_valid) in validity.iter().enumerate() {
785            let len = len_at(i);
786            let value = &data[offset..offset + len];
787            let view = if !is_valid {
788                BinaryView::empty_view()
789            } else if len > BinaryView::MAX_INLINED_SIZE {
790                // In `u32` range: `referenced <= bytes.len() <= MAX_BUFFER_LEN` (checked by the
791                // caller), and `compact` never grows past `referenced`.
792                #[expect(clippy::cast_possible_truncation)]
793                let view = BinaryView::make_view(value, buf_index, compact.len() as u32);
794                compact.extend_from_slice(value);
795                view
796            } else {
797                BinaryView::make_view(value, buf_index, 0)
798            };
799            self.views_builder.push(view);
800            offset += len;
801        }
802        assert_eq!(
803            offset,
804            data.len(),
805            "value lengths must describe the byte heap exactly"
806        );
807
808        if !compact.is_empty() {
809            let pushed_index = self.completed.push(compact.freeze());
810            assert_eq!(pushed_index, buf_index, "Buffer already exists");
811        }
812
813        self.nulls.append_validity_mask(validity);
814        debug_assert_eq!(self.nulls.len(), self.views_builder.len());
815    }
816
817    /// Finishes the builder directly into a [`VarBinViewArray`].
818    pub fn finish_into_varbinview(&mut self) -> VarBinViewArray {
819        self.flush_in_progress();
820        let buffers = std::mem::take(&mut self.completed);
821
822        assert_eq!(
823            self.views_builder.len(),
824            self.nulls.len(),
825            "View and validity length must match"
826        );
827
828        let validity = self.nulls.finish_with_nullability(self.dtype.nullability());
829
830        let views = std::mem::replace(
831            &mut self.views_builder,
832            BufferMut::empty_aligned_in(Alignment::of::<BinaryView>(), self.allocator.clone()),
833        )
834        .freeze();
835
836        // SAFETY: the builder methods check safety at each step.
837        unsafe {
838            VarBinViewArray::new_unchecked(views, buffers.finish(), self.dtype.clone(), validity)
839        }
840    }
841
842    pub(crate) fn append_varbinview_array(
843        &mut self,
844        array: ArrayView<'_, VarBinView>,
845        ctx: &mut ExecutionCtx,
846    ) -> VortexResult<()> {
847        self.flush_in_progress();
848
849        let mask = array.varbinview_validity().execute_mask(array.len(), ctx)?;
850
851        self.nulls.append_validity_mask(&mask);
852
853        let view_adjustment =
854            self.completed
855                .extend_from_compaction(BuffersWithOffsets::from_array(
856                    array,
857                    self.compaction_threshold,
858                    ctx,
859                ));
860
861        match view_adjustment {
862            ViewAdjustment::Precomputed(adjustment) => self.views_builder.extend_trusted(
863                array
864                    .views()
865                    .iter()
866                    .map(|view| adjustment.adjust_view(view)),
867            ),
868            ViewAdjustment::Rewriting(adjustment) => match mask {
869                Mask::AllTrue(_) => {
870                    for (idx, &view) in array.views().iter().enumerate() {
871                        let new_view = self.push_view(view, &adjustment, array, idx);
872                        self.views_builder.push(new_view);
873                    }
874                }
875                Mask::AllFalse(_) => {
876                    self.views_builder
877                        .push_n(BinaryView::empty_view(), array.len());
878                }
879                Mask::Values(v) => {
880                    let views = array.views();
881                    let start = self.views_builder.len();
882                    self.views_builder
883                        .push_n(BinaryView::empty_view(), array.len());
884                    v.bit_buffer().for_each_set_index(|idx| {
885                        let new_view = self.push_view(views[idx], &adjustment, array, idx);
886                        self.views_builder[start + idx] = new_view;
887                    });
888                }
889            },
890        }
891
892        Ok(())
893    }
894}
895
896impl ArrayBuilder for VarBinViewBuilder {
897    fn as_any(&self) -> &dyn Any {
898        self
899    }
900
901    fn as_any_mut(&mut self) -> &mut dyn Any {
902        self
903    }
904
905    fn dtype(&self) -> &DType {
906        &self.dtype
907    }
908
909    fn len(&self) -> usize {
910        self.nulls.len()
911    }
912
913    fn append_zeros(&mut self, n: usize) {
914        self.views_builder.push_n(BinaryView::empty_view(), n);
915        self.nulls.append_n_non_nulls(n);
916    }
917
918    unsafe fn append_nulls_unchecked(&mut self, n: usize) {
919        self.views_builder.push_n(BinaryView::empty_view(), n);
920        self.nulls.append_n_nulls(n);
921    }
922
923    fn append_scalar(&mut self, scalar: &Scalar) -> VortexResult<()> {
924        vortex_ensure_eq!(
925            scalar.dtype(),
926            self.dtype(),
927            "VarBinViewBuilder received a scalar with the wrong dtype"
928        );
929
930        match self.dtype() {
931            DType::Utf8(_) => match scalar.as_utf8().value() {
932                Some(value) => self.append_value(value),
933                None => self.append_null(),
934            },
935            DType::Binary(_) => match scalar.as_binary().value() {
936                Some(value) => self.append_value(value),
937                None => self.append_null(),
938            },
939            _ => vortex_bail!(
940                "VarBinViewBuilder can only handle Utf8 or Binary scalars, got {:?}",
941                scalar.dtype()
942            ),
943        }
944
945        Ok(())
946    }
947
948    fn reserve_exact(&mut self, additional: usize) {
949        self.views_builder.reserve(additional);
950        self.nulls.reserve_exact(additional);
951    }
952
953    fn finish(&mut self) -> ArrayRef {
954        self.finish_into_varbinview().into_array()
955    }
956
957    fn finish_into_canonical(&mut self, _ctx: &mut ExecutionCtx) -> Canonical {
958        Canonical::VarBinView(self.finish_into_varbinview())
959    }
960}
961
962impl VarBinViewBuilder {
963    #[allow(clippy::inline_always)]
964    #[inline(always)]
965    fn push_view(
966        &mut self,
967        view: BinaryView,
968        adjustment: &RewritingViewAdjustment,
969        array: ArrayView<'_, VarBinView>,
970        idx: usize,
971    ) -> BinaryView {
972        if view.is_inlined() {
973            view
974        } else if let Some(adjusted) = adjustment.adjust_view(&view) {
975            adjusted
976        } else {
977            let bytes = array.bytes_at(idx);
978            let (new_buf_idx, new_offset) = self.append_value_to_buffer(&bytes);
979            BinaryView::make_view(bytes.as_slice(), new_buf_idx, new_offset)
980        }
981    }
982}
983
984/// Rebases a view built against a local buffer numbering onto the builder indices those buffers
985/// landed at, i.e. `mapping[i]` is where the caller's buffer `i` went. Inlined views carry no
986/// buffer reference and pass through unchanged.
987#[inline]
988fn remap_view(view: BinaryView, mapping: &[u32]) -> BinaryView {
989    if view.is_inlined() {
990        view
991    } else {
992        let view_ref = view.as_view();
993        view_ref
994            .with_buffer_and_offset(mapping[view_ref.buffer_index as usize], view_ref.offset)
995            .into()
996    }
997}
998
999/// Where a caller's buffer went under `VarBinViewBuilder::push_buffers_compacted`.
1000enum CompactedSlot {
1001    /// Adopted whole at this index.
1002    Kept { index: u32 },
1003    /// Adopted at this index as the slice starting `shift` bytes in, so view offsets shift down.
1004    Sliced { index: u32, shift: u32 },
1005    /// Not adopted: each referenced view's bytes are copied out of the source buffer into the
1006    /// builder's own storage.
1007    Rewrite { source: ByteBuffer },
1008}
1009
1010/// One unmeasured [`BufferUtilization`] per buffer, ready for [`measure_view`] passes.
1011fn unmeasured_utilizations(buffers: &[ByteBuffer]) -> Vec<BufferUtilization> {
1012    buffers
1013        .iter()
1014        .map(|buffer| {
1015            // Views address at most `u32` offsets, so measuring an oversized buffer against the
1016            // saturated length under-reports utilization, which can only compact harder — and its
1017            // unaddressable tail is dead weight worth compacting anyway.
1018            BufferUtilization::zero(u32::try_from(buffer.len()).unwrap_or(u32::MAX))
1019        })
1020        .collect()
1021}
1022
1023/// Counts `view`'s bytes against the buffer it references; inlined views reference none.
1024fn measure_view(utilizations: &mut [BufferUtilization], view: &BinaryView) {
1025    if !view.is_inlined() {
1026        let view_ref = view.as_view();
1027        utilizations[view_ref.buffer_index as usize].add(view_ref.offset, view_ref.size);
1028    }
1029}
1030
1031pub enum CompletedBuffers {
1032    Default(Vec<ByteBuffer>),
1033    Deduplicated(DeduplicatedBuffers),
1034}
1035
1036impl Default for CompletedBuffers {
1037    fn default() -> Self {
1038        Self::Default(Vec::new())
1039    }
1040}
1041
1042// Self::push enforces len < u32::max
1043#[expect(clippy::cast_possible_truncation)]
1044impl CompletedBuffers {
1045    fn len(&self) -> u32 {
1046        match self {
1047            Self::Default(buffers) => buffers.len() as u32,
1048            Self::Deduplicated(buffers) => buffers.len(),
1049        }
1050    }
1051
1052    /// Push a new block, returning the index it landed at (or, when deduplicating, the index of
1053    /// the identical block already held).
1054    fn push(&mut self, block: ByteBuffer) -> u32 {
1055        match self {
1056            Self::Default(buffers) => {
1057                assert!(buffers.len() < u32::MAX as usize, "Too many blocks");
1058                buffers.push(block);
1059                self.len() - 1
1060            }
1061            Self::Deduplicated(buffers) => buffers.push(block),
1062        }
1063    }
1064
1065    /// Does not compact buffers, bypasses utilization checks.
1066    fn extend_from_slice_unchecked(&mut self, buffers: &[ByteBuffer]) {
1067        for buffer in buffers {
1068            self.push(buffer.clone());
1069        }
1070    }
1071
1072    fn extend_from_compaction(&mut self, buffers: BuffersWithOffsets) -> ViewAdjustment {
1073        match (self, buffers) {
1074            (
1075                Self::Default(completed_buffers),
1076                BuffersWithOffsets::AllKept { buffers, offsets },
1077            ) => {
1078                let buffer_offset = completed_buffers.len() as u32;
1079                completed_buffers.extend_from_slice(&buffers);
1080                ViewAdjustment::shift(buffer_offset, offsets)
1081            }
1082            (
1083                Self::Default(completed_buffers),
1084                BuffersWithOffsets::SomeCompacted { buffers, offsets },
1085            ) => {
1086                let lookup = buffers
1087                    .iter()
1088                    .map(|maybe_buffer| {
1089                        maybe_buffer.as_ref().map(|buffer| {
1090                            completed_buffers.push(buffer.clone());
1091                            completed_buffers.len() as u32 - 1
1092                        })
1093                    })
1094                    .collect();
1095                ViewAdjustment::rewriting(lookup, offsets)
1096            }
1097
1098            (
1099                Self::Deduplicated(completed_buffers),
1100                BuffersWithOffsets::AllKept { buffers, offsets },
1101            ) => {
1102                let buffer_lookup = completed_buffers.extend_from_iter(buffers.iter().cloned());
1103                ViewAdjustment::lookup(buffer_lookup, offsets)
1104            }
1105            (
1106                Self::Deduplicated(completed_buffers),
1107                BuffersWithOffsets::SomeCompacted { buffers, offsets },
1108            ) => {
1109                let buffer_lookup = completed_buffers.extend_from_option_slice(&buffers);
1110                ViewAdjustment::rewriting(buffer_lookup, offsets)
1111            }
1112        }
1113    }
1114
1115    fn finish(self) -> Arc<[ByteBuffer]> {
1116        match self {
1117            Self::Default(buffers) => Arc::from(buffers),
1118            Self::Deduplicated(buffers) => buffers.finish(),
1119        }
1120    }
1121}
1122
1123#[derive(Default)]
1124pub struct DeduplicatedBuffers {
1125    buffers: Vec<ByteBuffer>,
1126    buffer_to_idx: HashMap<BufferId, u32>,
1127}
1128
1129impl DeduplicatedBuffers {
1130    // Self::push enforces len < u32::max
1131    #[expect(clippy::cast_possible_truncation)]
1132    fn len(&self) -> u32 {
1133        self.buffers.len() as u32
1134    }
1135
1136    /// Push a new block if not seen before. Returns the idx of the block.
1137    pub(crate) fn push(&mut self, block: ByteBuffer) -> u32 {
1138        assert!(self.buffers.len() < u32::MAX as usize, "Too many blocks");
1139
1140        let initial_len = self.len();
1141        let id = BufferId::from(&block);
1142        match self.buffer_to_idx.entry(id) {
1143            Entry::Occupied(idx) => *idx.get(),
1144            Entry::Vacant(entry) => {
1145                let idx = initial_len;
1146                entry.insert(idx);
1147                self.buffers.push(block);
1148                idx
1149            }
1150        }
1151    }
1152
1153    pub(crate) fn extend_from_option_slice(
1154        &mut self,
1155        buffers: &[Option<ByteBuffer>],
1156    ) -> Vec<Option<u32>> {
1157        buffers
1158            .iter()
1159            .map(|buffer| buffer.as_ref().map(|buf| self.push(buf.clone())))
1160            .collect()
1161    }
1162
1163    /// Pushes each of `buffers`, returning the index of each in the deduplicated buffers.
1164    pub fn extend_from_iter(&mut self, buffers: impl Iterator<Item = ByteBuffer>) -> Vec<u32> {
1165        buffers.map(|buffer| self.push(buffer)).collect()
1166    }
1167
1168    /// The deduplicated buffers, in the order they were first pushed.
1169    pub fn finish(self) -> Arc<[ByteBuffer]> {
1170        Arc::from(self.buffers)
1171    }
1172}
1173
1174#[derive(PartialEq, Eq, Hash)]
1175struct BufferId {
1176    // *const u8 stored as usize for `Send`
1177    ptr: usize,
1178    len: usize,
1179}
1180
1181impl BufferId {
1182    fn from(buffer: &ByteBuffer) -> Self {
1183        let slice = buffer.as_slice();
1184        Self {
1185            ptr: slice.as_ptr() as usize,
1186            len: slice.len(),
1187        }
1188    }
1189}
1190
1191#[derive(Debug, Clone)]
1192pub enum BufferGrowthStrategy {
1193    /// Use a fixed buffer size for all allocations.
1194    Fixed { size: u32 },
1195    /// Use exponential growth starting from initial_size, doubling until max_size.
1196    Exponential { current_size: u32, max_size: u32 },
1197}
1198
1199impl Default for BufferGrowthStrategy {
1200    fn default() -> Self {
1201        Self::Exponential {
1202            current_size: 4 * 1024,    // 4KB starting size
1203            max_size: 2 * 1024 * 1024, // 2MB max size
1204        }
1205    }
1206}
1207
1208impl BufferGrowthStrategy {
1209    pub fn fixed(size: u32) -> Self {
1210        Self::Fixed { size }
1211    }
1212
1213    pub fn exponential(initial_size: u32, max_size: u32) -> Self {
1214        Self::Exponential {
1215            current_size: initial_size,
1216            max_size,
1217        }
1218    }
1219
1220    /// Returns the next buffer size to allocate and updates internal state.
1221    pub fn next_size(&mut self) -> u32 {
1222        match self {
1223            Self::Fixed { size } => *size,
1224            Self::Exponential {
1225                current_size,
1226                max_size,
1227            } => {
1228                let result = *current_size;
1229                if *current_size < *max_size {
1230                    *current_size = current_size.saturating_mul(2).min(*max_size);
1231                }
1232                result
1233            }
1234        }
1235    }
1236}
1237
1238enum BuffersWithOffsets {
1239    AllKept {
1240        buffers: Arc<[ByteBuffer]>,
1241        offsets: Option<Vec<u32>>,
1242    },
1243    SomeCompacted {
1244        buffers: Vec<Option<ByteBuffer>>,
1245        offsets: Option<Vec<u32>>,
1246    },
1247}
1248
1249impl BuffersWithOffsets {
1250    pub fn from_array(
1251        array: ArrayView<'_, VarBinView>,
1252        compaction_threshold: f64,
1253        ctx: &mut ExecutionCtx,
1254    ) -> Self {
1255        if compaction_threshold == 0.0 {
1256            return Self::AllKept {
1257                buffers: Arc::from(
1258                    array
1259                        .data_buffers()
1260                        .iter()
1261                        .cloned()
1262                        .map(|b| b.unwrap_host())
1263                        .collect_vec(),
1264                ),
1265                offsets: None,
1266            };
1267        }
1268
1269        let buffer_utilizations = array
1270            .buffer_utilizations(ctx)
1271            .vortex_expect("buffer_utilizations in BuffersWithOffsets::from_array");
1272        let mut has_rewrite = false;
1273        let mut has_nonzero_offset = false;
1274        for utilization in buffer_utilizations.iter() {
1275            match compaction_strategy(utilization, compaction_threshold) {
1276                CompactionStrategy::KeepFull => continue,
1277                CompactionStrategy::Slice { .. } => has_nonzero_offset = true,
1278                CompactionStrategy::Rewrite => has_rewrite = true,
1279            }
1280        }
1281
1282        let buffers_with_offsets_iter = buffer_utilizations
1283            .iter()
1284            .zip(array.data_buffers().iter())
1285            .map(|(utilization, buffer)| {
1286                match compaction_strategy(utilization, compaction_threshold) {
1287                    CompactionStrategy::KeepFull => (Some(buffer.as_host().clone()), 0),
1288                    CompactionStrategy::Slice { start, end } => (
1289                        Some(buffer.as_host().slice(start as usize..end as usize)),
1290                        start,
1291                    ),
1292                    CompactionStrategy::Rewrite => (None, 0),
1293                }
1294            });
1295
1296        match (has_rewrite, has_nonzero_offset) {
1297            // keep all buffers
1298            (false, false) => {
1299                let buffers: Vec<_> = buffers_with_offsets_iter
1300                    .map(|(b, _)| b.vortex_expect("already checked for rewrite"))
1301                    .collect();
1302                Self::AllKept {
1303                    buffers: Arc::from(buffers),
1304                    offsets: None,
1305                }
1306            }
1307            // rewrite, all zero offsets
1308            (true, false) => {
1309                let buffers: Vec<_> = buffers_with_offsets_iter.map(|(b, _)| b).collect();
1310                Self::SomeCompacted {
1311                    buffers,
1312                    offsets: None,
1313                }
1314            }
1315            // keep all buffers, but some have offsets
1316            (false, true) => {
1317                let (buffers, offsets): (Vec<_>, _) = buffers_with_offsets_iter
1318                    .map(|(buffer, offset)| {
1319                        (buffer.vortex_expect("already checked for rewrite"), offset)
1320                    })
1321                    .collect();
1322                Self::AllKept {
1323                    buffers: Arc::from(buffers),
1324                    offsets: Some(offsets),
1325                }
1326            }
1327            // rewrite and some have offsets
1328            (true, true) => {
1329                let (buffers, offsets) = buffers_with_offsets_iter.collect();
1330                Self::SomeCompacted {
1331                    buffers,
1332                    offsets: Some(offsets),
1333                }
1334            }
1335        }
1336    }
1337}
1338
1339#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1340enum CompactionStrategy {
1341    KeepFull,
1342    /// Slice the buffer to [start, end) range
1343    Slice {
1344        start: u32,
1345        end: u32,
1346    },
1347    /// Rewrite data into new compacted buffer
1348    Rewrite,
1349}
1350
1351fn compaction_strategy(
1352    buffer_utilization: &BufferUtilization,
1353    threshold: f64,
1354) -> CompactionStrategy {
1355    match buffer_utilization.overall_utilization() {
1356        // rewrite empty or not used buffers TODO(os): maybe keep them
1357        0.0 => CompactionStrategy::Rewrite,
1358        utilised if utilised >= threshold => CompactionStrategy::KeepFull,
1359        _ if buffer_utilization.range_utilization() >= threshold => {
1360            let Range { start, end } = buffer_utilization.range();
1361            CompactionStrategy::Slice { start, end }
1362        }
1363        _ => CompactionStrategy::Rewrite,
1364    }
1365}
1366
1367enum ViewAdjustment {
1368    Precomputed(PrecomputedViewAdjustment),
1369    Rewriting(RewritingViewAdjustment),
1370}
1371
1372impl ViewAdjustment {
1373    fn shift(buffer_offset: u32, offsets: Option<Vec<u32>>) -> Self {
1374        Self::Precomputed(PrecomputedViewAdjustment::Shift {
1375            buffer_offset,
1376            offsets,
1377        })
1378    }
1379
1380    fn lookup(buffer_lookup: Vec<u32>, offsets: Option<Vec<u32>>) -> Self {
1381        Self::Precomputed(PrecomputedViewAdjustment::Lookup {
1382            buffer_lookup,
1383            offsets,
1384        })
1385    }
1386
1387    fn rewriting(buffer_lookup: Vec<Option<u32>>, offsets: Option<Vec<u32>>) -> Self {
1388        Self::Rewriting(RewritingViewAdjustment {
1389            buffer_lookup,
1390            offsets,
1391        })
1392    }
1393}
1394
1395// Care when adding new variants or fields in this enum, it will mess with inlining if it gets too big
1396enum PrecomputedViewAdjustment {
1397    Shift {
1398        buffer_offset: u32,
1399        offsets: Option<Vec<u32>>,
1400    },
1401    Lookup {
1402        buffer_lookup: Vec<u32>,
1403        offsets: Option<Vec<u32>>,
1404    },
1405}
1406
1407impl PrecomputedViewAdjustment {
1408    #[inline]
1409    fn adjust_view(&self, view: &BinaryView) -> BinaryView {
1410        if view.is_inlined() {
1411            return *view;
1412        }
1413        let view_ref = view.as_view();
1414        match self {
1415            Self::Shift {
1416                buffer_offset,
1417                offsets,
1418            } => {
1419                let b_idx = view_ref.buffer_index;
1420                let offset_shift = offsets
1421                    .as_ref()
1422                    .map(|o| o[b_idx as usize])
1423                    .unwrap_or_default();
1424
1425                // If offset < offset_shift, this view was invalid and wasn't counted in buffer_utilizations.
1426                // Return an empty view to match how invalid views are handled in the Rewriting path.
1427                if view_ref.offset < offset_shift {
1428                    return BinaryView::empty_view();
1429                }
1430
1431                view_ref
1432                    .with_buffer_and_offset(b_idx + buffer_offset, view_ref.offset - offset_shift)
1433            }
1434            Self::Lookup {
1435                buffer_lookup,
1436                offsets,
1437            } => {
1438                let b_idx = view_ref.buffer_index;
1439                let buffer = buffer_lookup[b_idx as usize];
1440                let offset_shift = offsets
1441                    .as_ref()
1442                    .map(|o| o[b_idx as usize])
1443                    .unwrap_or_default();
1444
1445                // If offset < offset_shift, this view was invalid and wasn't counted in buffer_utilizations.
1446                // Return an empty view to match how invalid views are handled in the Rewriting path.
1447                if view_ref.offset < offset_shift {
1448                    return BinaryView::empty_view();
1449                }
1450
1451                view_ref.with_buffer_and_offset(buffer, view_ref.offset - offset_shift)
1452            }
1453        }
1454        .into()
1455    }
1456}
1457
1458struct RewritingViewAdjustment {
1459    buffer_lookup: Vec<Option<u32>>,
1460    offsets: Option<Vec<u32>>,
1461}
1462
1463impl RewritingViewAdjustment {
1464    /// Can return None if this view can't be adjusted, because there is no precomputed lookup
1465    /// for the current buffer.
1466    #[inline]
1467    fn adjust_view(&self, view: &BinaryView) -> Option<BinaryView> {
1468        if view.is_inlined() {
1469            return Some(*view);
1470        }
1471
1472        let view_ref = view.as_view();
1473        self.buffer_lookup[view_ref.buffer_index as usize].map(|buffer| {
1474            let offset_shift = self
1475                .offsets
1476                .as_ref()
1477                .map(|o| o[view_ref.buffer_index as usize])
1478                .unwrap_or_default();
1479            view_ref
1480                .with_buffer_and_offset(buffer, view_ref.offset - offset_shift)
1481                .into()
1482        })
1483    }
1484}
1485
1486#[cfg(test)]
1487mod tests {
1488    use std::sync::LazyLock;
1489
1490    use vortex_buffer::BufferAllocatorRef;
1491    use vortex_buffer::ByteBuffer;
1492    use vortex_error::VortexResult;
1493    use vortex_mask::Mask;
1494    use vortex_session::VortexSession;
1495
1496    use crate::IntoArray;
1497    use crate::VortexSessionExecute;
1498    use crate::assert_arrays_eq;
1499    use crate::builders::ArrayBuilder;
1500    use crate::builders::VarBinViewBuilder;
1501    use crate::builders::varbinview::VarBinViewArray;
1502    use crate::dtype::DType;
1503    use crate::dtype::Nullability;
1504    use crate::scalar::Scalar;
1505
1506    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
1507
1508    /// A long-enough value that a view over it must reference a data buffer.
1509    const LONG: &str = "a value that is far too long to inline";
1510
1511    /// The heap is adopted zero-copy as a data buffer, the views are built against it in place,
1512    /// and the append composes with staged in-progress bytes on either side.
1513    #[test]
1514    fn test_append_buffer_with_lengths() {
1515        let mut ctx = SESSION.create_execution_ctx();
1516        let mut builder = VarBinViewBuilder::with_capacity_in(
1517            DType::Utf8(Nullability::Nullable),
1518            8,
1519            BufferAllocatorRef::statically_allocated(),
1520        );
1521
1522        // Stages an in-progress buffer the bulk append has to flush first.
1523        builder.append_value(LONG);
1524
1525        let heap = ByteBuffer::copy_from([LONG.as_bytes(), b"", b"tiny"].concat());
1526        let heap_ptr = heap.as_ptr();
1527        let lengths = [u32::try_from(LONG.len()).unwrap(), 0, 4];
1528        builder.append_buffer_with_lengths(heap, &lengths, &Mask::from_iter([true, false, true]));
1529
1530        builder.append_value("tail");
1531
1532        let actual = builder.finish_into_varbinview();
1533        // The adopted heap sits after the flushed in-progress buffer, untouched.
1534        assert_eq!(actual.data_buffers()[1].as_host().as_ptr(), heap_ptr);
1535
1536        let expected = <VarBinViewArray as FromIterator<_>>::from_iter([
1537            Some(LONG),
1538            Some(LONG),
1539            None,
1540            Some("tiny"),
1541            Some("tail"),
1542        ]);
1543        assert_arrays_eq!(actual, expected, &mut ctx);
1544    }
1545
1546    /// Offsets need not start at zero: only the referenced range of the heap is adopted.
1547    #[test]
1548    fn test_append_buffer_with_offsets() {
1549        let mut ctx = SESSION.create_execution_ctx();
1550        let mut builder = VarBinViewBuilder::with_capacity_in(
1551            DType::Utf8(Nullability::Nullable),
1552            8,
1553            BufferAllocatorRef::statically_allocated(),
1554        );
1555
1556        let heap = ByteBuffer::copy_from(format!("..{LONG}tiny!!"));
1557        let long_len = u32::try_from(LONG.len()).unwrap();
1558        let offsets = [2u32, 2 + long_len, 2 + long_len, 2 + long_len + 4];
1559        builder.append_buffer_with_offsets(
1560            heap.clone(),
1561            &offsets,
1562            &Mask::from_iter([true, false, true]),
1563        );
1564
1565        let actual = builder.finish_into_varbinview();
1566        // Zero-copy adoption of just the `offsets[0]..offsets[last]` range.
1567        // SAFETY: offset 2 is in bounds of the heap.
1568        assert_eq!(actual.data_buffers()[0].as_host().as_ptr(), unsafe {
1569            heap.as_ptr().add(2)
1570        });
1571        assert_eq!(
1572            actual.data_buffers()[0].len(),
1573            LONG.len() + 4,
1574            "only the referenced range must be adopted"
1575        );
1576
1577        let expected =
1578            <VarBinViewArray as FromIterator<_>>::from_iter([Some(LONG), None, Some("tiny")]);
1579        assert_arrays_eq!(actual, expected, &mut ctx);
1580    }
1581
1582    /// A compacting builder must measure the heap it is handed: values short enough to inline
1583    /// never reference it, so an under-utilized heap is rewritten to just the referencing values.
1584    #[test]
1585    fn test_append_buffer_with_lengths_compacts_underutilized_heap() {
1586        let mut ctx = SESSION.create_execution_ctx();
1587        let mut builder = VarBinViewBuilder::with_compaction_in(
1588            DType::Utf8(Nullability::Nullable),
1589            4,
1590            1.0,
1591            BufferAllocatorRef::statically_allocated(),
1592        );
1593
1594        let heap = ByteBuffer::copy_from([b"short".as_slice(), LONG.as_bytes(), b"tiny"].concat());
1595        let lengths = [5u32, u32::try_from(LONG.len()).unwrap(), 4];
1596        builder.append_buffer_with_lengths(heap, &lengths, &Mask::new_true(3));
1597
1598        let actual = builder.finish_into_varbinview();
1599        assert_eq!(actual.data_buffers().len(), 1);
1600        assert_eq!(
1601            actual.data_buffers()[0].len(),
1602            LONG.len(),
1603            "the compact buffer must hold only the non-inlined values"
1604        );
1605
1606        let expected = <VarBinViewArray as FromIterator<_>>::from_iter([
1607            Some("short"),
1608            Some(LONG),
1609            Some("tiny"),
1610        ]);
1611        assert_arrays_eq!(actual, expected, &mut ctx);
1612    }
1613
1614    /// Rewriting an under-utilized heap must consume null values' spans without retaining their
1615    /// bytes or producing views that reference them.
1616    #[test]
1617    fn test_append_buffer_with_lengths_compaction_skips_null_bytes() {
1618        let mut ctx = SESSION.create_execution_ctx();
1619        let mut builder = VarBinViewBuilder::with_compaction_in(
1620            DType::Utf8(Nullability::Nullable),
1621            2,
1622            1.0,
1623            BufferAllocatorRef::statically_allocated(),
1624        );
1625
1626        let heap = ByteBuffer::copy_from([LONG.as_bytes(), LONG.as_bytes()].concat());
1627        let lengths = [u32::try_from(LONG.len()).unwrap(); 2];
1628        builder.append_buffer_with_lengths(heap, &lengths, &Mask::from_iter([false, true]));
1629
1630        let actual = builder.finish_into_varbinview();
1631        assert_eq!(actual.data_buffers().len(), 1);
1632        assert_eq!(
1633            actual.data_buffers()[0].len(),
1634            LONG.len(),
1635            "the compact buffer must omit bytes belonging to null rows"
1636        );
1637
1638        let expected = <VarBinViewArray as FromIterator<_>>::from_iter([None::<&str>, Some(LONG)]);
1639        assert_arrays_eq!(actual, expected, &mut ctx);
1640    }
1641
1642    /// `push_buffers` returns where each buffer landed, and a deduplicating builder maps a
1643    /// re-pushed buffer back to its existing index instead of holding it twice.
1644    #[test]
1645    fn test_push_buffers_deduplicates() {
1646        let mut builder = VarBinViewBuilder::with_buffer_deduplication_in(
1647            DType::Utf8(Nullability::Nullable),
1648            8,
1649            BufferAllocatorRef::statically_allocated(),
1650        );
1651
1652        let first = ByteBuffer::copy_from(LONG);
1653        let second = ByteBuffer::copy_from("another value far too long to inline");
1654
1655        assert_eq!(
1656            builder.push_buffers([first.clone(), second.clone()]),
1657            [0, 1]
1658        );
1659        assert_eq!(builder.push_buffers([second, first]), [1, 0]);
1660        assert_eq!(builder.completed_block_count(), 2);
1661    }
1662
1663    /// Gathered views are rebased onto wherever the pushed buffers landed, and null rows never
1664    /// resolve their index.
1665    #[test]
1666    fn test_append_views_gathered() {
1667        let mut ctx = SESSION.create_execution_ctx();
1668        let dictionary = <VarBinViewArray as FromIterator<_>>::from_iter([
1669            Some("tiny"),
1670            Some(LONG),
1671            Some("small"),
1672        ]);
1673        let buffers = dictionary
1674            .data_buffers()
1675            .iter()
1676            .map(|buffer| buffer.as_host().clone())
1677            .collect::<Vec<_>>();
1678
1679        let mut builder = VarBinViewBuilder::with_capacity_in(
1680            DType::Utf8(Nullability::Nullable),
1681            8,
1682            BufferAllocatorRef::statically_allocated(),
1683        );
1684        // Stages an in-progress buffer that the gather has to flush ahead of its own buffers.
1685        builder.append_value(LONG);
1686
1687        let codes: [usize; 4] = [1, 0, usize::MAX, 2];
1688        let views = dictionary.views();
1689        builder.append_views_gathered(
1690            buffers,
1691            views,
1692            &Mask::from_iter([true, true, false, true]),
1693            // The null row's code is garbage; the builder must not look it up.
1694            |row| codes[row],
1695        );
1696
1697        let expected = <VarBinViewArray as FromIterator<_>>::from_iter([
1698            Some(LONG),
1699            Some(LONG),
1700            Some("tiny"),
1701            None,
1702            Some("small"),
1703        ]);
1704        assert_arrays_eq!(builder.finish_into_varbinview(), expected, &mut ctx);
1705    }
1706
1707    /// Scattered patches overwrite the fill view at their rows, and both are rebased onto the
1708    /// adopted buffers.
1709    #[test]
1710    fn test_append_views_scattered() {
1711        use crate::arrays::varbinview::build_views::BinaryView;
1712
1713        let mut ctx = SESSION.create_execution_ctx();
1714        let patch_values =
1715            <VarBinViewArray as FromIterator<_>>::from_iter([Some(LONG), Some("tiny")]);
1716        let mut buffers = patch_values
1717            .data_buffers()
1718            .iter()
1719            .map(|buffer| buffer.as_host().clone())
1720            .collect::<Vec<_>>();
1721
1722        let fill_bytes = ByteBuffer::copy_from("a fill value too long to inline");
1723        buffers.push(fill_bytes.clone());
1724        let fill = BinaryView::make_view(
1725            fill_bytes.as_slice(),
1726            u32::try_from(buffers.len() - 1).unwrap(),
1727            0,
1728        );
1729
1730        let mut builder = VarBinViewBuilder::with_capacity_in(
1731            DType::Utf8(Nullability::Nullable),
1732            8,
1733            BufferAllocatorRef::statically_allocated(),
1734        );
1735        let views = patch_values.views();
1736        builder.append_views_scattered(
1737            buffers,
1738            5,
1739            fill,
1740            [(1usize, views[0]), (3usize, views[1])].into_iter(),
1741            &Mask::from_iter([true, true, false, true, true]),
1742        );
1743
1744        let expected = <VarBinViewArray as FromIterator<_>>::from_iter([
1745            Some("a fill value too long to inline"),
1746            Some(LONG),
1747            None,
1748            Some("tiny"),
1749            Some("a fill value too long to inline"),
1750        ]);
1751        assert_arrays_eq!(builder.finish_into_varbinview(), expected, &mut ctx);
1752    }
1753
1754    /// A compacting builder must measure the buffers a gather hands it: with the middle
1755    /// dictionary value never referenced, adopting the heap whole would keep its bytes alive.
1756    /// Duplicate codes must share one rewritten copy, and null rows must not resolve their code.
1757    #[test]
1758    fn test_append_views_gathered_compacts_unreferenced_values() {
1759        const DEAD: &str = "a dead value nobody gathers, far too long to inline";
1760        const OTHER: &str = "another value far too long to inline";
1761
1762        let mut ctx = SESSION.create_execution_ctx();
1763        let dictionary =
1764            <VarBinViewArray as FromIterator<_>>::from_iter([Some(LONG), Some(DEAD), Some(OTHER)]);
1765        assert_eq!(dictionary.data_buffers().len(), 1);
1766        let buffers = dictionary
1767            .data_buffers()
1768            .iter()
1769            .map(|buffer| buffer.as_host().clone())
1770            .collect::<Vec<_>>();
1771
1772        let mut builder = VarBinViewBuilder::with_compaction_in(
1773            DType::Utf8(Nullability::Nullable),
1774            8,
1775            1.0,
1776            BufferAllocatorRef::statically_allocated(),
1777        );
1778        let codes: [usize; 5] = [2, 0, usize::MAX, 2, 0];
1779        builder.append_views_gathered(
1780            buffers,
1781            dictionary.views(),
1782            &Mask::from_iter([true, true, false, true, true]),
1783            |row| codes[row],
1784        );
1785
1786        let actual = builder.finish_into_varbinview();
1787        assert_eq!(actual.data_buffers().len(), 1);
1788        assert_eq!(
1789            actual.data_buffers()[0].len(),
1790            LONG.len() + OTHER.len(),
1791            "the rewritten buffer must hold each referenced value exactly once"
1792        );
1793
1794        let expected = <VarBinViewArray as FromIterator<_>>::from_iter([
1795            Some(OTHER),
1796            Some(LONG),
1797            None,
1798            Some(OTHER),
1799            Some(LONG),
1800        ]);
1801        assert_arrays_eq!(actual, expected, &mut ctx);
1802    }
1803
1804    /// A gather that references only a contiguous tail of the heap must adopt just that slice,
1805    /// zero-copy.
1806    #[test]
1807    fn test_append_views_gathered_slices_contiguous_range() {
1808        const TAIL: &str = "the referenced tail value, too long to inline";
1809
1810        let mut ctx = SESSION.create_execution_ctx();
1811        let dictionary = <VarBinViewArray as FromIterator<_>>::from_iter([Some(LONG), Some(TAIL)]);
1812        let heap = dictionary.data_buffers()[0].as_host().clone();
1813
1814        let mut builder = VarBinViewBuilder::with_compaction_in(
1815            DType::Utf8(Nullability::Nullable),
1816            8,
1817            1.0,
1818            BufferAllocatorRef::statically_allocated(),
1819        );
1820        builder.append_views_gathered(
1821            [heap.clone()],
1822            dictionary.views(),
1823            &Mask::new_true(2),
1824            |_| 1,
1825        );
1826
1827        let actual = builder.finish_into_varbinview();
1828        assert_eq!(actual.data_buffers().len(), 1);
1829        assert_eq!(actual.data_buffers()[0].len(), TAIL.len());
1830        // SAFETY: LONG.len() is in bounds of the heap.
1831        assert_eq!(actual.data_buffers()[0].as_host().as_ptr(), unsafe {
1832            heap.as_ptr().add(LONG.len())
1833        });
1834
1835        let expected = <VarBinViewArray as FromIterator<_>>::from_iter([Some(TAIL), Some(TAIL)]);
1836        assert_arrays_eq!(actual, expected, &mut ctx);
1837    }
1838
1839    /// A buffer whose referenced share clears the threshold is adopted whole, zero-copy.
1840    #[test]
1841    fn test_append_views_gathered_keeps_utilized_buffer() {
1842        const SHORTER: &str = "a shorter long value";
1843
1844        let mut ctx = SESSION.create_execution_ctx();
1845        let dictionary =
1846            <VarBinViewArray as FromIterator<_>>::from_iter([Some(LONG), Some(SHORTER)]);
1847        let heap = dictionary.data_buffers()[0].as_host().clone();
1848
1849        let mut builder = VarBinViewBuilder::with_compaction_in(
1850            DType::Utf8(Nullability::Nullable),
1851            8,
1852            0.5,
1853            BufferAllocatorRef::statically_allocated(),
1854        );
1855        builder.append_views_gathered(
1856            [heap.clone()],
1857            dictionary.views(),
1858            &Mask::new_true(1),
1859            |_| 0,
1860        );
1861
1862        let actual = builder.finish_into_varbinview();
1863        assert_eq!(actual.data_buffers().len(), 1);
1864        assert_eq!(actual.data_buffers()[0].as_host().as_ptr(), heap.as_ptr());
1865        assert_eq!(actual.data_buffers()[0].len(), heap.len());
1866
1867        let expected = <VarBinViewArray as FromIterator<_>>::from_iter([Some(LONG)]);
1868        assert_arrays_eq!(actual, expected, &mut ctx);
1869    }
1870
1871    /// An all-null gather references nothing, so a compacting builder must not retain any of the
1872    /// buffers — and must never resolve a code.
1873    #[test]
1874    fn test_append_views_gathered_all_null_drops_buffers() {
1875        let mut ctx = SESSION.create_execution_ctx();
1876        let dictionary = <VarBinViewArray as FromIterator<_>>::from_iter([Some(LONG)]);
1877        let buffers = dictionary
1878            .data_buffers()
1879            .iter()
1880            .map(|buffer| buffer.as_host().clone())
1881            .collect::<Vec<_>>();
1882
1883        let mut builder = VarBinViewBuilder::with_compaction_in(
1884            DType::Utf8(Nullability::Nullable),
1885            8,
1886            1.0,
1887            BufferAllocatorRef::statically_allocated(),
1888        );
1889        builder.append_views_gathered(buffers, dictionary.views(), &Mask::new_false(3), |_| {
1890            usize::MAX
1891        });
1892
1893        let actual = builder.finish_into_varbinview();
1894        assert!(
1895            actual.data_buffers().is_empty(),
1896            "an all-null gather must not retain any buffers"
1897        );
1898
1899        let expected = <VarBinViewArray as FromIterator<_>>::from_iter([None::<&str>, None, None]);
1900        assert_arrays_eq!(actual, expected, &mut ctx);
1901    }
1902
1903    /// A fully-inlined heap has zero utilization; a compacting builder must not retain it at all.
1904    #[test]
1905    fn test_append_buffer_with_lengths_drops_fully_inlined_heap() {
1906        let mut ctx = SESSION.create_execution_ctx();
1907        let mut builder = VarBinViewBuilder::with_compaction_in(
1908            DType::Utf8(Nullability::Nullable),
1909            4,
1910            1.0,
1911            BufferAllocatorRef::statically_allocated(),
1912        );
1913
1914        let heap = ByteBuffer::copy_from(b"shorttinysmall".as_slice());
1915        builder.append_buffer_with_lengths(heap, &[5u32, 4, 5], &Mask::new_true(3));
1916
1917        let actual = builder.finish_into_varbinview();
1918        assert!(
1919            actual.data_buffers().is_empty(),
1920            "a fully-inlined append must not retain any value bytes"
1921        );
1922
1923        let expected = <VarBinViewArray as FromIterator<_>>::from_iter([
1924            Some("short"),
1925            Some("tiny"),
1926            Some("small"),
1927        ]);
1928        assert_arrays_eq!(actual, expected, &mut ctx);
1929    }
1930
1931    #[test]
1932    fn test_utf8_builder() {
1933        let mut ctx = SESSION.create_execution_ctx();
1934        let mut builder = VarBinViewBuilder::with_capacity_in(
1935            DType::Utf8(Nullability::Nullable),
1936            10,
1937            BufferAllocatorRef::statically_allocated(),
1938        );
1939
1940        builder.append_value("Hello");
1941        builder.append_null();
1942        builder.append_value("World");
1943
1944        builder.append_nulls(2);
1945
1946        builder.append_zeros(2);
1947        builder.append_value("test");
1948
1949        let actual = builder.finish();
1950        let expected = <VarBinViewArray as FromIterator<_>>::from_iter([
1951            Some("Hello"),
1952            None,
1953            Some("World"),
1954            None,
1955            None,
1956            Some(""),
1957            Some(""),
1958            Some("test"),
1959        ]);
1960        for (index, value) in [
1961            Some("Hello"),
1962            None,
1963            Some("World"),
1964            None,
1965            None,
1966            Some(""),
1967            Some(""),
1968            Some("test"),
1969        ]
1970        .into_iter()
1971        .enumerate()
1972        {
1973            let expected = value.map_or_else(
1974                || Scalar::null(DType::Utf8(Nullability::Nullable)),
1975                |value| Scalar::utf8(value, Nullability::Nullable),
1976            );
1977            assert_eq!(actual.execute_scalar(index, &mut ctx).unwrap(), expected);
1978        }
1979        assert_arrays_eq!(actual, expected, &mut ctx);
1980    }
1981
1982    #[test]
1983    fn test_utf8_builder_with_extend() {
1984        let mut ctx = SESSION.create_execution_ctx();
1985        let array = {
1986            let mut builder = VarBinViewBuilder::with_capacity_in(
1987                DType::Utf8(Nullability::Nullable),
1988                10,
1989                BufferAllocatorRef::statically_allocated(),
1990            );
1991            builder.append_null();
1992            builder.append_value("Hello2");
1993            builder.finish()
1994        };
1995        let mut builder = VarBinViewBuilder::with_capacity_in(
1996            DType::Utf8(Nullability::Nullable),
1997            10,
1998            BufferAllocatorRef::statically_allocated(),
1999        );
2000
2001        builder.append_value("Hello1");
2002        array.append_to_builder(&mut builder, &mut ctx).unwrap();
2003        builder.append_nulls(2);
2004        builder.append_value("Hello3");
2005
2006        let actual = builder.finish_into_canonical(&mut ctx);
2007        let expected = <VarBinViewArray as FromIterator<_>>::from_iter([
2008            Some("Hello1"),
2009            None,
2010            Some("Hello2"),
2011            None,
2012            None,
2013            Some("Hello3"),
2014        ]);
2015        let actual = actual.into_array();
2016        for (index, value) in [
2017            Some("Hello1"),
2018            None,
2019            Some("Hello2"),
2020            None,
2021            None,
2022            Some("Hello3"),
2023        ]
2024        .into_iter()
2025        .enumerate()
2026        {
2027            let expected = value.map_or_else(
2028                || Scalar::null(DType::Utf8(Nullability::Nullable)),
2029                |value| Scalar::utf8(value, Nullability::Nullable),
2030            );
2031            assert_eq!(actual.execute_scalar(index, &mut ctx).unwrap(), expected);
2032        }
2033        assert_arrays_eq!(actual, expected.into_array(), &mut ctx);
2034    }
2035
2036    #[test]
2037    fn test_buffer_deduplication() -> VortexResult<()> {
2038        let array = {
2039            let mut builder = VarBinViewBuilder::with_capacity_in(
2040                DType::Utf8(Nullability::Nullable),
2041                10,
2042                BufferAllocatorRef::statically_allocated(),
2043            );
2044            builder.append_value("This is a long string that should not be inlined");
2045            builder.append_value("short string");
2046            builder.finish_into_varbinview()
2047        };
2048
2049        assert_eq!(array.data_buffers().len(), 1);
2050        let mut builder = VarBinViewBuilder::with_buffer_deduplication_in(
2051            DType::Utf8(Nullability::Nullable),
2052            10,
2053            BufferAllocatorRef::statically_allocated(),
2054        );
2055
2056        let mut ctx = SESSION.create_execution_ctx();
2057
2058        array.append_to_builder(&mut builder, &mut ctx)?;
2059        assert_eq!(builder.completed_block_count(), 1);
2060
2061        array
2062            .slice(1..2)?
2063            .append_to_builder(&mut builder, &mut ctx)?;
2064        array
2065            .slice(0..1)?
2066            .append_to_builder(&mut builder, &mut ctx)?;
2067        assert_eq!(builder.completed_block_count(), 1);
2068
2069        let array2 = {
2070            let mut builder = VarBinViewBuilder::with_capacity_in(
2071                DType::Utf8(Nullability::Nullable),
2072                10,
2073                BufferAllocatorRef::statically_allocated(),
2074            );
2075            builder.append_value("This is a long string that should not be inlined");
2076            builder.finish_into_varbinview()
2077        };
2078
2079        array2.append_to_builder(&mut builder, &mut ctx)?;
2080        assert_eq!(builder.completed_block_count(), 2);
2081
2082        array
2083            .slice(0..1)?
2084            .append_to_builder(&mut builder, &mut ctx)?;
2085        array2
2086            .slice(0..1)?
2087            .append_to_builder(&mut builder, &mut ctx)?;
2088        assert_eq!(builder.completed_block_count(), 2);
2089        let actual = builder.finish_into_varbinview();
2090        let long = "This is a long string that should not be inlined";
2091        assert_eq!(actual.dtype(), &DType::Utf8(Nullability::Nullable));
2092        assert_eq!(actual.len(), 7);
2093        for (index, value) in [long, "short string", "short string", long, long, long, long]
2094            .into_iter()
2095            .enumerate()
2096        {
2097            assert_eq!(
2098                actual.execute_scalar(index, &mut ctx)?,
2099                Scalar::utf8(value, Nullability::Nullable)
2100            );
2101        }
2102        Ok(())
2103    }
2104
2105    #[test]
2106    fn test_append_scalar() {
2107        let mut ctx = SESSION.create_execution_ctx();
2108        use crate::scalar::Scalar;
2109
2110        // Test with Utf8 builder.
2111        let mut utf8_builder = VarBinViewBuilder::with_capacity_in(
2112            DType::Utf8(Nullability::Nullable),
2113            10,
2114            BufferAllocatorRef::statically_allocated(),
2115        );
2116
2117        // Test appending a valid utf8 value.
2118        let utf8_scalar1 = Scalar::utf8("hello", Nullability::Nullable);
2119        utf8_builder.append_scalar(&utf8_scalar1).unwrap();
2120
2121        // Test appending another value.
2122        let utf8_scalar2 = Scalar::utf8("world", Nullability::Nullable);
2123        utf8_builder.append_scalar(&utf8_scalar2).unwrap();
2124
2125        // Test appending null value.
2126        let null_scalar = Scalar::null(DType::Utf8(Nullability::Nullable));
2127        utf8_builder.append_scalar(&null_scalar).unwrap();
2128
2129        let array = utf8_builder.finish();
2130        let expected =
2131            <VarBinViewArray as FromIterator<_>>::from_iter([Some("hello"), Some("world"), None]);
2132        assert_arrays_eq!(&array, &expected, &mut ctx);
2133
2134        // Test with Binary builder.
2135        let mut binary_builder = VarBinViewBuilder::with_capacity_in(
2136            DType::Binary(Nullability::Nullable),
2137            10,
2138            BufferAllocatorRef::statically_allocated(),
2139        );
2140
2141        let binary_scalar = Scalar::binary(vec![1u8, 2, 3], Nullability::Nullable);
2142        binary_builder.append_scalar(&binary_scalar).unwrap();
2143
2144        let binary_null = Scalar::null(DType::Binary(Nullability::Nullable));
2145        binary_builder.append_scalar(&binary_null).unwrap();
2146
2147        let binary_array = binary_builder.finish();
2148        let expected =
2149            <VarBinViewArray as FromIterator<_>>::from_iter([Some(vec![1u8, 2, 3]), None]);
2150        assert_arrays_eq!(&binary_array, &expected, &mut ctx);
2151
2152        // Test wrong dtype error.
2153        let mut builder = VarBinViewBuilder::with_capacity_in(
2154            DType::Utf8(Nullability::NonNullable),
2155            10,
2156            BufferAllocatorRef::statically_allocated(),
2157        );
2158        let wrong_scalar = Scalar::from(42i32);
2159        assert!(builder.append_scalar(&wrong_scalar).is_err());
2160    }
2161
2162    #[test]
2163    fn test_buffer_growth_strategies() {
2164        use super::BufferGrowthStrategy;
2165
2166        // Test Fixed strategy
2167        let mut strategy = BufferGrowthStrategy::fixed(1024);
2168
2169        // Should always return the fixed size
2170        assert_eq!(strategy.next_size(), 1024);
2171        assert_eq!(strategy.next_size(), 1024);
2172        assert_eq!(strategy.next_size(), 1024);
2173
2174        // Test Exponential strategy
2175        let mut strategy = BufferGrowthStrategy::exponential(1024, 8192);
2176
2177        // Should double each time until hitting max_size
2178        assert_eq!(strategy.next_size(), 1024); // First: 1024
2179        assert_eq!(strategy.next_size(), 2048); // Second: 2048
2180        assert_eq!(strategy.next_size(), 4096); // Third: 4096
2181        assert_eq!(strategy.next_size(), 8192); // Fourth: 8192 (max)
2182        assert_eq!(strategy.next_size(), 8192); // Fifth: 8192 (capped)
2183    }
2184
2185    #[test]
2186    fn test_large_value_allocation() {
2187        use super::BufferGrowthStrategy;
2188        use super::VarBinViewBuilder;
2189
2190        let mut builder = VarBinViewBuilder::new_in(
2191            DType::Binary(Nullability::Nullable),
2192            10,
2193            Default::default(),
2194            BufferGrowthStrategy::exponential(1024, 4096),
2195            0.0,
2196            BufferAllocatorRef::statically_allocated(),
2197        );
2198
2199        // Create a value larger than max_size
2200        let large_value = vec![0u8; 8192];
2201
2202        // Should successfully append the large value
2203        builder.append_value(&large_value);
2204
2205        let array = builder.finish_into_varbinview();
2206        assert_eq!(array.len(), 1);
2207
2208        // Verify the value was stored correctly
2209        let retrieved = array
2210            .execute_scalar(0, &mut SESSION.create_execution_ctx())
2211            .unwrap()
2212            .as_binary()
2213            .value()
2214            .cloned()
2215            .unwrap();
2216        assert_eq!(retrieved.len(), 8192);
2217        assert_eq!(retrieved.as_slice(), &large_value);
2218    }
2219}