Skip to main content

datafusion_physical_expr_common/
binary_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//! [`ArrowBytesMap`] and [`ArrowBytesSet`] for storing maps/sets of values from
6//! StringArray / LargeStringArray / BinaryArray / LargeBinaryArray.
7
8use arrow::array::{
9    Array, ArrayRef, BufferBuilder, GenericBinaryArray, GenericStringArray,
10    NullBufferBuilder, OffsetSizeTrait,
11    cast::AsArray,
12    types::{ByteArrayType, GenericBinaryType, GenericStringType},
13};
14use arrow::buffer::{Buffer, NullBuffer, OffsetBuffer, ScalarBuffer};
15use arrow::datatypes::DataType;
16use datafusion_common::hash_utils::RandomState;
17use datafusion_common::hash_utils::create_hashes;
18use datafusion_common::utils::proxy::VecAllocExt;
19use datafusion_common::{Result, exec_err};
20use std::any::type_name;
21use std::fmt::Debug;
22use std::mem::{size_of, swap};
23use std::ops::Range;
24use std::sync::Arc;
25
26/// Should the output be a String or Binary?
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum OutputType {
29    /// `StringArray` or `LargeStringArray`
30    Utf8,
31    /// `StringViewArray`
32    Utf8View,
33    /// `BinaryArray` or `LargeBinaryArray`
34    Binary,
35    /// `BinaryViewArray`
36    BinaryView,
37}
38
39/// HashSet optimized for storing string or binary values that can produce that
40/// the final set as a GenericStringArray with minimal copies.
41#[derive(Debug)]
42pub struct ArrowBytesSet<O: OffsetSizeTrait>(ArrowBytesMap<O, ()>);
43
44impl<O: OffsetSizeTrait> ArrowBytesSet<O> {
45    /// Creates a set that does not pre-allocate its hash table or value buffer.
46    ///
47    /// See [`ArrowBytesMap::new`] for when to prefer this over
48    /// [`Self::with_capacity`].
49    pub fn new(output_type: OutputType) -> Self {
50        Self(ArrowBytesMap::new(output_type))
51    }
52
53    /// Creates a set with room for `map_capacity` entries.
54    ///
55    /// See [`ArrowBytesMap::with_capacity`].
56    pub fn with_capacity(output_type: OutputType, map_capacity: usize) -> Self {
57        Self(ArrowBytesMap::with_capacity(output_type, map_capacity))
58    }
59
60    /// Return the contents of this set and replace it with a new empty
61    /// set with the same output type
62    pub fn take(&mut self) -> Self {
63        Self(self.0.take())
64    }
65
66    /// Inserts each value from `values` into the set
67    pub fn insert(&mut self, values: &ArrayRef) {
68        fn make_payload_fn(_value: Option<&[u8]>) {}
69        fn observe_payload_fn(_payload: ()) {}
70        self.0
71            .insert_if_new(values, make_payload_fn, observe_payload_fn);
72    }
73
74    /// Converts this set into a `StringArray`/`LargeStringArray` or
75    /// `BinaryArray`/`LargeBinaryArray` containing each distinct value that
76    /// was interned. This is done without copying the values.
77    pub fn into_state(self) -> ArrayRef {
78        self.0.into_state()
79    }
80
81    /// Returns the total number of distinct values (including nulls) seen so far
82    pub fn len(&self) -> usize {
83        self.0.len()
84    }
85
86    pub fn is_empty(&self) -> bool {
87        self.0.is_empty()
88    }
89
90    /// returns the total number of distinct values (not including nulls) seen so far
91    pub fn non_null_len(&self) -> usize {
92        self.0.non_null_len()
93    }
94
95    /// Return the total size, in bytes, of memory used to store the data in
96    /// this set, not including `self`
97    pub fn size(&self) -> usize {
98        self.0.size()
99    }
100}
101
102/// Optimized map for storing Arrow "bytes" types (`String`, `LargeString`,
103/// `Binary`, and `LargeBinary`) values that can produce the set of keys on
104/// output as `GenericBinaryArray` without copies.
105///
106/// Equivalent to `HashSet<String, V>` but with better performance if you need
107/// to emit the keys as an Arrow `StringArray` / `BinaryArray`. For other
108/// purposes it is the same as a `HashMap<String, V>`
109///
110/// # Generic Arguments
111///
112/// * `O`: OffsetSize (String/LargeString)
113/// * `V`: payload type
114///
115/// # Description
116///
117/// This is a specialized HashMap with the following properties:
118///
119/// 1. Optimized for storing and emitting Arrow byte types  (e.g.
120///    `StringArray` / `BinaryArray`) very efficiently by minimizing copying of
121///    the string values themselves, both when inserting and when emitting the
122///    final array.
123///
124///
125/// 2. Retains the insertion order of entries in the final array. The values are
126///    in the same order as they were inserted.
127///
128/// Note this structure can be used as a `HashSet` by specifying the value type
129/// as `()`, as is done by [`ArrowBytesSet`].
130///
131/// This map is used by the special `COUNT DISTINCT` aggregate function to
132/// store the distinct values, and by the `GROUP BY` operator to store
133/// group values when they are a single string array.
134///
135/// # Example
136///
137/// The following diagram shows how the map would store the four strings
138/// "Foo", NULL, "Bar", "TheQuickBrownFox":
139///
140/// * `hashtable` stores entries for each distinct string that has been
141///   inserted. The entries contain the payload as well as information about the
142///   value (either an offset or the actual bytes, see `Entry` docs for more
143///   details)
144///
145/// * `offsets` stores offsets into `buffer` for each distinct string value,
146///   following the same convention as the offsets in a `StringArray` or
147///   `LargeStringArray`.
148///
149/// * `buffer` stores the actual byte data
150///
151/// * `null`: stores the index and payload of the null value, in this case the
152///   second value (index 1)
153///
154/// ```text
155/// ┌───────────────────────────────────┐    ┌─────┐    ┌────┐
156/// │                ...                │    │  0  │    │FooB│
157/// │ ┌──────────────────────────────┐  │    │  0  │    │arTh│
158/// │ │      <Entry for "Bar">       │  │    │  3  │    │eQui│
159/// │ │            len: 3            │  │    │  3  │    │ckBr│
160/// │ │   offset_or_inline: "Bar"    │  │    │  6  │    │ownF│
161/// │ │         payload:...          │  │    │     │    │ox  │
162/// │ └──────────────────────────────┘  │    │     │    │    │
163/// │                ...                │    └─────┘    └────┘
164/// │ ┌──────────────────────────────┐  │
165/// │ │<Entry for "TheQuickBrownFox">│  │    offsets    buffer
166/// │ │           len: 16            │  │
167/// │ │     offset_or_inline: 6      │  │    ┌───────────────┐
168/// │ │         payload: ...         │  │    │    Some(1)    │
169/// │ └──────────────────────────────┘  │    │ payload: ...  │
170/// │                ...                │    └───────────────┘
171/// └───────────────────────────────────┘
172///                                              null
173///               HashTable
174/// ```
175///
176/// # Entry Format
177///
178/// Entries stored in a [`ArrowBytesMap`] represents a value that is either
179/// stored inline or in the buffer
180///
181/// This helps the case where there are many short (less than 8 bytes) strings
182/// that are the same (e.g. "MA", "CA", "NY", "TX", etc)
183///
184/// ```text
185///                                                                ┌──────────────────┐
186///                                                  ─ ─ ─ ─ ─ ─ ─▶│...               │
187///                                                 │              │TheQuickBrownFox  │
188///                                                                │...               │
189///                                                 │              │                  │
190///                                                                └──────────────────┘
191///                                                 │               buffer of u8
192///
193///                                                 │
194///                        ┌────────────────┬───────────────┬───────────────┐
195///  Storing               │                │ starting byte │  length, in   │
196///  "TheQuickBrownFox"    │   hash value   │   offset in   │  bytes (not   │
197///  (long string)         │                │    buffer     │  characters)  │
198///                        └────────────────┴───────────────┴───────────────┘
199///                              8 bytes          8 bytes       4 or 8
200///
201///
202///                         ┌───────────────┬─┬─┬─┬─┬─┬─┬─┬─┬───────────────┐
203/// Storing "foobar"        │               │ │ │ │ │ │ │ │ │  length, in   │
204/// (short string)          │  hash value   │?│?│f│o│o│b│a│r│  bytes (not   │
205///                         │               │ │ │ │ │ │ │ │ │  characters)  │
206///                         └───────────────┴─┴─┴─┴─┴─┴─┴─┴─┴───────────────┘
207///                              8 bytes         8 bytes        4 or 8
208/// ```
209pub struct ArrowBytesMap<O, V>
210where
211    O: OffsetSizeTrait,
212    V: Debug + PartialEq + Eq + Clone + Copy + Default,
213{
214    /// Should the output be String or Binary?
215    output_type: OutputType,
216    /// Underlying hash set for each distinct value
217    map: hashbrown::hash_table::HashTable<Entry<O, V>>,
218    /// Hash table capacity to re-create the map with in [`Self::take`], so a
219    /// map built with [`Self::with_capacity`] keeps its pre-allocation when it
220    /// is emptied and reused
221    initial_map_capacity: usize,
222    /// Value buffer capacity to re-create the buffer with in [`Self::take`],
223    /// for the same reason as `initial_map_capacity`
224    initial_buffer_capacity: usize,
225    /// In progress buffer containing all values
226    buffer: Vec<u8>,
227    /// Offsets into `buffer` for each distinct  value. These offsets as used
228    /// directly to create the final `GenericBinaryArray`. The `i`th string is
229    /// stored in the range `offsets[i]..offsets[i+1]` in `buffer`. Null values
230    /// are stored as a zero length string.
231    offsets: Vec<O>,
232    /// random state used to generate hashes
233    random_state: RandomState,
234    /// buffer that stores hash values (reused across batches to save allocations)
235    hashes_buffer: Vec<u64>,
236    /// `(payload, null_index)` for the 'null' value, if any
237    /// NOTE null_index is the logical index in the final array, not the index
238    /// in the buffer
239    null: Option<(V, usize)>,
240}
241
242/// The size, in number of entries, of the hash table pre-allocated by
243/// [`ArrowBytesMap::with_capacity`]. It is a warm up size for maps that go on
244/// to hold many values, not a bound on what the map can hold.
245pub const INITIAL_MAP_CAPACITY: usize = 128;
246/// The size, in bytes, of the string data buffer pre-allocated by
247/// [`ArrowBytesMap::with_capacity`]
248pub const INITIAL_BUFFER_CAPACITY: usize = 8 * 1024;
249
250/// Appends `value` to a map's value buffer, growing the buffer on a power of
251/// two ladder.
252///
253/// `Vec` doubles from wherever its first allocation landed, so a buffer started
254/// empty by [`ArrowBytesMap::new`] and one started at
255/// [`INITIAL_BUFFER_CAPACITY`] by [`ArrowBytesMap::with_capacity`] sit on
256/// different ladders, and can hold the same values at capacities differing by
257/// up to 2x in either direction depending on the value lengths. Rounding every
258/// growth up to a power of two puts both on one ladder, which is what makes a
259/// lazily allocated map never larger than a pre-allocated one holding the same
260/// values. Growth stays geometric, so appending is still amortized constant
261/// time.
262fn push_value_bytes(buffer: &mut Vec<u8>, value: &[u8]) {
263    let required = buffer.len() + value.len();
264    if required > buffer.capacity() {
265        let target = required.checked_next_power_of_two().unwrap_or(required);
266        buffer.reserve_exact(target - buffer.len());
267    }
268    buffer.extend_from_slice(value);
269}
270
271impl<O: OffsetSizeTrait, V> ArrowBytesMap<O, V>
272where
273    V: Debug + PartialEq + Eq + Clone + Copy + Default,
274{
275    /// Creates a map that does not pre-allocate its hash table or value buffer.
276    ///
277    /// Use this when maps are created in large numbers and most of them stay
278    /// small, such as the per group `COUNT(DISTINCT)` accumulators that
279    /// `GroupsAccumulatorAdapter` creates one of per group. There the
280    /// pre-allocation dwarfs the values the map actually holds.
281    pub fn new(output_type: OutputType) -> Self {
282        Self::new_inner(output_type, 0, 0)
283    }
284
285    /// Creates a map whose hash table is pre-allocated for `map_capacity`
286    /// entries and whose value buffer is pre-allocated with
287    /// [`INITIAL_BUFFER_CAPACITY`] bytes.
288    ///
289    /// Use this for the few long lived maps that are each expected to hold many
290    /// values, such as the single map backing a `GROUP BY` on one string
291    /// column. The capacities are preserved across [`Self::take`].
292    pub fn with_capacity(output_type: OutputType, map_capacity: usize) -> Self {
293        Self::new_inner(output_type, map_capacity, INITIAL_BUFFER_CAPACITY)
294    }
295
296    fn new_inner(
297        output_type: OutputType,
298        map_capacity: usize,
299        buffer_capacity: usize,
300    ) -> Self {
301        Self {
302            output_type,
303            map: hashbrown::hash_table::HashTable::with_capacity(map_capacity),
304            initial_map_capacity: map_capacity,
305            initial_buffer_capacity: buffer_capacity,
306            buffer: Vec::with_capacity(buffer_capacity),
307            offsets: vec![O::default()], // first offset is always 0
308            random_state: RandomState::default(),
309            hashes_buffer: vec![],
310            null: None,
311        }
312    }
313
314    /// Return the contents of this map and replace it with a new empty map with
315    /// the same output type
316    pub fn take(&mut self) -> Self {
317        let mut new_self = Self::new_inner(
318            self.output_type,
319            self.initial_map_capacity,
320            self.initial_buffer_capacity,
321        );
322        swap(self, &mut new_self);
323        new_self
324    }
325
326    /// Empties this map and releases every allocation it holds, so
327    /// [`Self::size`] drops to approximately zero.
328    ///
329    /// This is the difference from [`Self::take`]: `take` restores the
330    /// capacities the map was configured with so the emptied map stays warm for
331    /// continued use, which is what emitting wants, whereas here the point is
332    /// to hand the memory back, as before spilling or before a downstream sort.
333    /// The configured capacities are remembered, so the next [`Self::take`]
334    /// warms the map up again.
335    pub fn clear_and_release(&mut self) {
336        let mut released = Self::new_inner(self.output_type, 0, 0);
337        released.initial_map_capacity = self.initial_map_capacity;
338        released.initial_buffer_capacity = self.initial_buffer_capacity;
339        *self = released;
340    }
341
342    /// Inserts each value from `values` into the map, invoking `payload_fn` for
343    /// each value if *not* already present, deferring the allocation of the
344    /// payload until it is needed.
345    ///
346    /// Note that this is different than a normal map that would replace the
347    /// existing entry
348    ///
349    /// # Arguments:
350    ///
351    /// `values`: array whose values are inserted
352    ///
353    /// `make_payload_fn`:  invoked for each value that is not already present
354    /// to create the payload, in order of the values in `values`
355    ///
356    /// `observe_payload_fn`: invoked once, for each value in `values`, that was
357    /// already present in the map, with corresponding payload value.
358    ///
359    /// # Returns
360    ///
361    /// The payload value for the entry, either the existing value or
362    /// the newly inserted value
363    ///
364    /// # Safety:
365    ///
366    /// Note that `make_payload_fn` and `observe_payload_fn` are only invoked
367    /// with valid values from `values`, not for the `NULL` value.
368    pub fn insert_if_new<MP, OP>(
369        &mut self,
370        values: &ArrayRef,
371        make_payload_fn: MP,
372        observe_payload_fn: OP,
373    ) where
374        MP: FnMut(Option<&[u8]>) -> V,
375        OP: FnMut(V),
376    {
377        // Sanity array type
378        match self.output_type {
379            OutputType::Binary => {
380                assert!(matches!(
381                    values.data_type(),
382                    DataType::Binary | DataType::LargeBinary
383                ));
384                self.insert_if_new_inner::<MP, OP, GenericBinaryType<O>>(
385                    values,
386                    make_payload_fn,
387                    observe_payload_fn,
388                )
389            }
390            OutputType::Utf8 => {
391                assert!(matches!(
392                    values.data_type(),
393                    DataType::Utf8 | DataType::LargeUtf8
394                ));
395                self.insert_if_new_inner::<MP, OP, GenericStringType<O>>(
396                    values,
397                    make_payload_fn,
398                    observe_payload_fn,
399                )
400            }
401            _ => unreachable!("View types should use `ArrowBytesViewMap`"),
402        }
403    }
404
405    /// Generic version of [`Self::insert_if_new`] that handles `ByteArrayType`
406    /// (both String and Binary)
407    ///
408    /// Note this is the only function that is generic on [`ByteArrayType`], which
409    /// avoids having to template the entire structure,  making the code
410    /// simpler and understand and reducing code bloat due to duplication.
411    ///
412    /// See comments on `insert_if_new` for more details
413    fn insert_if_new_inner<MP, OP, B>(
414        &mut self,
415        values: &ArrayRef,
416        mut make_payload_fn: MP,
417        mut observe_payload_fn: OP,
418    ) where
419        MP: FnMut(Option<&[u8]>) -> V,
420        OP: FnMut(V),
421        B: ByteArrayType,
422    {
423        // step 1: compute hashes
424        let batch_hashes = &mut self.hashes_buffer;
425        batch_hashes.clear();
426        batch_hashes.resize(values.len(), 0);
427        create_hashes([values], &self.random_state, batch_hashes)
428            // hash is supported for all types and create_hashes only
429            // returns errors for unsupported types
430            .unwrap();
431
432        // step 2: insert each value into the set, if not already present
433        let values = values.as_bytes::<B>();
434
435        // Ensure lengths are equivalent
436        assert_eq!(values.len(), batch_hashes.len());
437
438        for (value, &hash) in values.iter().zip(batch_hashes.iter()) {
439            // handle null value
440            let Some(value) = value else {
441                let payload = if let Some(&(payload, _offset)) = self.null.as_ref() {
442                    payload
443                } else {
444                    let payload = make_payload_fn(None);
445                    let null_index = self.offsets.len() - 1;
446                    // nulls need a zero length in the offset buffer
447                    let offset = self.buffer.len();
448                    self.offsets.push(O::usize_as(offset));
449                    self.null = Some((payload, null_index));
450                    payload
451                };
452                observe_payload_fn(payload);
453                continue;
454            };
455
456            // get the value as bytes
457            let value: &[u8] = value.as_ref();
458            let value_len = O::usize_as(value.len());
459
460            // value is "small"
461            let payload = if value.len() <= SHORT_VALUE_LEN {
462                let inline = value.iter().fold(0usize, |acc, &x| (acc << 8) | x as usize);
463
464                // is value is already present in the set?
465                let entry = self.map.find_mut(hash, |header| {
466                    // compare value if hashes match
467                    if header.hash != hash || header.len != value_len {
468                        return false;
469                    }
470                    // value is stored inline so no need to consult buffer
471                    // (this is the "small string optimization")
472                    inline == header.offset_or_inline
473                });
474
475                if let Some(entry) = entry {
476                    entry.payload
477                }
478                // if no existing entry, make a new one
479                else {
480                    // Put the small values into buffer and offsets so it appears
481                    // the output array, but store the actual bytes inline for
482                    // comparison
483                    push_value_bytes(&mut self.buffer, value);
484                    self.offsets.push(O::usize_as(self.buffer.len()));
485                    let payload = make_payload_fn(Some(value));
486                    let new_header = Entry {
487                        hash,
488                        len: value_len,
489                        offset_or_inline: inline,
490                        payload,
491                    };
492                    self.map
493                        .insert_unique(hash, new_header, |header| header.hash);
494                    payload
495                }
496            }
497            // value is not "small"
498            else {
499                // Check if the value is already present in the set
500                let entry = self.map.find_mut(hash, |header| {
501                    // Without the length test, a short entry colliding on
502                    // `hash` builds `range()` from its inlined bytes and
503                    // reads past the buffer: memory safety, not just a
504                    // wasted comparison.
505                    if header.hash != hash || header.len != value_len {
506                        return false;
507                    }
508                    // SAFETY: a long entry, so `offset_or_inline` indexes the
509                    // append-only `buffer`, written before the insert.
510                    let existing_value =
511                        unsafe { self.buffer.get_unchecked(header.range()) };
512                    value == existing_value
513                });
514
515                if let Some(entry) = entry {
516                    entry.payload
517                }
518                // if no existing entry, make a new one
519                else {
520                    // Put the small values into buffer and offsets so it
521                    // appears the output array, and store that offset
522                    // so the bytes can be compared if needed
523                    let offset = self.buffer.len(); // offset of start for data
524                    push_value_bytes(&mut self.buffer, value);
525                    self.offsets.push(O::usize_as(self.buffer.len()));
526
527                    let payload = make_payload_fn(Some(value));
528                    let new_header = Entry {
529                        hash,
530                        len: value_len,
531                        offset_or_inline: offset,
532                        payload,
533                    };
534                    self.map
535                        .insert_unique(hash, new_header, |header| header.hash);
536                    payload
537                }
538            };
539            observe_payload_fn(payload);
540        }
541        // Check for overflow in offsets (if more data was sent than can be represented)
542        assert!(
543            O::from_usize(self.buffer.len()).is_some(),
544            "Put {} bytes in buffer, more than can be represented by a {}",
545            self.buffer.len(),
546            type_name::<O>()
547        )
548    }
549
550    /// Converts this set into a `StringArray`, `LargeStringArray`,
551    /// `BinaryArray`, or `LargeBinaryArray` containing each distinct value
552    /// that was inserted. This is done without copying the values.
553    ///
554    /// The values are guaranteed to be returned in the same order in which
555    /// they were first seen.
556    pub fn into_state(self) -> ArrayRef {
557        let Self {
558            output_type,
559            map: _,
560            initial_map_capacity: _,
561            initial_buffer_capacity: _,
562            offsets,
563            buffer,
564            random_state: _,
565            hashes_buffer: _,
566            null,
567        } = self;
568
569        // Only make a `NullBuffer` if there was a null value
570        let nulls = null.map(|(_payload, null_index)| {
571            let num_values = offsets.len() - 1;
572            single_null_buffer(num_values, null_index)
573        });
574        // SAFETY: the offsets were constructed correctly in `insert_if_new` --
575        // monotonically increasing, overflows were checked.
576        let offsets = unsafe { OffsetBuffer::new_unchecked(ScalarBuffer::from(offsets)) };
577        let values = Buffer::from_vec(buffer);
578
579        match output_type {
580            OutputType::Binary => {
581                // SAFETY: the offsets were constructed correctly
582                Arc::new(unsafe {
583                    GenericBinaryArray::new_unchecked(offsets, values, nulls)
584                })
585            }
586            OutputType::Utf8 => {
587                // SAFETY:
588                // 1. the offsets were constructed safely
589                //
590                // 2. we asserted the input arrays were all the correct type and
591                // thus since all the values that went in were valid (e.g. utf8)
592                // so are all the values that come out
593                Arc::new(unsafe {
594                    GenericStringArray::new_unchecked(offsets, values, nulls)
595                })
596            }
597            _ => unreachable!("View types should use `ArrowBytesViewMap`"),
598        }
599    }
600
601    /// Copies keys at `indices` into an array without changing this map.
602    ///
603    /// Keys are returned in index order, and duplicate indices are supported.
604    pub fn keys<I>(&self, indices: I) -> Result<ArrayRef>
605    where
606        I: IntoIterator<Item = usize>,
607    {
608        let indices = indices.into_iter();
609        let mut output_offsets = Vec::with_capacity(indices.size_hint().0 + 1);
610        let mut output_values = BufferBuilder::<u8>::new(0);
611        let mut output_nulls = NullBufferBuilder::new(indices.size_hint().0);
612        output_offsets.push(O::default());
613        let null_index = self.null.map(|(_, index)| index);
614        let num_keys = self.offsets.len() - 1;
615
616        for index in indices {
617            if index >= num_keys {
618                return exec_err!(
619                    "Key index {index} is out of bounds for {num_keys} keys"
620                );
621            }
622            let start = self.offsets[index].as_usize();
623            let end = self.offsets[index + 1].as_usize();
624            output_values.append_slice(&self.buffer.as_slice()[start..end]);
625            if O::from_usize(output_values.len()).is_none() {
626                return exec_err!("Offset overflow while copying byte map keys");
627            }
628            output_offsets.push(O::usize_as(output_values.len()));
629            output_nulls.append(index != null_index.unwrap_or(usize::MAX));
630        }
631
632        // SAFETY: offsets are constructed from the length of `output_values`.
633        let offsets =
634            unsafe { OffsetBuffer::new_unchecked(ScalarBuffer::from(output_offsets)) };
635        let values = output_values.finish();
636        let nulls = output_nulls.finish();
637        Ok(match self.output_type {
638            OutputType::Binary => Arc::new(unsafe {
639                GenericBinaryArray::new_unchecked(offsets, values, nulls)
640            }),
641            OutputType::Utf8 => Arc::new(unsafe {
642                GenericStringArray::new_unchecked(offsets, values, nulls)
643            }),
644            _ => unreachable!("View types should use `ArrowBytesViewMap`"),
645        })
646    }
647
648    /// Total number of entries (including null, if present)
649    pub fn len(&self) -> usize {
650        self.non_null_len() + self.null.map(|_| 1).unwrap_or(0)
651    }
652
653    /// Is the set empty?
654    pub fn is_empty(&self) -> bool {
655        self.map.is_empty() && self.null.is_none()
656    }
657
658    /// Number of non null entries
659    pub fn non_null_len(&self) -> usize {
660        self.map.len()
661    }
662
663    /// Return the total size, in bytes, of memory used to store the data in
664    /// this set, not including `self`
665    pub fn size(&self) -> usize {
666        // `HashTable::allocation_size` reports the whole hashbrown allocation,
667        // which is the entry array plus the control bytes plus the trailing
668        // group, so it is larger than `capacity() * size_of::<Entry<O, V>>()`.
669        // It is a constant time layout calculation, not a walk of the table.
670        self.map.allocation_size()
671            + self.buffer.capacity() * size_of::<u8>()
672            + self.offsets.allocated_size()
673            + self.hashes_buffer.allocated_size()
674    }
675}
676
677/// Returns a `NullBuffer` with a single null value at the given index
678pub(crate) fn single_null_buffer(num_values: usize, null_index: usize) -> NullBuffer {
679    let mut null_builder = NullBufferBuilder::new(num_values);
680    null_builder.append_n_non_nulls(null_index);
681    null_builder.append_null();
682    null_builder.append_n_non_nulls(num_values - null_index - 1);
683    // SAFETY: inner builder must be constructed
684    null_builder.finish().unwrap()
685}
686
687impl<O: OffsetSizeTrait, V> Debug for ArrowBytesMap<O, V>
688where
689    V: Debug + PartialEq + Eq + Clone + Copy + Default,
690{
691    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
692        f.debug_struct("ArrowBytesMap")
693            .field("map", &"<map>")
694            .field("map_allocation_size", &self.map.allocation_size())
695            .field("buffer", &self.buffer)
696            .field("random_state", &self.random_state)
697            .field("hashes_buffer", &self.hashes_buffer)
698            .finish()
699    }
700}
701
702/// Maximum size of a value that can be inlined in the hash table
703const SHORT_VALUE_LEN: usize = size_of::<usize>();
704
705/// Entry in the hash table -- see [`ArrowBytesMap`] for more details
706#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
707struct Entry<O, V>
708where
709    O: OffsetSizeTrait,
710    V: Debug + PartialEq + Eq + Clone + Copy + Default,
711{
712    /// hash of the value (stored to avoid recomputing it in hash table check)
713    hash: u64,
714    /// if len =< [`SHORT_VALUE_LEN`]: the data inlined
715    /// if len > [`SHORT_VALUE_LEN`], the offset of where the data starts
716    offset_or_inline: usize,
717    /// length of the value, in bytes (use O here so we use only i32 for
718    /// strings, rather 64 bit usize)
719    len: O,
720    /// value stored by the entry
721    payload: V,
722}
723
724impl<O, V> Entry<O, V>
725where
726    O: OffsetSizeTrait,
727    V: Debug + PartialEq + Eq + Clone + Copy + Default,
728{
729    /// returns self.offset..self.offset + self.len
730    #[inline(always)]
731    fn range(&self) -> Range<usize> {
732        self.offset_or_inline..self.offset_or_inline + self.len.as_usize()
733    }
734}
735
736#[cfg(test)]
737mod tests {
738    use super::*;
739    use arrow::array::{BinaryArray, LargeBinaryArray, StringArray};
740    use std::collections::HashMap;
741
742    /// A lower bound on the bytes a hashbrown table holding `entries` entries
743    /// of type `T` must allocate: one entry slot and one control byte each.
744    /// Derived independently of the production accounting so it can bracket it.
745    fn min_table_bytes<T>(entries: usize) -> usize {
746        entries * (size_of::<T>() + 1)
747    }
748
749    #[test]
750    fn map_new_does_not_allocate() {
751        let map = ArrowBytesMap::<i32, ()>::new(OutputType::Utf8);
752
753        assert_eq!(map.map.capacity(), 0);
754        assert_eq!(map.map.allocation_size(), 0);
755        assert_eq!(map.buffer.capacity(), 0);
756        // Only the single leading zero offset is allocated.
757        assert!(map.size() < 128, "expected {} to be tiny", map.size());
758    }
759
760    #[test]
761    fn map_with_capacity_reports_the_real_hash_table_allocation() {
762        let map = ArrowBytesMap::<i32, ()>::with_capacity(
763            OutputType::Utf8,
764            INITIAL_MAP_CAPACITY,
765        );
766
767        assert!(map.map.capacity() >= INITIAL_MAP_CAPACITY);
768        assert_eq!(map.buffer.capacity(), INITIAL_BUFFER_CAPACITY);
769
770        // Before this accounting was corrected the map reported its hash table
771        // as costing zero bytes until the table grew past its pre-allocation.
772        let table_bytes = map.map.allocation_size();
773        let lower_bound = min_table_bytes::<Entry<i32, ()>>(map.map.capacity());
774        assert!(
775            table_bytes >= lower_bound,
776            "expected {table_bytes} to be at least {lower_bound}"
777        );
778        assert!(
779            table_bytes <= 2 * lower_bound + 64,
780            "expected {table_bytes} to be within a small factor of {lower_bound}"
781        );
782        assert!(map.size() >= table_bytes + INITIAL_BUFFER_CAPACITY);
783    }
784
785    #[test]
786    fn take_preserves_the_capacity_the_map_was_built_with() {
787        let mut preallocated = ArrowBytesMap::<i32, ()>::with_capacity(
788            OutputType::Utf8,
789            INITIAL_MAP_CAPACITY,
790        );
791        let capacity = preallocated.map.capacity();
792        preallocated.take();
793        assert_eq!(preallocated.map.capacity(), capacity);
794        assert_eq!(preallocated.buffer.capacity(), INITIAL_BUFFER_CAPACITY);
795
796        let mut lazy = ArrowBytesMap::<i32, ()>::new(OutputType::Utf8);
797        lazy.take();
798        assert_eq!(lazy.map.capacity(), 0);
799        assert_eq!(lazy.buffer.capacity(), 0);
800    }
801
802    #[test]
803    fn clear_and_release_frees_the_preallocation_that_take_keeps() {
804        let mut map = ArrowBytesMap::<i32, ()>::with_capacity(
805            OutputType::Utf8,
806            INITIAL_MAP_CAPACITY,
807        );
808        let values: ArrayRef = Arc::new(StringArray::from_iter_values(
809            (0..1_000).map(|i| format!("distinct value number {i}")),
810        ));
811        map.insert_if_new(&values, |_| (), |_| ());
812
813        let populated_size = map.size();
814        assert!(populated_size > INITIAL_BUFFER_CAPACITY);
815
816        // `take` deliberately keeps the map warm, so it does not release the
817        // configured capacities.
818        map.take();
819        let taken_size = map.size();
820        assert!(
821            taken_size > INITIAL_BUFFER_CAPACITY,
822            "expected take to retain the warm up allocations, got {taken_size}"
823        );
824
825        map.clear_and_release();
826        let released_size = map.size();
827        assert_eq!(map.map.allocation_size(), 0);
828        assert_eq!(map.buffer.capacity(), 0);
829        assert!(
830            released_size < 128,
831            "expected the released map to report approximately zero bytes, got {released_size}"
832        );
833
834        // The configured capacities survive, so the map warms back up when it
835        // is emitted from again.
836        map.take();
837        assert!(map.map.capacity() >= INITIAL_MAP_CAPACITY);
838        assert_eq!(map.buffer.capacity(), INITIAL_BUFFER_CAPACITY);
839    }
840
841    #[test]
842    fn push_value_bytes_ignores_an_empty_value() {
843        let mut buffer = Vec::new();
844        push_value_bytes(&mut buffer, b"");
845        assert_eq!(buffer.capacity(), 0);
846        assert!(buffer.is_empty());
847
848        push_value_bytes(&mut buffer, b"abcd");
849        let capacity = buffer.capacity();
850        push_value_bytes(&mut buffer, b"");
851        assert_eq!(buffer, b"abcd");
852        assert_eq!(buffer.capacity(), capacity);
853    }
854
855    #[test]
856    fn push_value_bytes_grows_only_past_a_power_of_two() {
857        let mut buffer = Vec::new();
858
859        // A first append that is not itself a power of two still lands on the
860        // ladder: a plain `Vec` would have stopped at a capacity of 9.
861        push_value_bytes(&mut buffer, &[1u8; 9]);
862        assert_eq!(buffer.len(), 9);
863        assert_eq!(buffer.capacity(), 16);
864
865        // Filling exactly to the capacity does not grow it.
866        push_value_bytes(&mut buffer, &[2u8; 7]);
867        assert_eq!(buffer.len(), 16);
868        assert_eq!(buffer.capacity(), 16);
869
870        // The next byte moves up one rung.
871        push_value_bytes(&mut buffer, &[3u8; 1]);
872        assert_eq!(buffer.len(), 17);
873        assert_eq!(buffer.capacity(), 32);
874
875        // So does an append that overshoots several rungs at once.
876        push_value_bytes(&mut buffer, &[4u8; 100]);
877        assert_eq!(buffer.len(), 117);
878        assert_eq!(buffer.capacity(), 128);
879
880        let mut expected = vec![1u8; 9];
881        expected.extend_from_slice(&[2u8; 7]);
882        expected.extend_from_slice(&[3u8; 1]);
883        expected.extend_from_slice(&[4u8; 100]);
884        assert_eq!(buffer, expected);
885    }
886
887    #[test]
888    fn push_value_bytes_does_not_grow_a_buffer_with_room() {
889        let mut buffer = Vec::with_capacity(INITIAL_BUFFER_CAPACITY);
890        let start = buffer.as_ptr();
891
892        let value = vec![7u8; 512];
893        for _ in 0..16 {
894            push_value_bytes(&mut buffer, &value);
895        }
896
897        assert_eq!(buffer.len(), INITIAL_BUFFER_CAPACITY);
898        assert_eq!(buffer.capacity(), INITIAL_BUFFER_CAPACITY);
899        assert!(
900            std::ptr::eq(buffer.as_ptr(), start),
901            "buffer was reallocated"
902        );
903        assert!(buffer.iter().all(|&byte| byte == 7));
904    }
905
906    #[test]
907    fn push_value_bytes_rounds_a_single_oversized_append_up_to_a_power_of_two() {
908        let value = vec![9u8; INITIAL_BUFFER_CAPACITY + 1];
909        let rounded = (INITIAL_BUFFER_CAPACITY + 1).next_power_of_two();
910
911        // A value larger than the pre-allocation lands on the same rung
912        // whether the buffer started empty or pre-allocated, which is what
913        // keeps a lazily allocated map from outgrowing a pre-allocated one.
914        let mut lazy = Vec::new();
915        push_value_bytes(&mut lazy, &value);
916        assert_eq!(lazy.len(), value.len());
917        assert_eq!(lazy.capacity(), rounded);
918        assert_eq!(lazy, value);
919
920        let mut pre_allocated = Vec::with_capacity(INITIAL_BUFFER_CAPACITY);
921        push_value_bytes(&mut pre_allocated, &value);
922        assert_eq!(pre_allocated.capacity(), rounded);
923        assert_eq!(pre_allocated, value);
924    }
925
926    #[test]
927    fn lazy_and_pre_allocated_buffers_grow_on_the_same_ladder() {
928        // Value lengths chosen so the buffer requirement lands between powers
929        // of two, which is where the two ladders used to diverge.
930        for value_len in [9usize, 13, 24, 37] {
931            let mut lazy = ArrowBytesMap::<i32, ()>::new(OutputType::Utf8);
932            let mut pre_allocated = ArrowBytesMap::<i32, ()>::with_capacity(
933                OutputType::Utf8,
934                INITIAL_MAP_CAPACITY,
935            );
936
937            for batch in 0..8 {
938                let values: ArrayRef =
939                    Arc::new(StringArray::from_iter_values((0..1_000).map(|i| {
940                        let value = format!("{}:{i}", batch * 1_000 + i);
941                        format!("{value:value_len$}")
942                    })));
943                lazy.insert_if_new(&values, |_| (), |_| ());
944                pre_allocated.insert_if_new(&values, |_| (), |_| ());
945
946                assert_eq!(lazy.buffer.len(), pre_allocated.buffer.len());
947                assert_eq!(
948                    lazy.buffer.capacity(),
949                    pre_allocated.buffer.capacity(),
950                    "value length {value_len}, batch {batch}: a buffer that \
951                     started empty reached {} bytes of capacity against {} for \
952                     one that started at INITIAL_BUFFER_CAPACITY",
953                    lazy.buffer.capacity(),
954                    pre_allocated.buffer.capacity(),
955                );
956            }
957        }
958    }
959
960    #[test]
961    fn a_lazy_buffer_stays_below_the_pre_allocated_floor_while_it_is_small() {
962        let mut lazy = ArrowBytesMap::<i32, ()>::new(OutputType::Utf8);
963        let values: ArrayRef = Arc::new(StringArray::from_iter_values(
964            (0..10).map(|i| format!("distinct value number {i}")),
965        ));
966        lazy.insert_if_new(&values, |_| (), |_| ());
967
968        assert!(
969            lazy.buffer.capacity() < INITIAL_BUFFER_CAPACITY,
970            "expected a small lazy buffer to stay under the {INITIAL_BUFFER_CAPACITY} \
971             byte pre-allocation, got {}",
972            lazy.buffer.capacity()
973        );
974    }
975
976    #[test]
977    fn string_set_empty() {
978        let mut set = ArrowBytesSet::<i32>::new(OutputType::Utf8);
979        let array: ArrayRef = Arc::new(StringArray::new_null(0));
980        set.insert(&array);
981        assert_eq!(set.len(), 0);
982        assert_eq!(set.non_null_len(), 0);
983        assert_set(set, &[]);
984    }
985
986    #[test]
987    fn string_set_one_null() {
988        let mut set = ArrowBytesSet::<i32>::new(OutputType::Utf8);
989        let array: ArrayRef = Arc::new(StringArray::new_null(1));
990        set.insert(&array);
991        assert_eq!(set.len(), 1);
992        assert_eq!(set.non_null_len(), 0);
993        assert_set(set, &[None]);
994    }
995
996    #[test]
997    fn string_set_many_null() {
998        let mut set = ArrowBytesSet::<i32>::new(OutputType::Utf8);
999        let array: ArrayRef = Arc::new(StringArray::new_null(11));
1000        set.insert(&array);
1001        assert_eq!(set.len(), 1);
1002        assert_eq!(set.non_null_len(), 0);
1003        assert_set(set, &[None]);
1004    }
1005
1006    #[test]
1007    fn string_set_basic_i32() {
1008        test_string_set_basic::<i32>();
1009    }
1010
1011    #[test]
1012    fn string_set_basic_i64() {
1013        test_string_set_basic::<i64>();
1014    }
1015
1016    fn test_string_set_basic<O: OffsetSizeTrait>() {
1017        // basic test for mixed small and large string values
1018        let values = GenericStringArray::<O>::from(vec![
1019            Some("a"),
1020            Some("b"),
1021            Some("CXCCCCCCCC"), // 10 bytes
1022            Some(""),
1023            Some("cbcxx"), // 5 bytes
1024            None,
1025            Some("AAAAAAAA"),  // 8 bytes
1026            Some("BBBBBQBBB"), // 9 bytes
1027            Some("a"),
1028            Some("cbcxx"),
1029            Some("b"),
1030            Some("cbcxx"),
1031            Some(""),
1032            None,
1033            Some("BBBBBQBBB"),
1034            Some("BBBBBQBBB"),
1035            Some("AAAAAAAA"),
1036            Some("CXCCCCCCCC"),
1037        ]);
1038
1039        let mut set = ArrowBytesSet::<O>::new(OutputType::Utf8);
1040        let array: ArrayRef = Arc::new(values);
1041        set.insert(&array);
1042        // values mut appear be in the order they were inserted
1043        assert_set(
1044            set,
1045            &[
1046                Some("a"),
1047                Some("b"),
1048                Some("CXCCCCCCCC"),
1049                Some(""),
1050                Some("cbcxx"),
1051                None,
1052                Some("AAAAAAAA"),
1053                Some("BBBBBQBBB"),
1054            ],
1055        );
1056    }
1057
1058    #[test]
1059    fn string_set_non_utf8_32() {
1060        test_string_set_non_utf8::<i32>();
1061    }
1062
1063    #[test]
1064    fn string_set_non_utf8_64() {
1065        test_string_set_non_utf8::<i64>();
1066    }
1067
1068    fn test_string_set_non_utf8<O: OffsetSizeTrait>() {
1069        // basic test for mixed small and large string values
1070        let values = GenericStringArray::<O>::from(vec![
1071            Some("a"),
1072            Some("✨🔥"),
1073            Some("🔥"),
1074            Some("✨✨✨"),
1075            Some("foobarbaz"),
1076            Some("🔥"),
1077            Some("✨🔥"),
1078        ]);
1079
1080        let mut set = ArrowBytesSet::<O>::new(OutputType::Utf8);
1081        let array: ArrayRef = Arc::new(values);
1082        set.insert(&array);
1083        // strings mut appear be in the order they were inserted
1084        assert_set(
1085            set,
1086            &[
1087                Some("a"),
1088                Some("✨🔥"),
1089                Some("🔥"),
1090                Some("✨✨✨"),
1091                Some("foobarbaz"),
1092            ],
1093        );
1094    }
1095
1096    /// A short value and a long value whose hashes collide must not be confused,
1097    /// whichever of them is inserted first.
1098    ///
1099    /// A short value keeps its bytes inlined in the entry's `offset_or_inline`
1100    /// field, while a long one keeps an offset into the value buffer there. An
1101    /// entry is only examined when its hash matches, so the length has to be
1102    /// compared before that field is interpreted at all. Each direction fails
1103    /// differently without that check, and each case below is chosen to make it
1104    /// actually fail rather than get away with it:
1105    ///
1106    /// * long value looked up against a short entry: `header.range()` is built
1107    ///   out of the inlined bytes, so `"ab"` (0x6162) sends the read tens of
1108    ///   kilobytes past the end of the buffer;
1109    /// * short value looked up against a long entry: the inlined bytes are
1110    ///   compared against that entry's offset, so a single NUL byte (inlined as
1111    ///   0) matches the long value stored at offset 0 and the two distinct
1112    ///   values collapse into one.
1113    ///
1114    /// `force_hash_collisions` makes every value collide, which is the only way
1115    /// to reach either path deterministically.
1116    #[cfg(feature = "force_hash_collisions")]
1117    #[test]
1118    fn short_and_long_values_with_colliding_hashes() {
1119        let long = "a value too long to be inlined";
1120        assert!(long.len() > SHORT_VALUE_LEN);
1121
1122        for [first, second] in [[long, "\0"], ["ab", long]] {
1123            assert!(first.len() <= SHORT_VALUE_LEN || second.len() <= SHORT_VALUE_LEN);
1124            // The second value is the one looked up against an entry of the
1125            // other kind; the repeats must match their own entry.
1126            let values: ArrayRef = Arc::new(StringArray::from(vec![
1127                Some(first),
1128                Some(second),
1129                Some(first),
1130                Some(second),
1131            ]));
1132
1133            let mut map = ArrowBytesMap::<i32, usize>::new(OutputType::Utf8);
1134            let mut inserted = vec![];
1135            let mut payloads = 0;
1136            map.insert_if_new(
1137                &values,
1138                |value| {
1139                    inserted.push(value.expect("no nulls in this test").to_vec());
1140                    payloads += 1;
1141                    payloads
1142                },
1143                |_| {},
1144            );
1145
1146            assert_eq!(
1147                inserted,
1148                vec![first.as_bytes().to_vec(), second.as_bytes().to_vec()],
1149                "inserting {first:?} then {second:?}"
1150            );
1151        }
1152    }
1153
1154    // asserts that the set contains the expected strings, in the same order
1155    fn assert_set<O: OffsetSizeTrait>(set: ArrowBytesSet<O>, expected: &[Option<&str>]) {
1156        let strings = set.into_state();
1157        let strings = strings.as_string::<O>();
1158        let state = strings.into_iter().collect::<Vec<_>>();
1159        assert_eq!(state, expected);
1160    }
1161
1162    // Test use of binary output type
1163    #[test]
1164    fn test_binary_set() {
1165        let values: ArrayRef = Arc::new(BinaryArray::from_opt_vec(vec![
1166            Some(b"a"),
1167            Some(b"CXCCCCCCCC"),
1168            None,
1169            Some(b"CXCCCCCCCC"),
1170        ]));
1171
1172        let expected: ArrayRef = Arc::new(BinaryArray::from_opt_vec(vec![
1173            Some(b"a"),
1174            Some(b"CXCCCCCCCC"),
1175            None,
1176        ]));
1177
1178        let mut set = ArrowBytesSet::<i32>::new(OutputType::Binary);
1179        set.insert(&values);
1180        assert_eq!(&set.into_state(), &expected);
1181    }
1182
1183    // Test use of binary output type
1184    #[test]
1185    fn test_large_binary_set() {
1186        let values: ArrayRef = Arc::new(LargeBinaryArray::from_opt_vec(vec![
1187            Some(b"a"),
1188            Some(b"CXCCCCCCCC"),
1189            None,
1190            Some(b"CXCCCCCCCC"),
1191        ]));
1192
1193        let expected: ArrayRef = Arc::new(LargeBinaryArray::from_opt_vec(vec![
1194            Some(b"a"),
1195            Some(b"CXCCCCCCCC"),
1196            None,
1197        ]));
1198
1199        let mut set = ArrowBytesSet::<i64>::new(OutputType::Binary);
1200        set.insert(&values);
1201        assert_eq!(&set.into_state(), &expected);
1202    }
1203
1204    #[test]
1205    #[should_panic(
1206        expected = "matches!(values.data_type(), DataType::Utf8 | DataType::LargeUtf8)"
1207    )]
1208    fn test_mismatched_types() {
1209        // inserting binary into a set that expects strings should panic
1210        let values: ArrayRef = Arc::new(LargeBinaryArray::from_opt_vec(vec![Some(b"a")]));
1211
1212        let mut set = ArrowBytesSet::<i64>::new(OutputType::Utf8);
1213        set.insert(&values);
1214    }
1215
1216    #[test]
1217    #[should_panic(expected = "byte array")]
1218    fn test_mismatched_sizes() {
1219        // inserting large strings into a set that expects small should panic
1220        let values: ArrayRef = Arc::new(LargeBinaryArray::from_opt_vec(vec![Some(b"a")]));
1221
1222        let mut set = ArrowBytesSet::<i32>::new(OutputType::Binary);
1223        set.insert(&values);
1224    }
1225
1226    // put more than 2GB in a string set and expect it to panic
1227    #[test]
1228    #[should_panic(
1229        expected = "Put 2147483648 bytes in buffer, more than can be represented by a i32"
1230    )]
1231    fn test_string_overflow() {
1232        let mut set = ArrowBytesSet::<i32>::new(OutputType::Utf8);
1233        for value in ["a", "b", "c"] {
1234            // 1GB strings, so 3rd is over 2GB and should panic
1235            let arr: ArrayRef =
1236                Arc::new(StringArray::from_iter_values([value.repeat(1 << 30)]));
1237            set.insert(&arr);
1238        }
1239    }
1240
1241    // inserting strings into the set does not increase reported memory
1242    #[test]
1243    fn test_string_set_memory_usage() {
1244        let strings1 = GenericStringArray::<i32>::from(vec![
1245            Some("a"),
1246            Some("b"),
1247            Some("CXCCCCCCCC"), // 10 bytes
1248            Some("AAAAAAAA"),   // 8 bytes
1249            Some("BBBBBQBBB"),  // 9 bytes
1250        ]);
1251        let total_strings1_len = strings1
1252            .iter()
1253            .map(|s| s.map(|s| s.len()).unwrap_or(0))
1254            .sum::<usize>();
1255        let values1: ArrayRef = Arc::new(GenericStringArray::<i32>::from(strings1));
1256
1257        // Much larger strings in strings2
1258        let strings2 = GenericStringArray::<i32>::from(vec![
1259            "FOO".repeat(1000),
1260            "BAR".repeat(2000),
1261            "BAZ".repeat(3000),
1262        ]);
1263        let total_strings2_len = strings2
1264            .iter()
1265            .map(|s| s.map(|s| s.len()).unwrap_or(0))
1266            .sum::<usize>();
1267        let values2: ArrayRef = Arc::new(GenericStringArray::<i32>::from(strings2));
1268
1269        let mut set = ArrowBytesSet::<i32>::new(OutputType::Utf8);
1270        let size_empty = set.size();
1271
1272        set.insert(&values1);
1273        let size_after_values1 = set.size();
1274        assert!(size_empty < size_after_values1);
1275        assert!(
1276            size_after_values1 > total_strings1_len,
1277            "expect {size_after_values1} to be more than {total_strings1_len}"
1278        );
1279        assert!(size_after_values1 < total_strings1_len + total_strings2_len);
1280
1281        // inserting the same strings should not affect the size
1282        set.insert(&values1);
1283        assert_eq!(set.size(), size_after_values1);
1284
1285        // inserting the large strings should increase the reported size
1286        set.insert(&values2);
1287        let size_after_values2 = set.size();
1288        assert!(size_after_values2 > size_after_values1);
1289        assert!(size_after_values2 > total_strings1_len + total_strings2_len);
1290    }
1291
1292    #[test]
1293    fn test_map() {
1294        let input = vec![
1295            // Note mix of short/long strings
1296            Some("A"),
1297            Some("bcdefghijklmnop"),
1298            Some("X"),
1299            Some("Y"),
1300            None,
1301            Some("qrstuvqxyzhjwya"),
1302            Some("✨🔥"),
1303            Some("🔥"),
1304            Some("🔥🔥🔥🔥🔥🔥"),
1305        ];
1306
1307        let mut test_map = TestMap::new();
1308        test_map.insert(&input);
1309        test_map.insert(&input); // put it in twice
1310        let expected_output: ArrayRef = Arc::new(StringArray::from(input));
1311        assert_eq!(&test_map.into_array(), &expected_output);
1312    }
1313
1314    #[derive(Debug, PartialEq, Eq, Default, Clone, Copy)]
1315    struct TestPayload {
1316        // store the string value to check against input
1317        index: usize, // store the index of the string (each new string gets the next sequential input)
1318    }
1319
1320    /// Wraps an [`ArrowBytesMap`], validating its invariants
1321    struct TestMap {
1322        map: ArrowBytesMap<i32, TestPayload>,
1323        // stores distinct strings seen, in order
1324        strings: Vec<Option<String>>,
1325        // map strings to index in strings
1326        indexes: HashMap<Option<String>, usize>,
1327    }
1328
1329    impl Debug for TestMap {
1330        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1331            f.debug_struct("TestMap")
1332                .field("map", &"...")
1333                .field("strings", &self.strings)
1334                .field("indexes", &self.indexes)
1335                .finish()
1336        }
1337    }
1338
1339    impl TestMap {
1340        /// creates a map with TestPayloads for the given strings and then
1341        /// validates the payloads
1342        fn new() -> Self {
1343            Self {
1344                map: ArrowBytesMap::new(OutputType::Utf8),
1345                strings: vec![],
1346                indexes: HashMap::new(),
1347            }
1348        }
1349
1350        /// Inserts strings into the map
1351        fn insert(&mut self, strings: &[Option<&str>]) {
1352            let string_array = StringArray::from(strings.to_vec());
1353            let arr: ArrayRef = Arc::new(string_array);
1354
1355            let mut next_index = self.indexes.len();
1356            let mut actual_new_strings = vec![];
1357            let mut actual_seen_indexes = vec![];
1358            // update self with new values, keeping track of newly added values
1359            for str in strings {
1360                let str = str.map(|s| s.to_string());
1361                let index = self.indexes.get(&str).copied().unwrap_or_else(|| {
1362                    actual_new_strings.push(str.clone());
1363                    let index = self.strings.len();
1364                    self.strings.push(str.clone());
1365                    self.indexes.insert(str, index);
1366                    index
1367                });
1368                actual_seen_indexes.push(index);
1369            }
1370
1371            // insert the values into the map, recording what we did
1372            let mut seen_new_strings = vec![];
1373            let mut seen_indexes = vec![];
1374            self.map.insert_if_new(
1375                &arr,
1376                |s| {
1377                    let value = s
1378                        .map(|s| String::from_utf8(s.to_vec()).expect("Non utf8 string"));
1379                    let index = next_index;
1380                    next_index += 1;
1381                    seen_new_strings.push(value);
1382                    TestPayload { index }
1383                },
1384                |payload| {
1385                    seen_indexes.push(payload.index);
1386                },
1387            );
1388
1389            assert_eq!(actual_seen_indexes, seen_indexes);
1390            assert_eq!(actual_new_strings, seen_new_strings);
1391        }
1392
1393        /// Call `self.map.into_array()` validating that the strings are in the same
1394        /// order as they were inserted
1395        fn into_array(self) -> ArrayRef {
1396            let Self {
1397                map,
1398                strings,
1399                indexes: _,
1400            } = self;
1401
1402            let arr = map.into_state();
1403            let expected: ArrayRef = Arc::new(StringArray::from(strings));
1404            assert_eq!(&arr, &expected);
1405            arr
1406        }
1407    }
1408}