datafusion-physical-expr-common 56.0.0

Common functionality of physical expression for DataFusion query engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements

//! [`ArrowBytesViewMap`] and [`ArrowBytesViewSet`] for storing maps/sets of values from
//! `StringViewArray`/`BinaryViewArray`.
use crate::binary_map::{OutputType, single_null_buffer};
use arrow::array::cast::AsArray;
use arrow::array::{
    Array, ArrayRef, BinaryViewArray, BinaryViewBuilder, ByteView, StringViewBuilder,
    make_view,
};
use arrow::buffer::{Buffer, ScalarBuffer};
use arrow::datatypes::{BinaryViewType, ByteViewType, DataType, StringViewType};
use datafusion_common::hash_utils::RandomState;
use datafusion_common::hash_utils::create_hashes;
use datafusion_common::utils::proxy::VecAllocExt;
use datafusion_common::{Result, exec_err};
use std::fmt::Debug;
use std::sync::Arc;

/// HashSet optimized for storing string or binary values that can produce that
/// the final set as a `GenericBinaryViewArray` with minimal copies.
#[derive(Debug)]
pub struct ArrowBytesViewSet(ArrowBytesViewMap<()>);

impl ArrowBytesViewSet {
    /// Creates a set that does not pre-allocate its hash table.
    ///
    /// See [`ArrowBytesViewMap::new`] for when to prefer this over
    /// [`Self::with_capacity`].
    pub fn new(output_type: OutputType) -> Self {
        Self(ArrowBytesViewMap::new(output_type))
    }

    /// Creates a set with room for `map_capacity` entries.
    ///
    /// See [`ArrowBytesViewMap::with_capacity`].
    pub fn with_capacity(output_type: OutputType, map_capacity: usize) -> Self {
        Self(ArrowBytesViewMap::with_capacity(output_type, map_capacity))
    }

    /// Inserts each value from `values` into the set
    pub fn insert(&mut self, values: &ArrayRef) {
        fn make_payload_fn(_value: Option<&[u8]>) {}
        fn observe_payload_fn(_payload: ()) {}
        self.0
            .insert_if_new(values, make_payload_fn, observe_payload_fn);
    }

    /// Return the contents of this map and replace it with a new empty map with
    /// the same output type
    pub fn take(&mut self) -> Self {
        Self(self.0.take())
    }

    /// Converts this set into a `StringViewArray` or `BinaryViewArray`
    /// containing each distinct value that was interned.
    /// This is done without copying the values.
    pub fn into_state(self) -> ArrayRef {
        self.0.into_state()
    }

    /// Returns the total number of distinct values (including nulls) seen so far
    pub fn len(&self) -> usize {
        self.0.len()
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// returns the total number of distinct values (not including nulls) seen so far
    pub fn non_null_len(&self) -> usize {
        self.0.non_null_len()
    }

    /// Return the total size, in bytes, of memory used to store the data in
    /// this set, not including `self`
    pub fn size(&self) -> usize {
        self.0.size()
    }
}

/// Optimized map for storing Arrow "byte view" types (`StringView`, `BinaryView`)
/// values that can produce the set of keys on
/// output as `GenericBinaryViewArray` without copies.
///
/// Equivalent to `HashSet<String, V>` but with better performance if you need
/// to emit the keys as an Arrow `StringViewArray` / `BinaryViewArray`. For other
/// purposes it is the same as a `HashMap<String, V>`
///
/// # Generic Arguments
///
/// * `V`: payload type
///
/// # Description
///
/// This is a specialized HashMap with the following properties:
///
/// 1. Optimized for storing and emitting Arrow byte types  (e.g.
///    `StringViewArray` / `BinaryViewArray`) very efficiently by minimizing copying of
///    the string values themselves, both when inserting and when emitting the
///    final array.
///
/// 2. Retains the insertion order of entries in the final array. The values are
///    in the same order as they were inserted.
///
/// Note this structure can be used as a `HashSet` by specifying the value type
/// as `()`, as is done by [`ArrowBytesViewSet`].
///
/// This map is used by the special `COUNT DISTINCT` aggregate function to
/// store the distinct values, and by the `GROUP BY` operator to store
/// group values when they are a single string array.
/// Max size of the in-progress buffer before flushing to completed buffers
const BYTE_VIEW_MAX_BLOCK_SIZE: usize = 2 * 1024 * 1024;

pub struct ArrowBytesViewMap<V>
where
    V: Debug + PartialEq + Eq + Clone + Copy + Default,
{
    /// Should the output be StringView or BinaryView?
    output_type: OutputType,
    /// Underlying hash set for each distinct value
    map: hashbrown::hash_table::HashTable<Entry<V>>,
    /// Hash table capacity to re-create the map with in [`Self::take`], so a
    /// map built with [`Self::with_capacity`] keeps its pre-allocation when it
    /// is emptied and reused
    initial_map_capacity: usize,

    /// Views for all stored values (in insertion order)
    views: Vec<u128>,
    /// In-progress buffer for out-of-line string data
    in_progress: Vec<u8>,
    /// Completed buffers containing string data
    completed: Vec<Buffer>,

    /// random state used to generate hashes
    random_state: RandomState,
    /// buffer that stores hash values (reused across batches to save allocations)
    hashes_buffer: Vec<u64>,
    /// `(payload, null_index)` for the 'null' value, if any
    /// NOTE null_index is the logical index in the final array, not the index
    /// in the buffer
    null: Option<(V, usize)>,
}

/// The size, in number of entries, of the hash table pre-allocated by
/// [`ArrowBytesViewMap::with_capacity`]. It is a warm up size for maps that go
/// on to hold many values, not a bound on what the map can hold.
pub const INITIAL_MAP_CAPACITY: usize = 512;

impl<V> ArrowBytesViewMap<V>
where
    V: Debug + PartialEq + Eq + Clone + Copy + Default,
{
    /// Creates a map that does not pre-allocate its hash table.
    ///
    /// Use this when maps are created in large numbers and most of them stay
    /// small, such as the per group `COUNT(DISTINCT)` accumulators that
    /// `GroupsAccumulatorAdapter` creates one of per group. There the
    /// pre-allocation dwarfs the values the map actually holds.
    pub fn new(output_type: OutputType) -> Self {
        Self::with_capacity(output_type, 0)
    }

    /// Creates a map whose hash table is pre-allocated for `map_capacity`
    /// entries.
    ///
    /// Use this for the few long lived maps that are each expected to hold many
    /// values, such as the single map backing a `GROUP BY` on one string
    /// column. The capacity is preserved across [`Self::take`].
    pub fn with_capacity(output_type: OutputType, map_capacity: usize) -> Self {
        Self {
            output_type,
            map: hashbrown::hash_table::HashTable::with_capacity(map_capacity),
            initial_map_capacity: map_capacity,
            views: Vec::new(),
            in_progress: Vec::new(),
            completed: Vec::new(),
            random_state: RandomState::default(),
            hashes_buffer: vec![],
            null: None,
        }
    }

    /// Return the contents of this map and replace it with a new empty map with
    /// the same output type
    pub fn take(&mut self) -> Self {
        let mut new_self =
            Self::with_capacity(self.output_type, self.initial_map_capacity);
        std::mem::swap(self, &mut new_self);
        new_self
    }

    /// Empties this map and releases every allocation it holds, so
    /// [`Self::size`] drops to approximately zero.
    ///
    /// This is the difference from [`Self::take`]: `take` restores the capacity
    /// the map was configured with so the emptied map stays warm for continued
    /// use, which is what emitting wants, whereas here the point is to hand the
    /// memory back, as before spilling or before a downstream sort. The
    /// configured capacity is remembered, so the next [`Self::take`] warms the
    /// map up again.
    pub fn clear_and_release(&mut self) {
        let mut released = Self::with_capacity(self.output_type, 0);
        released.initial_map_capacity = self.initial_map_capacity;
        *self = released;
    }

    /// Inserts each value from `values` into the map, invoking `payload_fn` for
    /// each value if *not* already present, deferring the allocation of the
    /// payload until it is needed.
    ///
    /// Note that this is different than a normal map that would replace the
    /// existing entry
    ///
    /// # Arguments:
    ///
    /// `values`: array whose values are inserted
    ///
    /// `make_payload_fn`:  invoked for each value that is not already present
    /// to create the payload, in order of the values in `values`
    ///
    /// `observe_payload_fn`: invoked once, for each value in `values`, that was
    /// already present in the map, with corresponding payload value.
    ///
    /// # Returns
    ///
    /// The payload value for the entry, either the existing value or
    /// the newly inserted value
    ///
    /// # Safety:
    ///
    /// Note that `make_payload_fn` and `observe_payload_fn` are only invoked
    /// with valid values from `values`, not for the `NULL` value.
    pub fn insert_if_new<MP, OP>(
        &mut self,
        values: &ArrayRef,
        make_payload_fn: MP,
        observe_payload_fn: OP,
    ) where
        MP: FnMut(Option<&[u8]>) -> V,
        OP: FnMut(V),
    {
        // Sanity check array type
        match self.output_type {
            OutputType::BinaryView => {
                assert!(matches!(values.data_type(), DataType::BinaryView));
                self.insert_if_new_inner::<MP, OP, BinaryViewType>(
                    values,
                    make_payload_fn,
                    observe_payload_fn,
                )
            }
            OutputType::Utf8View => {
                assert!(matches!(values.data_type(), DataType::Utf8View));
                self.insert_if_new_inner::<MP, OP, StringViewType>(
                    values,
                    make_payload_fn,
                    observe_payload_fn,
                )
            }
            _ => unreachable!("Utf8/Binary should use `ArrowBytesSet`"),
        }
    }

    /// Generic version of [`Self::insert_if_new`] that handles `ByteViewType`
    /// (both StringView and BinaryView)
    ///
    /// Note this is the only function that is generic on [`ByteViewType`], which
    /// avoids having to template the entire structure,  making the code
    /// simpler and understand and reducing code bloat due to duplication.
    ///
    /// See comments on `insert_if_new` for more details
    fn insert_if_new_inner<MP, OP, B>(
        &mut self,
        values: &ArrayRef,
        mut make_payload_fn: MP,
        mut observe_payload_fn: OP,
    ) where
        MP: FnMut(Option<&[u8]>) -> V,
        OP: FnMut(V),
        B: ByteViewType,
    {
        // step 1: compute hashes
        let batch_hashes = &mut self.hashes_buffer;
        batch_hashes.clear();
        batch_hashes.resize(values.len(), 0);
        create_hashes([values], &self.random_state, batch_hashes)
            // hash is supported for all types and create_hashes only
            // returns errors for unsupported types
            .unwrap();

        // step 2: insert each value into the set, if not already present
        let values = values.as_byte_view::<B>();

        // Get raw views buffer for direct comparison
        let input_views = values.views();

        // Ensure lengths are equivalent
        assert_eq!(values.len(), self.hashes_buffer.len());

        for i in 0..values.len() {
            let view_u128 = input_views[i];
            let hash = self.hashes_buffer[i];

            // handle null value via validity bitmap check
            if values.is_null(i) {
                let payload = if let Some(&(payload, _offset)) = self.null.as_ref() {
                    payload
                } else {
                    let payload = make_payload_fn(None);
                    let null_index = self.views.len();
                    self.views.push(0);
                    self.null = Some((payload, null_index));
                    payload
                };
                observe_payload_fn(payload);
                continue;
            }

            // Extract length from the view (first 4 bytes of u128 in little-endian)
            let len = view_u128 as u32;

            // Check if value already exists
            let maybe_payload = {
                // Borrow completed and in_progress for comparison
                let completed = &self.completed;
                let in_progress = &self.in_progress;

                self.map
                    .find(hash, |header| {
                        if header.hash != hash {
                            return false;
                        }

                        // Fast path: inline strings can be compared directly
                        if len <= 12 {
                            return header.view == view_u128;
                        }

                        // For larger strings: first compare the 4-byte prefix
                        let stored_prefix = (header.view >> 32) as u32;
                        let input_prefix = (view_u128 >> 32) as u32;
                        if stored_prefix != input_prefix {
                            return false;
                        }

                        // Prefix matched - compare full bytes
                        let byte_view = ByteView::from(header.view);
                        let stored_len = byte_view.length as usize;
                        let buffer_index = byte_view.buffer_index as usize;
                        let offset = byte_view.offset as usize;

                        let stored_value = if buffer_index < completed.len() {
                            &completed[buffer_index].as_slice()
                                [offset..offset + stored_len]
                        } else {
                            &in_progress[offset..offset + stored_len]
                        };
                        let input_value: &[u8] = values.value(i).as_ref();
                        stored_value == input_value
                    })
                    .map(|entry| entry.payload)
            };

            let payload = if let Some(payload) = maybe_payload {
                payload
            } else {
                // no existing value, make a new one
                let (new_view, payload) = if len <= 12 {
                    // Inline path: bytes are already packed in view_u128.
                    // The inline ByteView format is [len:u32 LE][data:12 bytes zero-padded],
                    // so extracting bytes from the u128 avoids a round-trip through
                    // values.value(i) (which reads the views buffer and returns the same slice).
                    let view_bytes = view_u128.to_le_bytes();
                    let value = &view_bytes[4..4 + len as usize];
                    let payload = make_payload_fn(Some(value));
                    // For inline strings, the stored view is identical to the input view:
                    // make_view(value, 0, 0) produces the same u128 as view_u128.
                    //
                    // SAFETY: view_u128 was a valid view, and the enclosing `len <= 12`
                    // ensures it is inline
                    let new_view = unsafe { self.append_inline_view(view_u128) };
                    (new_view, payload)
                } else {
                    let value: &[u8] = values.value(i).as_ref();
                    let payload = make_payload_fn(Some(value));
                    let new_view = self.append_value(value);
                    (new_view, payload)
                };

                let new_header = Entry {
                    view: new_view,
                    hash,
                    payload,
                };

                self.map.insert_unique(hash, new_header, |h| h.hash);
                payload
            };
            observe_payload_fn(payload);
        }
    }

    /// Returns the bytes for the key at `index`, irrespective of nullness.
    fn key(&self, index: usize) -> &[u8] {
        let view = &self.views[index];
        let byte_view = ByteView::from(*view);
        let length = byte_view.length as usize;
        if length <= 12 {
            // SAFETY: `view` is a valid inline view with `length` bytes.
            unsafe { BinaryViewArray::inline_value(view, length) }
        } else {
            let buffer_index = byte_view.buffer_index as usize;
            let offset = byte_view.offset as usize;
            if buffer_index < self.completed.len() {
                &self.completed[buffer_index][offset..offset + length]
            } else {
                &self.in_progress[offset..offset + length]
            }
        }
    }

    /// Converts this set into a `StringViewArray`, or `BinaryViewArray`,
    /// containing each distinct value
    /// that was inserted. This is done without copying the values.
    ///
    /// The values are guaranteed to be returned in the same order in which
    /// they were first seen.
    pub fn into_state(mut self) -> ArrayRef {
        // Flush any remaining in-progress buffer
        if !self.in_progress.is_empty() {
            let flushed = std::mem::take(&mut self.in_progress);
            self.completed.push(Buffer::from_vec(flushed));
        }

        // Build null buffer if we have any nulls
        let null_buffer = match self.null {
            Some((_payload, index)) => Some(single_null_buffer(self.views.len(), index)),
            None => None,
        };

        let views = ScalarBuffer::from(self.views);
        let array = unsafe {
            BinaryViewArray::new_unchecked(views, self.completed.into(), null_buffer)
        };

        match self.output_type {
            OutputType::BinaryView => Arc::new(array),
            OutputType::Utf8View => {
                // SAFETY: all input was valid utf8
                let array = unsafe { array.to_string_view_unchecked() };
                Arc::new(array)
            }
            _ => unreachable!("Utf8/Binary should use `ArrowBytesMap`"),
        }
    }

    /// Copies keys at `indices` into an array without changing this map.
    ///
    /// Keys are returned in index order, and duplicate indices are supported.
    pub fn keys<I>(&self, indices: I) -> Result<ArrayRef>
    where
        I: IntoIterator<Item = usize>,
    {
        let indices = indices.into_iter();
        let capacity = indices.size_hint().0;
        let num_keys = self.views.len();
        let null_index = self.null.map(|(_, index)| index);

        macro_rules! build_keys {
            ($builder:ty, $value:expr) => {{
                let mut builder = <$builder>::with_capacity(capacity);
                for index in indices {
                    if index >= num_keys {
                        return exec_err!(
                            "Key index {index} is out of bounds for {num_keys} keys"
                        );
                    }
                    if null_index == Some(index) {
                        builder.append_null();
                    } else {
                        builder.append_value($value(self.key(index)));
                    }
                }
                Arc::new(builder.finish()) as ArrayRef
            }};
        }

        Ok(match self.output_type {
            OutputType::BinaryView => build_keys!(BinaryViewBuilder, |value| value),
            OutputType::Utf8View => build_keys!(StringViewBuilder, |value| unsafe {
                // Inputs to an Utf8View map are validated UTF-8.
                std::str::from_utf8_unchecked(value)
            }),
            _ => unreachable!("Utf8/Binary should use `ArrowBytesMap`"),
        })
    }

    /// Append an already-computed inline view (len <= 12) directly, bypassing
    /// buffer allocation.
    ///
    /// Returns the view that was stored (identical to the argument).
    ///
    /// # Safety
    ///
    /// `view` must be a valid inline `ByteView`: the length field in the low
    /// 32 bits must be <= 12, and the remaining 12 bytes must hold the
    /// value's bytes (zero-padded if shorter). Calling with a non-inline view
    /// would store a value that downstream `views` consumers interpret as
    /// `[buffer_index, offset]` into the `completed`/`in_progress` buffers,
    /// which is unsound for any view that didn't originate from a real
    /// allocation in those buffers.
    unsafe fn append_inline_view(&mut self, view: u128) -> u128 {
        self.views.push(view);
        view
    }

    /// Append a value to our buffers and return the view pointing to it
    fn append_value(&mut self, value: &[u8]) -> u128 {
        let len = value.len();
        let view = if len <= 12 {
            make_view(value, 0, 0)
        } else {
            // Ensure buffer is big enough
            if self.in_progress.len() + len > BYTE_VIEW_MAX_BLOCK_SIZE {
                let flushed = std::mem::replace(
                    &mut self.in_progress,
                    Vec::with_capacity(BYTE_VIEW_MAX_BLOCK_SIZE),
                );
                self.completed.push(Buffer::from_vec(flushed));
            }

            let buffer_index = self.completed.len() as u32;
            let offset = self.in_progress.len() as u32;
            self.in_progress.extend_from_slice(value);

            make_view(value, buffer_index, offset)
        };

        self.views.push(view);
        view
    }

    /// Total number of entries (including null, if present)
    pub fn len(&self) -> usize {
        self.non_null_len() + self.null.map(|_| 1).unwrap_or(0)
    }

    /// Is the set empty?
    pub fn is_empty(&self) -> bool {
        self.map.is_empty() && self.null.is_none()
    }

    /// Number of non null entries
    pub fn non_null_len(&self) -> usize {
        self.map.len()
    }

    /// Return the total size, in bytes, of memory used to store the data in
    /// this set, not including `self` or input-array buffers.
    pub fn size(&self) -> usize {
        // All fields below own their allocations. Count retained capacity rather
        // than used length because this value drives memory accounting.
        //
        // `HashTable::allocation_size` reports the whole hashbrown allocation,
        // which is the entry array plus the control bytes plus the trailing
        // group, so it is larger than `capacity() * size_of::<Entry<V>>()`. It
        // is a constant time layout calculation, not a walk of the table.
        let map_size = self.map.allocation_size();
        let views_size = self.views.allocated_size();
        let in_progress_size = self.in_progress.allocated_size();
        let completed_size = self.completed.allocated_size()
            + self.completed.iter().map(Buffer::capacity).sum::<usize>();

        map_size
            + views_size
            + in_progress_size
            + completed_size
            + self.hashes_buffer.allocated_size()
    }
}

impl<V> Debug for ArrowBytesViewMap<V>
where
    V: Debug + PartialEq + Eq + Clone + Copy + Default,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ArrowBytesMap")
            .field("map", &"<map>")
            .field("map_allocation_size", &self.map.allocation_size())
            .field("views_len", &self.views.len())
            .field("completed_buffers", &self.completed.len())
            .field("random_state", &self.random_state)
            .field("hashes_buffer", &self.hashes_buffer)
            .finish()
    }
}

/// Entry in the hash table -- see [`ArrowBytesViewMap`] for more details
///
/// Stores the view pointing to our internal buffers, eliminating the need
/// for a separate builder index. For inline strings (<=12 bytes), the view
/// contains the entire value. For out-of-line strings, the view contains
/// buffer_index and offset pointing directly to our storage.
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
struct Entry<V>
where
    V: Debug + PartialEq + Eq + Clone + Copy + Default,
{
    /// The u128 view pointing to our internal buffers. For inline strings,
    /// this contains the complete value. For larger strings, this contains
    /// the buffer_index/offset into our completed/in_progress buffers.
    view: u128,

    hash: u64,

    /// value stored by the entry
    payload: V,
}

#[cfg(test)]
mod tests {
    use arrow::array::{GenericByteViewArray, StringViewArray};
    use datafusion_common::HashMap;
    use std::mem::size_of;

    use super::*;

    // asserts that the set contains the expected strings, in the same order
    fn assert_set(set: ArrowBytesViewSet, expected: &[Option<&str>]) {
        let strings = set.into_state();
        let strings = strings.as_string_view();
        let state = strings.into_iter().collect::<Vec<_>>();
        assert_eq!(state, expected);
    }

    #[test]
    fn string_view_set_empty() {
        let mut set = ArrowBytesViewSet::new(OutputType::Utf8View);
        let array: ArrayRef = Arc::new(StringViewArray::new_null(0));
        set.insert(&array);
        assert_eq!(set.len(), 0);
        assert_eq!(set.non_null_len(), 0);
        assert_set(set, &[]);
    }

    #[test]
    fn string_view_set_one_null() {
        let mut set = ArrowBytesViewSet::new(OutputType::Utf8View);
        let array: ArrayRef = Arc::new(StringViewArray::new_null(1));
        set.insert(&array);
        assert_eq!(set.len(), 1);
        assert_eq!(set.non_null_len(), 0);
        assert_set(set, &[None]);
    }

    #[test]
    fn string_view_set_many_null() {
        let mut set = ArrowBytesViewSet::new(OutputType::Utf8View);
        let array: ArrayRef = Arc::new(StringViewArray::new_null(11));
        set.insert(&array);
        assert_eq!(set.len(), 1);
        assert_eq!(set.non_null_len(), 0);
        assert_set(set, &[None]);
    }

    #[test]
    fn test_string_view_set_basic() {
        // basic test for mixed small and large string values
        let values = GenericByteViewArray::from(vec![
            Some("a"),
            Some("b"),
            Some("CXCCCCCCCCAABB"), // 14 bytes
            Some(""),
            Some("cbcxx"), // 5 bytes
            None,
            Some("AAAAAAAA"),     // 8 bytes
            Some("BBBBBQBBBAAA"), // 12 bytes
            Some("a"),
            Some("cbcxx"),
            Some("b"),
            Some("cbcxx"),
            Some(""),
            None,
            Some("BBBBBQBBBAAA"),
            Some("BBBBBQBBBAAA"),
            Some("AAAAAAAA"),
            Some("CXCCCCCCCCAABB"),
        ]);

        let mut set = ArrowBytesViewSet::new(OutputType::Utf8View);
        let array: ArrayRef = Arc::new(values);
        set.insert(&array);
        // values mut appear be in the order they were inserted
        assert_set(
            set,
            &[
                Some("a"),
                Some("b"),
                Some("CXCCCCCCCCAABB"),
                Some(""),
                Some("cbcxx"),
                None,
                Some("AAAAAAAA"),
                Some("BBBBBQBBBAAA"),
            ],
        );
    }

    #[test]
    fn test_string_set_non_utf8() {
        // basic test for mixed small and large string values
        let values = GenericByteViewArray::from(vec![
            Some("a"),
            Some("✨🔥✨🔥✨🔥✨🔥✨🔥✨🔥✨🔥✨🔥"),
            Some("🔥"),
            Some("✨✨✨"),
            Some("foobarbaz"),
            Some("🔥"),
            Some("✨🔥✨🔥✨🔥✨🔥✨🔥✨🔥✨🔥✨🔥"),
        ]);

        let mut set = ArrowBytesViewSet::new(OutputType::Utf8View);
        let array: ArrayRef = Arc::new(values);
        set.insert(&array);
        // strings mut appear be in the order they were inserted
        assert_set(
            set,
            &[
                Some("a"),
                Some("✨🔥✨🔥✨🔥✨🔥✨🔥✨🔥✨🔥✨🔥"),
                Some("🔥"),
                Some("✨✨✨"),
                Some("foobarbaz"),
            ],
        );
    }

    // Test use of binary output type
    #[test]
    fn test_binary_set() {
        let v: Vec<Option<&[u8]>> = vec![
            Some(b"a"),
            Some(b"CXCCCCCCCCCCCCC"),
            None,
            Some(b"CXCCCCCCCCCCCCC"),
        ];
        let values: ArrayRef = Arc::new(BinaryViewArray::from(v));

        let expected: Vec<Option<&[u8]>> =
            vec![Some(b"a"), Some(b"CXCCCCCCCCCCCCC"), None];
        let expected: ArrayRef = Arc::new(GenericByteViewArray::from(expected));

        let mut set = ArrowBytesViewSet::new(OutputType::BinaryView);
        set.insert(&values);
        assert_eq!(&set.into_state(), &expected);
    }

    // inserting strings into the set does not increase reported memory
    #[test]
    fn test_string_set_memory_usage() {
        let strings1 = StringViewArray::from(vec![
            Some("a"),
            Some("b"),
            Some("CXCCCCCCCCCCC"), // 13 bytes
            Some("AAAAAAAA"),      // 8 bytes
            Some("BBBBBQBBB"),     // 9 bytes
        ]);
        let total_strings1_len = strings1
            .iter()
            .map(|s| s.map(|s| s.len()).unwrap_or(0))
            .sum::<usize>();
        let values1: ArrayRef = Arc::new(StringViewArray::from(strings1));

        // Much larger strings in strings2
        let strings2 = StringViewArray::from(vec![
            "FOO".repeat(1000),
            "BAR larger than 12 bytes.".repeat(100_000),
            "more unique.".repeat(1000),
            "more unique2.".repeat(1000),
            "FOO".repeat(3000),
        ]);
        let total_strings2_len = strings2
            .iter()
            .map(|s| s.map(|s| s.len()).unwrap_or(0))
            .sum::<usize>();
        let values2: ArrayRef = Arc::new(StringViewArray::from(strings2));

        let mut set = ArrowBytesViewSet::new(OutputType::Utf8View);
        let size_empty = set.size();

        set.insert(&values1);
        let size_after_values1 = set.size();
        assert!(size_empty < size_after_values1);
        assert!(
            size_after_values1 > total_strings1_len,
            "expect {size_after_values1} to be more than {total_strings1_len}"
        );
        assert!(size_after_values1 < total_strings1_len + total_strings2_len);

        // inserting the same strings should not affect the size
        set.insert(&values1);
        assert_eq!(set.size(), size_after_values1);
        assert_eq!(set.len(), 5);

        // inserting the large strings should increase the reported size
        set.insert(&values2);
        let size_after_values2 = set.size();
        assert!(size_after_values2 > size_after_values1);

        assert_eq!(set.len(), 10);
    }

    /// A lower bound on the bytes a hashbrown table holding `entries` entries
    /// of type `T` must allocate: one entry slot and one control byte each.
    /// Derived independently of the production accounting so it can bracket it.
    fn min_table_bytes<T>(entries: usize) -> usize {
        entries * (size_of::<T>() + 1)
    }

    #[test]
    fn map_new_does_not_allocate() {
        let map = ArrowBytesViewMap::<()>::new(OutputType::Utf8View);

        assert_eq!(map.map.capacity(), 0);
        assert_eq!(map.map.allocation_size(), 0);
        assert_eq!(map.size(), 0);
    }

    #[test]
    fn test_size_counts_initial_hash_table_capacity() {
        let map = ArrowBytesViewMap::<()>::with_capacity(
            OutputType::Utf8View,
            INITIAL_MAP_CAPACITY,
        );

        assert!(map.map.capacity() >= INITIAL_MAP_CAPACITY);
        assert_eq!(map.size(), map.map.allocation_size());

        // Before this accounting was corrected the map reported exactly
        // `capacity() * size_of::<Entry<V>>()`, which leaves out the control
        // bytes and undercounts the real allocation by roughly half.
        let lower_bound = min_table_bytes::<Entry<()>>(map.map.capacity());
        assert!(
            map.size() >= lower_bound,
            "expected {} to be at least {lower_bound}",
            map.size()
        );
        assert!(
            map.size() <= 2 * lower_bound + 64,
            "expected {} to be within a small factor of {lower_bound}",
            map.size()
        );
        assert!(
            map.size() > map.map.capacity() * size_of::<Entry<()>>(),
            "expected {} to exceed {}",
            map.size(),
            map.map.capacity() * size_of::<Entry<()>>()
        );
    }

    #[test]
    fn take_preserves_the_capacity_the_map_was_built_with() {
        let mut preallocated = ArrowBytesViewMap::<()>::with_capacity(
            OutputType::Utf8View,
            INITIAL_MAP_CAPACITY,
        );
        let capacity = preallocated.map.capacity();
        preallocated.take();
        assert_eq!(preallocated.map.capacity(), capacity);

        let mut lazy = ArrowBytesViewMap::<()>::new(OutputType::Utf8View);
        lazy.take();
        assert_eq!(lazy.map.capacity(), 0);
    }

    #[test]
    fn clear_and_release_frees_the_preallocation_that_take_keeps() {
        let mut map = ArrowBytesViewMap::<()>::with_capacity(
            OutputType::Utf8View,
            INITIAL_MAP_CAPACITY,
        );
        let values: ArrayRef = Arc::new(StringViewArray::from_iter_values(
            (0..1_000).map(|i| format!("distinct value number {i}")),
        ));
        map.insert_if_new(&values, |_| (), |_| ());

        let warm_size = map.map.allocation_size();
        assert!(warm_size > 0);

        // `take` deliberately keeps the map warm, so it does not release the
        // configured capacity.
        map.take();
        let taken_size = map.size();
        assert!(
            taken_size >= min_table_bytes::<Entry<()>>(INITIAL_MAP_CAPACITY),
            "expected take to retain the warm up allocation, got {taken_size}"
        );

        map.clear_and_release();
        assert_eq!(map.map.allocation_size(), 0);
        let released_size = map.size();
        assert!(
            released_size < 128,
            "expected the released map to report approximately zero bytes, got {released_size}"
        );

        // The configured capacity survives, so the map warms back up when it is
        // emitted from again.
        map.take();
        assert!(map.map.capacity() >= INITIAL_MAP_CAPACITY);
    }

    #[test]
    fn test_size_counts_retained_buffer_capacities() {
        let first = "a".repeat(BYTE_VIEW_MAX_BLOCK_SIZE / 2 + 1);
        let second = "b".repeat(BYTE_VIEW_MAX_BLOCK_SIZE / 2 + 1);
        let third = "c".repeat(BYTE_VIEW_MAX_BLOCK_SIZE / 2 + 1);
        let values: ArrayRef = Arc::new(StringViewArray::from(vec![
            first.as_str(),
            second.as_str(),
            third.as_str(),
        ]));

        let mut map = ArrowBytesViewMap::new(OutputType::Utf8View);
        map.insert_if_new(&values, |_| (), |_| {});

        // Make unused vector capacity explicit; the completed buffers were created
        // by the map's flush path.
        map.views.shrink_to_fit();
        map.views.reserve_exact(1);
        map.completed.shrink_to_fit();
        map.completed.reserve_exact(1);

        // The map owns these allocations; `values` and its Arrow buffers remain external.
        assert!(map.views.capacity() > map.views.len());
        assert!(map.completed.capacity() > map.completed.len());
        assert!(
            map.completed
                .iter()
                .any(|buffer| buffer.capacity() > buffer.len())
        );

        let expected_size = map.map.allocation_size()
            + map.views.allocated_size()
            + map.in_progress.allocated_size()
            + map.completed.allocated_size()
            + map.completed.iter().map(Buffer::capacity).sum::<usize>()
            + map.hashes_buffer.allocated_size();
        assert_eq!(map.size(), expected_size);

        // Verify the retained-capacity delta independently from the production formula.
        let legacy_size = map.map.allocation_size()
            + map.views.len() * size_of::<u128>()
            + map.in_progress.capacity()
            + map.completed.iter().map(Buffer::len).sum::<usize>()
            + map.hashes_buffer.allocated_size();
        let retained_capacity_delta = (map.views.capacity() - map.views.len())
            * size_of::<u128>()
            + map.completed.capacity() * size_of::<Buffer>()
            + map
                .completed
                .iter()
                .map(|buffer| buffer.capacity() - buffer.len())
                .sum::<usize>();
        assert_eq!(map.size() - legacy_size, retained_capacity_delta);

        let size_after_insert = map.size();
        map.insert_if_new(&values, |_| (), |_| {});
        assert_eq!(map.size(), size_after_insert);
    }

    #[derive(Debug, PartialEq, Eq, Default, Clone, Copy)]
    struct TestPayload {
        // store the string value to check against input
        index: usize, // store the index of the string (each new string gets the next sequential input)
    }

    /// Wraps an [`ArrowBytesViewMap`], validating its invariants
    struct TestMap {
        map: ArrowBytesViewMap<TestPayload>,
        // stores distinct strings seen, in order
        strings: Vec<Option<String>>,
        // map strings to index in strings
        indexes: HashMap<Option<String>, usize>,
    }

    impl TestMap {
        /// creates a map with TestPayloads for the given strings and then
        /// validates the payloads
        fn new() -> Self {
            Self {
                map: ArrowBytesViewMap::new(OutputType::Utf8View),
                strings: vec![],
                indexes: HashMap::new(),
            }
        }

        /// Inserts strings into the map
        fn insert(&mut self, strings: &[Option<&str>]) {
            let string_array = StringViewArray::from(strings.to_vec());
            let arr: ArrayRef = Arc::new(string_array);

            let mut next_index = self.indexes.len();
            let mut actual_new_strings = vec![];
            let mut actual_seen_indexes = vec![];
            // update self with new values, keeping track of newly added values
            for str in strings {
                let str = str.map(|s| s.to_string());
                let index = self.indexes.get(&str).copied().unwrap_or_else(|| {
                    actual_new_strings.push(str.clone());
                    let index = self.strings.len();
                    self.strings.push(str.clone());
                    self.indexes.insert(str, index);
                    index
                });
                actual_seen_indexes.push(index);
            }

            // insert the values into the map, recording what we did
            let mut seen_new_strings = vec![];
            let mut seen_indexes = vec![];
            self.map.insert_if_new(
                &arr,
                |s| {
                    let value = s
                        .map(|s| String::from_utf8(s.to_vec()).expect("Non utf8 string"));
                    let index = next_index;
                    next_index += 1;
                    seen_new_strings.push(value);
                    TestPayload { index }
                },
                |payload| {
                    seen_indexes.push(payload.index);
                },
            );

            assert_eq!(actual_seen_indexes, seen_indexes);
            assert_eq!(actual_new_strings, seen_new_strings);
        }

        /// Call `self.map.into_array()` validating that the strings are in the same
        /// order as they were inserted
        fn into_array(self) -> ArrayRef {
            let Self {
                map,
                strings,
                indexes: _,
            } = self;

            let arr = map.into_state();
            let expected: ArrayRef = Arc::new(StringViewArray::from(strings));
            assert_eq!(&arr, &expected);
            arr
        }
    }

    #[test]
    fn test_map() {
        let input = vec![
            // Note mix of short/long strings
            Some("A"),
            Some("bcdefghijklmnop1234567"),
            Some("X"),
            Some("Y"),
            None,
            Some("qrstuvqxyzhjwya"),
            Some("✨🔥"),
            Some("🔥"),
            Some("🔥🔥🔥🔥🔥🔥"),
        ];

        let mut test_map = TestMap::new();
        test_map.insert(&input);
        test_map.insert(&input); // put it in twice
        let expected_output: ArrayRef = Arc::new(StringViewArray::from(input));
        assert_eq!(&test_map.into_array(), &expected_output);
    }
}