Skip to main content

datafusion_physical_expr_common/
binary_view_map.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5//! [`ArrowBytesViewMap`] and [`ArrowBytesViewSet`] for storing maps/sets of values from
6//! `StringViewArray`/`BinaryViewArray`.
7use crate::binary_map::{OutputType, single_null_buffer};
8use arrow::array::cast::AsArray;
9use arrow::array::{
10    Array, ArrayRef, BinaryViewArray, BinaryViewBuilder, ByteView, StringViewBuilder,
11    make_view,
12};
13use arrow::buffer::{Buffer, ScalarBuffer};
14use arrow::datatypes::{BinaryViewType, ByteViewType, DataType, StringViewType};
15use datafusion_common::hash_utils::RandomState;
16use datafusion_common::hash_utils::create_hashes;
17use datafusion_common::utils::proxy::VecAllocExt;
18use datafusion_common::{Result, exec_err};
19use std::fmt::Debug;
20use std::sync::Arc;
21
22/// HashSet optimized for storing string or binary values that can produce that
23/// the final set as a `GenericBinaryViewArray` with minimal copies.
24#[derive(Debug)]
25pub struct ArrowBytesViewSet(ArrowBytesViewMap<()>);
26
27impl ArrowBytesViewSet {
28    /// Creates a set that does not pre-allocate its hash table.
29    ///
30    /// See [`ArrowBytesViewMap::new`] for when to prefer this over
31    /// [`Self::with_capacity`].
32    pub fn new(output_type: OutputType) -> Self {
33        Self(ArrowBytesViewMap::new(output_type))
34    }
35
36    /// Creates a set with room for `map_capacity` entries.
37    ///
38    /// See [`ArrowBytesViewMap::with_capacity`].
39    pub fn with_capacity(output_type: OutputType, map_capacity: usize) -> Self {
40        Self(ArrowBytesViewMap::with_capacity(output_type, map_capacity))
41    }
42
43    /// Inserts each value from `values` into the set
44    pub fn insert(&mut self, values: &ArrayRef) {
45        fn make_payload_fn(_value: Option<&[u8]>) {}
46        fn observe_payload_fn(_payload: ()) {}
47        self.0
48            .insert_if_new(values, make_payload_fn, observe_payload_fn);
49    }
50
51    /// Return the contents of this map and replace it with a new empty map with
52    /// the same output type
53    pub fn take(&mut self) -> Self {
54        Self(self.0.take())
55    }
56
57    /// Converts this set into a `StringViewArray` or `BinaryViewArray`
58    /// containing each distinct value that was interned.
59    /// This is done without copying the values.
60    pub fn into_state(self) -> ArrayRef {
61        self.0.into_state()
62    }
63
64    /// Returns the total number of distinct values (including nulls) seen so far
65    pub fn len(&self) -> usize {
66        self.0.len()
67    }
68
69    pub fn is_empty(&self) -> bool {
70        self.0.is_empty()
71    }
72
73    /// returns the total number of distinct values (not including nulls) seen so far
74    pub fn non_null_len(&self) -> usize {
75        self.0.non_null_len()
76    }
77
78    /// Return the total size, in bytes, of memory used to store the data in
79    /// this set, not including `self`
80    pub fn size(&self) -> usize {
81        self.0.size()
82    }
83}
84
85/// Optimized map for storing Arrow "byte view" types (`StringView`, `BinaryView`)
86/// values that can produce the set of keys on
87/// output as `GenericBinaryViewArray` without copies.
88///
89/// Equivalent to `HashSet<String, V>` but with better performance if you need
90/// to emit the keys as an Arrow `StringViewArray` / `BinaryViewArray`. For other
91/// purposes it is the same as a `HashMap<String, V>`
92///
93/// # Generic Arguments
94///
95/// * `V`: payload type
96///
97/// # Description
98///
99/// This is a specialized HashMap with the following properties:
100///
101/// 1. Optimized for storing and emitting Arrow byte types  (e.g.
102///    `StringViewArray` / `BinaryViewArray`) very efficiently by minimizing copying of
103///    the string values themselves, both when inserting and when emitting the
104///    final array.
105///
106/// 2. Retains the insertion order of entries in the final array. The values are
107///    in the same order as they were inserted.
108///
109/// Note this structure can be used as a `HashSet` by specifying the value type
110/// as `()`, as is done by [`ArrowBytesViewSet`].
111///
112/// This map is used by the special `COUNT DISTINCT` aggregate function to
113/// store the distinct values, and by the `GROUP BY` operator to store
114/// group values when they are a single string array.
115/// Max size of the in-progress buffer before flushing to completed buffers
116const BYTE_VIEW_MAX_BLOCK_SIZE: usize = 2 * 1024 * 1024;
117
118pub struct ArrowBytesViewMap<V>
119where
120    V: Debug + PartialEq + Eq + Clone + Copy + Default,
121{
122    /// Should the output be StringView or BinaryView?
123    output_type: OutputType,
124    /// Underlying hash set for each distinct value
125    map: hashbrown::hash_table::HashTable<Entry<V>>,
126    /// Hash table capacity to re-create the map with in [`Self::take`], so a
127    /// map built with [`Self::with_capacity`] keeps its pre-allocation when it
128    /// is emptied and reused
129    initial_map_capacity: usize,
130
131    /// Views for all stored values (in insertion order)
132    views: Vec<u128>,
133    /// In-progress buffer for out-of-line string data
134    in_progress: Vec<u8>,
135    /// Completed buffers containing string data
136    completed: Vec<Buffer>,
137
138    /// random state used to generate hashes
139    random_state: RandomState,
140    /// buffer that stores hash values (reused across batches to save allocations)
141    hashes_buffer: Vec<u64>,
142    /// `(payload, null_index)` for the 'null' value, if any
143    /// NOTE null_index is the logical index in the final array, not the index
144    /// in the buffer
145    null: Option<(V, usize)>,
146}
147
148/// The size, in number of entries, of the hash table pre-allocated by
149/// [`ArrowBytesViewMap::with_capacity`]. It is a warm up size for maps that go
150/// on to hold many values, not a bound on what the map can hold.
151pub const INITIAL_MAP_CAPACITY: usize = 512;
152
153impl<V> ArrowBytesViewMap<V>
154where
155    V: Debug + PartialEq + Eq + Clone + Copy + Default,
156{
157    /// Creates a map that does not pre-allocate its hash table.
158    ///
159    /// Use this when maps are created in large numbers and most of them stay
160    /// small, such as the per group `COUNT(DISTINCT)` accumulators that
161    /// `GroupsAccumulatorAdapter` creates one of per group. There the
162    /// pre-allocation dwarfs the values the map actually holds.
163    pub fn new(output_type: OutputType) -> Self {
164        Self::with_capacity(output_type, 0)
165    }
166
167    /// Creates a map whose hash table is pre-allocated for `map_capacity`
168    /// entries.
169    ///
170    /// Use this for the few long lived maps that are each expected to hold many
171    /// values, such as the single map backing a `GROUP BY` on one string
172    /// column. The capacity is preserved across [`Self::take`].
173    pub fn with_capacity(output_type: OutputType, map_capacity: usize) -> Self {
174        Self {
175            output_type,
176            map: hashbrown::hash_table::HashTable::with_capacity(map_capacity),
177            initial_map_capacity: map_capacity,
178            views: Vec::new(),
179            in_progress: Vec::new(),
180            completed: Vec::new(),
181            random_state: RandomState::default(),
182            hashes_buffer: vec![],
183            null: None,
184        }
185    }
186
187    /// Return the contents of this map and replace it with a new empty map with
188    /// the same output type
189    pub fn take(&mut self) -> Self {
190        let mut new_self =
191            Self::with_capacity(self.output_type, self.initial_map_capacity);
192        std::mem::swap(self, &mut new_self);
193        new_self
194    }
195
196    /// Empties this map and releases every allocation it holds, so
197    /// [`Self::size`] drops to approximately zero.
198    ///
199    /// This is the difference from [`Self::take`]: `take` restores the capacity
200    /// the map was configured with so the emptied map stays warm for continued
201    /// use, which is what emitting wants, whereas here the point is to hand the
202    /// memory back, as before spilling or before a downstream sort. The
203    /// configured capacity is remembered, so the next [`Self::take`] warms the
204    /// map up again.
205    pub fn clear_and_release(&mut self) {
206        let mut released = Self::with_capacity(self.output_type, 0);
207        released.initial_map_capacity = self.initial_map_capacity;
208        *self = released;
209    }
210
211    /// Inserts each value from `values` into the map, invoking `payload_fn` for
212    /// each value if *not* already present, deferring the allocation of the
213    /// payload until it is needed.
214    ///
215    /// Note that this is different than a normal map that would replace the
216    /// existing entry
217    ///
218    /// # Arguments:
219    ///
220    /// `values`: array whose values are inserted
221    ///
222    /// `make_payload_fn`:  invoked for each value that is not already present
223    /// to create the payload, in order of the values in `values`
224    ///
225    /// `observe_payload_fn`: invoked once, for each value in `values`, that was
226    /// already present in the map, with corresponding payload value.
227    ///
228    /// # Returns
229    ///
230    /// The payload value for the entry, either the existing value or
231    /// the newly inserted value
232    ///
233    /// # Safety:
234    ///
235    /// Note that `make_payload_fn` and `observe_payload_fn` are only invoked
236    /// with valid values from `values`, not for the `NULL` value.
237    pub fn insert_if_new<MP, OP>(
238        &mut self,
239        values: &ArrayRef,
240        make_payload_fn: MP,
241        observe_payload_fn: OP,
242    ) where
243        MP: FnMut(Option<&[u8]>) -> V,
244        OP: FnMut(V),
245    {
246        // Sanity check array type
247        match self.output_type {
248            OutputType::BinaryView => {
249                assert!(matches!(values.data_type(), DataType::BinaryView));
250                self.insert_if_new_inner::<MP, OP, BinaryViewType>(
251                    values,
252                    make_payload_fn,
253                    observe_payload_fn,
254                )
255            }
256            OutputType::Utf8View => {
257                assert!(matches!(values.data_type(), DataType::Utf8View));
258                self.insert_if_new_inner::<MP, OP, StringViewType>(
259                    values,
260                    make_payload_fn,
261                    observe_payload_fn,
262                )
263            }
264            _ => unreachable!("Utf8/Binary should use `ArrowBytesSet`"),
265        }
266    }
267
268    /// Generic version of [`Self::insert_if_new`] that handles `ByteViewType`
269    /// (both StringView and BinaryView)
270    ///
271    /// Note this is the only function that is generic on [`ByteViewType`], which
272    /// avoids having to template the entire structure,  making the code
273    /// simpler and understand and reducing code bloat due to duplication.
274    ///
275    /// See comments on `insert_if_new` for more details
276    fn insert_if_new_inner<MP, OP, B>(
277        &mut self,
278        values: &ArrayRef,
279        mut make_payload_fn: MP,
280        mut observe_payload_fn: OP,
281    ) where
282        MP: FnMut(Option<&[u8]>) -> V,
283        OP: FnMut(V),
284        B: ByteViewType,
285    {
286        // step 1: compute hashes
287        let batch_hashes = &mut self.hashes_buffer;
288        batch_hashes.clear();
289        batch_hashes.resize(values.len(), 0);
290        create_hashes([values], &self.random_state, batch_hashes)
291            // hash is supported for all types and create_hashes only
292            // returns errors for unsupported types
293            .unwrap();
294
295        // step 2: insert each value into the set, if not already present
296        let values = values.as_byte_view::<B>();
297
298        // Get raw views buffer for direct comparison
299        let input_views = values.views();
300
301        // Ensure lengths are equivalent
302        assert_eq!(values.len(), self.hashes_buffer.len());
303
304        for i in 0..values.len() {
305            let view_u128 = input_views[i];
306            let hash = self.hashes_buffer[i];
307
308            // handle null value via validity bitmap check
309            if values.is_null(i) {
310                let payload = if let Some(&(payload, _offset)) = self.null.as_ref() {
311                    payload
312                } else {
313                    let payload = make_payload_fn(None);
314                    let null_index = self.views.len();
315                    self.views.push(0);
316                    self.null = Some((payload, null_index));
317                    payload
318                };
319                observe_payload_fn(payload);
320                continue;
321            }
322
323            // Extract length from the view (first 4 bytes of u128 in little-endian)
324            let len = view_u128 as u32;
325
326            // Check if value already exists
327            let maybe_payload = {
328                // Borrow completed and in_progress for comparison
329                let completed = &self.completed;
330                let in_progress = &self.in_progress;
331
332                self.map
333                    .find(hash, |header| {
334                        if header.hash != hash {
335                            return false;
336                        }
337
338                        // Fast path: inline strings can be compared directly
339                        if len <= 12 {
340                            return header.view == view_u128;
341                        }
342
343                        // For larger strings: first compare the 4-byte prefix
344                        let stored_prefix = (header.view >> 32) as u32;
345                        let input_prefix = (view_u128 >> 32) as u32;
346                        if stored_prefix != input_prefix {
347                            return false;
348                        }
349
350                        // Prefix matched - compare full bytes
351                        let byte_view = ByteView::from(header.view);
352                        let stored_len = byte_view.length as usize;
353                        let buffer_index = byte_view.buffer_index as usize;
354                        let offset = byte_view.offset as usize;
355
356                        let stored_value = if buffer_index < completed.len() {
357                            &completed[buffer_index].as_slice()
358                                [offset..offset + stored_len]
359                        } else {
360                            &in_progress[offset..offset + stored_len]
361                        };
362                        let input_value: &[u8] = values.value(i).as_ref();
363                        stored_value == input_value
364                    })
365                    .map(|entry| entry.payload)
366            };
367
368            let payload = if let Some(payload) = maybe_payload {
369                payload
370            } else {
371                // no existing value, make a new one
372                let (new_view, payload) = if len <= 12 {
373                    // Inline path: bytes are already packed in view_u128.
374                    // The inline ByteView format is [len:u32 LE][data:12 bytes zero-padded],
375                    // so extracting bytes from the u128 avoids a round-trip through
376                    // values.value(i) (which reads the views buffer and returns the same slice).
377                    let view_bytes = view_u128.to_le_bytes();
378                    let value = &view_bytes[4..4 + len as usize];
379                    let payload = make_payload_fn(Some(value));
380                    // For inline strings, the stored view is identical to the input view:
381                    // make_view(value, 0, 0) produces the same u128 as view_u128.
382                    //
383                    // SAFETY: view_u128 was a valid view, and the enclosing `len <= 12`
384                    // ensures it is inline
385                    let new_view = unsafe { self.append_inline_view(view_u128) };
386                    (new_view, payload)
387                } else {
388                    let value: &[u8] = values.value(i).as_ref();
389                    let payload = make_payload_fn(Some(value));
390                    let new_view = self.append_value(value);
391                    (new_view, payload)
392                };
393
394                let new_header = Entry {
395                    view: new_view,
396                    hash,
397                    payload,
398                };
399
400                self.map.insert_unique(hash, new_header, |h| h.hash);
401                payload
402            };
403            observe_payload_fn(payload);
404        }
405    }
406
407    /// Returns the bytes for the key at `index`, irrespective of nullness.
408    fn key(&self, index: usize) -> &[u8] {
409        let view = &self.views[index];
410        let byte_view = ByteView::from(*view);
411        let length = byte_view.length as usize;
412        if length <= 12 {
413            // SAFETY: `view` is a valid inline view with `length` bytes.
414            unsafe { BinaryViewArray::inline_value(view, length) }
415        } else {
416            let buffer_index = byte_view.buffer_index as usize;
417            let offset = byte_view.offset as usize;
418            if buffer_index < self.completed.len() {
419                &self.completed[buffer_index][offset..offset + length]
420            } else {
421                &self.in_progress[offset..offset + length]
422            }
423        }
424    }
425
426    /// Converts this set into a `StringViewArray`, or `BinaryViewArray`,
427    /// containing each distinct value
428    /// that was inserted. This is done without copying the values.
429    ///
430    /// The values are guaranteed to be returned in the same order in which
431    /// they were first seen.
432    pub fn into_state(mut self) -> ArrayRef {
433        // Flush any remaining in-progress buffer
434        if !self.in_progress.is_empty() {
435            let flushed = std::mem::take(&mut self.in_progress);
436            self.completed.push(Buffer::from_vec(flushed));
437        }
438
439        // Build null buffer if we have any nulls
440        let null_buffer = match self.null {
441            Some((_payload, index)) => Some(single_null_buffer(self.views.len(), index)),
442            None => None,
443        };
444
445        let views = ScalarBuffer::from(self.views);
446        let array = unsafe {
447            BinaryViewArray::new_unchecked(views, self.completed.into(), null_buffer)
448        };
449
450        match self.output_type {
451            OutputType::BinaryView => Arc::new(array),
452            OutputType::Utf8View => {
453                // SAFETY: all input was valid utf8
454                let array = unsafe { array.to_string_view_unchecked() };
455                Arc::new(array)
456            }
457            _ => unreachable!("Utf8/Binary should use `ArrowBytesMap`"),
458        }
459    }
460
461    /// Copies keys at `indices` into an array without changing this map.
462    ///
463    /// Keys are returned in index order, and duplicate indices are supported.
464    pub fn keys<I>(&self, indices: I) -> Result<ArrayRef>
465    where
466        I: IntoIterator<Item = usize>,
467    {
468        let indices = indices.into_iter();
469        let capacity = indices.size_hint().0;
470        let num_keys = self.views.len();
471        let null_index = self.null.map(|(_, index)| index);
472
473        macro_rules! build_keys {
474            ($builder:ty, $value:expr) => {{
475                let mut builder = <$builder>::with_capacity(capacity);
476                for index in indices {
477                    if index >= num_keys {
478                        return exec_err!(
479                            "Key index {index} is out of bounds for {num_keys} keys"
480                        );
481                    }
482                    if null_index == Some(index) {
483                        builder.append_null();
484                    } else {
485                        builder.append_value($value(self.key(index)));
486                    }
487                }
488                Arc::new(builder.finish()) as ArrayRef
489            }};
490        }
491
492        Ok(match self.output_type {
493            OutputType::BinaryView => build_keys!(BinaryViewBuilder, |value| value),
494            OutputType::Utf8View => build_keys!(StringViewBuilder, |value| unsafe {
495                // Inputs to an Utf8View map are validated UTF-8.
496                std::str::from_utf8_unchecked(value)
497            }),
498            _ => unreachable!("Utf8/Binary should use `ArrowBytesMap`"),
499        })
500    }
501
502    /// Append an already-computed inline view (len <= 12) directly, bypassing
503    /// buffer allocation.
504    ///
505    /// Returns the view that was stored (identical to the argument).
506    ///
507    /// # Safety
508    ///
509    /// `view` must be a valid inline `ByteView`: the length field in the low
510    /// 32 bits must be <= 12, and the remaining 12 bytes must hold the
511    /// value's bytes (zero-padded if shorter). Calling with a non-inline view
512    /// would store a value that downstream `views` consumers interpret as
513    /// `[buffer_index, offset]` into the `completed`/`in_progress` buffers,
514    /// which is unsound for any view that didn't originate from a real
515    /// allocation in those buffers.
516    unsafe fn append_inline_view(&mut self, view: u128) -> u128 {
517        self.views.push(view);
518        view
519    }
520
521    /// Append a value to our buffers and return the view pointing to it
522    fn append_value(&mut self, value: &[u8]) -> u128 {
523        let len = value.len();
524        let view = if len <= 12 {
525            make_view(value, 0, 0)
526        } else {
527            // Ensure buffer is big enough
528            if self.in_progress.len() + len > BYTE_VIEW_MAX_BLOCK_SIZE {
529                let flushed = std::mem::replace(
530                    &mut self.in_progress,
531                    Vec::with_capacity(BYTE_VIEW_MAX_BLOCK_SIZE),
532                );
533                self.completed.push(Buffer::from_vec(flushed));
534            }
535
536            let buffer_index = self.completed.len() as u32;
537            let offset = self.in_progress.len() as u32;
538            self.in_progress.extend_from_slice(value);
539
540            make_view(value, buffer_index, offset)
541        };
542
543        self.views.push(view);
544        view
545    }
546
547    /// Total number of entries (including null, if present)
548    pub fn len(&self) -> usize {
549        self.non_null_len() + self.null.map(|_| 1).unwrap_or(0)
550    }
551
552    /// Is the set empty?
553    pub fn is_empty(&self) -> bool {
554        self.map.is_empty() && self.null.is_none()
555    }
556
557    /// Number of non null entries
558    pub fn non_null_len(&self) -> usize {
559        self.map.len()
560    }
561
562    /// Return the total size, in bytes, of memory used to store the data in
563    /// this set, not including `self` or input-array buffers.
564    pub fn size(&self) -> usize {
565        // All fields below own their allocations. Count retained capacity rather
566        // than used length because this value drives memory accounting.
567        //
568        // `HashTable::allocation_size` reports the whole hashbrown allocation,
569        // which is the entry array plus the control bytes plus the trailing
570        // group, so it is larger than `capacity() * size_of::<Entry<V>>()`. It
571        // is a constant time layout calculation, not a walk of the table.
572        let map_size = self.map.allocation_size();
573        let views_size = self.views.allocated_size();
574        let in_progress_size = self.in_progress.allocated_size();
575        let completed_size = self.completed.allocated_size()
576            + self.completed.iter().map(Buffer::capacity).sum::<usize>();
577
578        map_size
579            + views_size
580            + in_progress_size
581            + completed_size
582            + self.hashes_buffer.allocated_size()
583    }
584}
585
586impl<V> Debug for ArrowBytesViewMap<V>
587where
588    V: Debug + PartialEq + Eq + Clone + Copy + Default,
589{
590    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
591        f.debug_struct("ArrowBytesMap")
592            .field("map", &"<map>")
593            .field("map_allocation_size", &self.map.allocation_size())
594            .field("views_len", &self.views.len())
595            .field("completed_buffers", &self.completed.len())
596            .field("random_state", &self.random_state)
597            .field("hashes_buffer", &self.hashes_buffer)
598            .finish()
599    }
600}
601
602/// Entry in the hash table -- see [`ArrowBytesViewMap`] for more details
603///
604/// Stores the view pointing to our internal buffers, eliminating the need
605/// for a separate builder index. For inline strings (<=12 bytes), the view
606/// contains the entire value. For out-of-line strings, the view contains
607/// buffer_index and offset pointing directly to our storage.
608#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
609struct Entry<V>
610where
611    V: Debug + PartialEq + Eq + Clone + Copy + Default,
612{
613    /// The u128 view pointing to our internal buffers. For inline strings,
614    /// this contains the complete value. For larger strings, this contains
615    /// the buffer_index/offset into our completed/in_progress buffers.
616    view: u128,
617
618    hash: u64,
619
620    /// value stored by the entry
621    payload: V,
622}
623
624#[cfg(test)]
625mod tests {
626    use arrow::array::{GenericByteViewArray, StringViewArray};
627    use datafusion_common::HashMap;
628    use std::mem::size_of;
629
630    use super::*;
631
632    // asserts that the set contains the expected strings, in the same order
633    fn assert_set(set: ArrowBytesViewSet, expected: &[Option<&str>]) {
634        let strings = set.into_state();
635        let strings = strings.as_string_view();
636        let state = strings.into_iter().collect::<Vec<_>>();
637        assert_eq!(state, expected);
638    }
639
640    #[test]
641    fn string_view_set_empty() {
642        let mut set = ArrowBytesViewSet::new(OutputType::Utf8View);
643        let array: ArrayRef = Arc::new(StringViewArray::new_null(0));
644        set.insert(&array);
645        assert_eq!(set.len(), 0);
646        assert_eq!(set.non_null_len(), 0);
647        assert_set(set, &[]);
648    }
649
650    #[test]
651    fn string_view_set_one_null() {
652        let mut set = ArrowBytesViewSet::new(OutputType::Utf8View);
653        let array: ArrayRef = Arc::new(StringViewArray::new_null(1));
654        set.insert(&array);
655        assert_eq!(set.len(), 1);
656        assert_eq!(set.non_null_len(), 0);
657        assert_set(set, &[None]);
658    }
659
660    #[test]
661    fn string_view_set_many_null() {
662        let mut set = ArrowBytesViewSet::new(OutputType::Utf8View);
663        let array: ArrayRef = Arc::new(StringViewArray::new_null(11));
664        set.insert(&array);
665        assert_eq!(set.len(), 1);
666        assert_eq!(set.non_null_len(), 0);
667        assert_set(set, &[None]);
668    }
669
670    #[test]
671    fn test_string_view_set_basic() {
672        // basic test for mixed small and large string values
673        let values = GenericByteViewArray::from(vec![
674            Some("a"),
675            Some("b"),
676            Some("CXCCCCCCCCAABB"), // 14 bytes
677            Some(""),
678            Some("cbcxx"), // 5 bytes
679            None,
680            Some("AAAAAAAA"),     // 8 bytes
681            Some("BBBBBQBBBAAA"), // 12 bytes
682            Some("a"),
683            Some("cbcxx"),
684            Some("b"),
685            Some("cbcxx"),
686            Some(""),
687            None,
688            Some("BBBBBQBBBAAA"),
689            Some("BBBBBQBBBAAA"),
690            Some("AAAAAAAA"),
691            Some("CXCCCCCCCCAABB"),
692        ]);
693
694        let mut set = ArrowBytesViewSet::new(OutputType::Utf8View);
695        let array: ArrayRef = Arc::new(values);
696        set.insert(&array);
697        // values mut appear be in the order they were inserted
698        assert_set(
699            set,
700            &[
701                Some("a"),
702                Some("b"),
703                Some("CXCCCCCCCCAABB"),
704                Some(""),
705                Some("cbcxx"),
706                None,
707                Some("AAAAAAAA"),
708                Some("BBBBBQBBBAAA"),
709            ],
710        );
711    }
712
713    #[test]
714    fn test_string_set_non_utf8() {
715        // basic test for mixed small and large string values
716        let values = GenericByteViewArray::from(vec![
717            Some("a"),
718            Some("✨🔥✨🔥✨🔥✨🔥✨🔥✨🔥✨🔥✨🔥"),
719            Some("🔥"),
720            Some("✨✨✨"),
721            Some("foobarbaz"),
722            Some("🔥"),
723            Some("✨🔥✨🔥✨🔥✨🔥✨🔥✨🔥✨🔥✨🔥"),
724        ]);
725
726        let mut set = ArrowBytesViewSet::new(OutputType::Utf8View);
727        let array: ArrayRef = Arc::new(values);
728        set.insert(&array);
729        // strings mut appear be in the order they were inserted
730        assert_set(
731            set,
732            &[
733                Some("a"),
734                Some("✨🔥✨🔥✨🔥✨🔥✨🔥✨🔥✨🔥✨🔥"),
735                Some("🔥"),
736                Some("✨✨✨"),
737                Some("foobarbaz"),
738            ],
739        );
740    }
741
742    // Test use of binary output type
743    #[test]
744    fn test_binary_set() {
745        let v: Vec<Option<&[u8]>> = vec![
746            Some(b"a"),
747            Some(b"CXCCCCCCCCCCCCC"),
748            None,
749            Some(b"CXCCCCCCCCCCCCC"),
750        ];
751        let values: ArrayRef = Arc::new(BinaryViewArray::from(v));
752
753        let expected: Vec<Option<&[u8]>> =
754            vec![Some(b"a"), Some(b"CXCCCCCCCCCCCCC"), None];
755        let expected: ArrayRef = Arc::new(GenericByteViewArray::from(expected));
756
757        let mut set = ArrowBytesViewSet::new(OutputType::BinaryView);
758        set.insert(&values);
759        assert_eq!(&set.into_state(), &expected);
760    }
761
762    // inserting strings into the set does not increase reported memory
763    #[test]
764    fn test_string_set_memory_usage() {
765        let strings1 = StringViewArray::from(vec![
766            Some("a"),
767            Some("b"),
768            Some("CXCCCCCCCCCCC"), // 13 bytes
769            Some("AAAAAAAA"),      // 8 bytes
770            Some("BBBBBQBBB"),     // 9 bytes
771        ]);
772        let total_strings1_len = strings1
773            .iter()
774            .map(|s| s.map(|s| s.len()).unwrap_or(0))
775            .sum::<usize>();
776        let values1: ArrayRef = Arc::new(StringViewArray::from(strings1));
777
778        // Much larger strings in strings2
779        let strings2 = StringViewArray::from(vec![
780            "FOO".repeat(1000),
781            "BAR larger than 12 bytes.".repeat(100_000),
782            "more unique.".repeat(1000),
783            "more unique2.".repeat(1000),
784            "FOO".repeat(3000),
785        ]);
786        let total_strings2_len = strings2
787            .iter()
788            .map(|s| s.map(|s| s.len()).unwrap_or(0))
789            .sum::<usize>();
790        let values2: ArrayRef = Arc::new(StringViewArray::from(strings2));
791
792        let mut set = ArrowBytesViewSet::new(OutputType::Utf8View);
793        let size_empty = set.size();
794
795        set.insert(&values1);
796        let size_after_values1 = set.size();
797        assert!(size_empty < size_after_values1);
798        assert!(
799            size_after_values1 > total_strings1_len,
800            "expect {size_after_values1} to be more than {total_strings1_len}"
801        );
802        assert!(size_after_values1 < total_strings1_len + total_strings2_len);
803
804        // inserting the same strings should not affect the size
805        set.insert(&values1);
806        assert_eq!(set.size(), size_after_values1);
807        assert_eq!(set.len(), 5);
808
809        // inserting the large strings should increase the reported size
810        set.insert(&values2);
811        let size_after_values2 = set.size();
812        assert!(size_after_values2 > size_after_values1);
813
814        assert_eq!(set.len(), 10);
815    }
816
817    /// A lower bound on the bytes a hashbrown table holding `entries` entries
818    /// of type `T` must allocate: one entry slot and one control byte each.
819    /// Derived independently of the production accounting so it can bracket it.
820    fn min_table_bytes<T>(entries: usize) -> usize {
821        entries * (size_of::<T>() + 1)
822    }
823
824    #[test]
825    fn map_new_does_not_allocate() {
826        let map = ArrowBytesViewMap::<()>::new(OutputType::Utf8View);
827
828        assert_eq!(map.map.capacity(), 0);
829        assert_eq!(map.map.allocation_size(), 0);
830        assert_eq!(map.size(), 0);
831    }
832
833    #[test]
834    fn test_size_counts_initial_hash_table_capacity() {
835        let map = ArrowBytesViewMap::<()>::with_capacity(
836            OutputType::Utf8View,
837            INITIAL_MAP_CAPACITY,
838        );
839
840        assert!(map.map.capacity() >= INITIAL_MAP_CAPACITY);
841        assert_eq!(map.size(), map.map.allocation_size());
842
843        // Before this accounting was corrected the map reported exactly
844        // `capacity() * size_of::<Entry<V>>()`, which leaves out the control
845        // bytes and undercounts the real allocation by roughly half.
846        let lower_bound = min_table_bytes::<Entry<()>>(map.map.capacity());
847        assert!(
848            map.size() >= lower_bound,
849            "expected {} to be at least {lower_bound}",
850            map.size()
851        );
852        assert!(
853            map.size() <= 2 * lower_bound + 64,
854            "expected {} to be within a small factor of {lower_bound}",
855            map.size()
856        );
857        assert!(
858            map.size() > map.map.capacity() * size_of::<Entry<()>>(),
859            "expected {} to exceed {}",
860            map.size(),
861            map.map.capacity() * size_of::<Entry<()>>()
862        );
863    }
864
865    #[test]
866    fn take_preserves_the_capacity_the_map_was_built_with() {
867        let mut preallocated = ArrowBytesViewMap::<()>::with_capacity(
868            OutputType::Utf8View,
869            INITIAL_MAP_CAPACITY,
870        );
871        let capacity = preallocated.map.capacity();
872        preallocated.take();
873        assert_eq!(preallocated.map.capacity(), capacity);
874
875        let mut lazy = ArrowBytesViewMap::<()>::new(OutputType::Utf8View);
876        lazy.take();
877        assert_eq!(lazy.map.capacity(), 0);
878    }
879
880    #[test]
881    fn clear_and_release_frees_the_preallocation_that_take_keeps() {
882        let mut map = ArrowBytesViewMap::<()>::with_capacity(
883            OutputType::Utf8View,
884            INITIAL_MAP_CAPACITY,
885        );
886        let values: ArrayRef = Arc::new(StringViewArray::from_iter_values(
887            (0..1_000).map(|i| format!("distinct value number {i}")),
888        ));
889        map.insert_if_new(&values, |_| (), |_| ());
890
891        let warm_size = map.map.allocation_size();
892        assert!(warm_size > 0);
893
894        // `take` deliberately keeps the map warm, so it does not release the
895        // configured capacity.
896        map.take();
897        let taken_size = map.size();
898        assert!(
899            taken_size >= min_table_bytes::<Entry<()>>(INITIAL_MAP_CAPACITY),
900            "expected take to retain the warm up allocation, got {taken_size}"
901        );
902
903        map.clear_and_release();
904        assert_eq!(map.map.allocation_size(), 0);
905        let released_size = map.size();
906        assert!(
907            released_size < 128,
908            "expected the released map to report approximately zero bytes, got {released_size}"
909        );
910
911        // The configured capacity survives, so the map warms back up when it is
912        // emitted from again.
913        map.take();
914        assert!(map.map.capacity() >= INITIAL_MAP_CAPACITY);
915    }
916
917    #[test]
918    fn test_size_counts_retained_buffer_capacities() {
919        let first = "a".repeat(BYTE_VIEW_MAX_BLOCK_SIZE / 2 + 1);
920        let second = "b".repeat(BYTE_VIEW_MAX_BLOCK_SIZE / 2 + 1);
921        let third = "c".repeat(BYTE_VIEW_MAX_BLOCK_SIZE / 2 + 1);
922        let values: ArrayRef = Arc::new(StringViewArray::from(vec![
923            first.as_str(),
924            second.as_str(),
925            third.as_str(),
926        ]));
927
928        let mut map = ArrowBytesViewMap::new(OutputType::Utf8View);
929        map.insert_if_new(&values, |_| (), |_| {});
930
931        // Make unused vector capacity explicit; the completed buffers were created
932        // by the map's flush path.
933        map.views.shrink_to_fit();
934        map.views.reserve_exact(1);
935        map.completed.shrink_to_fit();
936        map.completed.reserve_exact(1);
937
938        // The map owns these allocations; `values` and its Arrow buffers remain external.
939        assert!(map.views.capacity() > map.views.len());
940        assert!(map.completed.capacity() > map.completed.len());
941        assert!(
942            map.completed
943                .iter()
944                .any(|buffer| buffer.capacity() > buffer.len())
945        );
946
947        let expected_size = map.map.allocation_size()
948            + map.views.allocated_size()
949            + map.in_progress.allocated_size()
950            + map.completed.allocated_size()
951            + map.completed.iter().map(Buffer::capacity).sum::<usize>()
952            + map.hashes_buffer.allocated_size();
953        assert_eq!(map.size(), expected_size);
954
955        // Verify the retained-capacity delta independently from the production formula.
956        let legacy_size = map.map.allocation_size()
957            + map.views.len() * size_of::<u128>()
958            + map.in_progress.capacity()
959            + map.completed.iter().map(Buffer::len).sum::<usize>()
960            + map.hashes_buffer.allocated_size();
961        let retained_capacity_delta = (map.views.capacity() - map.views.len())
962            * size_of::<u128>()
963            + map.completed.capacity() * size_of::<Buffer>()
964            + map
965                .completed
966                .iter()
967                .map(|buffer| buffer.capacity() - buffer.len())
968                .sum::<usize>();
969        assert_eq!(map.size() - legacy_size, retained_capacity_delta);
970
971        let size_after_insert = map.size();
972        map.insert_if_new(&values, |_| (), |_| {});
973        assert_eq!(map.size(), size_after_insert);
974    }
975
976    #[derive(Debug, PartialEq, Eq, Default, Clone, Copy)]
977    struct TestPayload {
978        // store the string value to check against input
979        index: usize, // store the index of the string (each new string gets the next sequential input)
980    }
981
982    /// Wraps an [`ArrowBytesViewMap`], validating its invariants
983    struct TestMap {
984        map: ArrowBytesViewMap<TestPayload>,
985        // stores distinct strings seen, in order
986        strings: Vec<Option<String>>,
987        // map strings to index in strings
988        indexes: HashMap<Option<String>, usize>,
989    }
990
991    impl TestMap {
992        /// creates a map with TestPayloads for the given strings and then
993        /// validates the payloads
994        fn new() -> Self {
995            Self {
996                map: ArrowBytesViewMap::new(OutputType::Utf8View),
997                strings: vec![],
998                indexes: HashMap::new(),
999            }
1000        }
1001
1002        /// Inserts strings into the map
1003        fn insert(&mut self, strings: &[Option<&str>]) {
1004            let string_array = StringViewArray::from(strings.to_vec());
1005            let arr: ArrayRef = Arc::new(string_array);
1006
1007            let mut next_index = self.indexes.len();
1008            let mut actual_new_strings = vec![];
1009            let mut actual_seen_indexes = vec![];
1010            // update self with new values, keeping track of newly added values
1011            for str in strings {
1012                let str = str.map(|s| s.to_string());
1013                let index = self.indexes.get(&str).copied().unwrap_or_else(|| {
1014                    actual_new_strings.push(str.clone());
1015                    let index = self.strings.len();
1016                    self.strings.push(str.clone());
1017                    self.indexes.insert(str, index);
1018                    index
1019                });
1020                actual_seen_indexes.push(index);
1021            }
1022
1023            // insert the values into the map, recording what we did
1024            let mut seen_new_strings = vec![];
1025            let mut seen_indexes = vec![];
1026            self.map.insert_if_new(
1027                &arr,
1028                |s| {
1029                    let value = s
1030                        .map(|s| String::from_utf8(s.to_vec()).expect("Non utf8 string"));
1031                    let index = next_index;
1032                    next_index += 1;
1033                    seen_new_strings.push(value);
1034                    TestPayload { index }
1035                },
1036                |payload| {
1037                    seen_indexes.push(payload.index);
1038                },
1039            );
1040
1041            assert_eq!(actual_seen_indexes, seen_indexes);
1042            assert_eq!(actual_new_strings, seen_new_strings);
1043        }
1044
1045        /// Call `self.map.into_array()` validating that the strings are in the same
1046        /// order as they were inserted
1047        fn into_array(self) -> ArrayRef {
1048            let Self {
1049                map,
1050                strings,
1051                indexes: _,
1052            } = self;
1053
1054            let arr = map.into_state();
1055            let expected: ArrayRef = Arc::new(StringViewArray::from(strings));
1056            assert_eq!(&arr, &expected);
1057            arr
1058        }
1059    }
1060
1061    #[test]
1062    fn test_map() {
1063        let input = vec![
1064            // Note mix of short/long strings
1065            Some("A"),
1066            Some("bcdefghijklmnop1234567"),
1067            Some("X"),
1068            Some("Y"),
1069            None,
1070            Some("qrstuvqxyzhjwya"),
1071            Some("✨🔥"),
1072            Some("🔥"),
1073            Some("🔥🔥🔥🔥🔥🔥"),
1074        ];
1075
1076        let mut test_map = TestMap::new();
1077        test_map.insert(&input);
1078        test_map.insert(&input); // put it in twice
1079        let expected_output: ArrayRef = Arc::new(StringViewArray::from(input));
1080        assert_eq!(&test_map.into_array(), &expected_output);
1081    }
1082}