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
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
// 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

//! [`ArrowBytesMap`] and [`ArrowBytesSet`] for storing maps/sets of values from
//! StringArray / LargeStringArray / BinaryArray / LargeBinaryArray.

use arrow::array::{
    Array, ArrayRef, BufferBuilder, GenericBinaryArray, GenericStringArray,
    NullBufferBuilder, OffsetSizeTrait,
    cast::AsArray,
    types::{ByteArrayType, GenericBinaryType, GenericStringType},
};
use arrow::buffer::{Buffer, NullBuffer, OffsetBuffer, ScalarBuffer};
use arrow::datatypes::DataType;
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::any::type_name;
use std::fmt::Debug;
use std::mem::{size_of, swap};
use std::ops::Range;
use std::sync::Arc;

/// Should the output be a String or Binary?
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputType {
    /// `StringArray` or `LargeStringArray`
    Utf8,
    /// `StringViewArray`
    Utf8View,
    /// `BinaryArray` or `LargeBinaryArray`
    Binary,
    /// `BinaryViewArray`
    BinaryView,
}

/// HashSet optimized for storing string or binary values that can produce that
/// the final set as a GenericStringArray with minimal copies.
#[derive(Debug)]
pub struct ArrowBytesSet<O: OffsetSizeTrait>(ArrowBytesMap<O, ()>);

impl<O: OffsetSizeTrait> ArrowBytesSet<O> {
    /// Creates a set that does not pre-allocate its hash table or value buffer.
    ///
    /// See [`ArrowBytesMap::new`] for when to prefer this over
    /// [`Self::with_capacity`].
    pub fn new(output_type: OutputType) -> Self {
        Self(ArrowBytesMap::new(output_type))
    }

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

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

    /// 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);
    }

    /// Converts this set into a `StringArray`/`LargeStringArray` or
    /// `BinaryArray`/`LargeBinaryArray` 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 "bytes" types (`String`, `LargeString`,
/// `Binary`, and `LargeBinary`) values that can produce the set of keys on
/// output as `GenericBinaryArray` without copies.
///
/// Equivalent to `HashSet<String, V>` but with better performance if you need
/// to emit the keys as an Arrow `StringArray` / `BinaryArray`. For other
/// purposes it is the same as a `HashMap<String, V>`
///
/// # Generic Arguments
///
/// * `O`: OffsetSize (String/LargeString)
/// * `V`: payload type
///
/// # Description
///
/// This is a specialized HashMap with the following properties:
///
/// 1. Optimized for storing and emitting Arrow byte types  (e.g.
///    `StringArray` / `BinaryArray`) 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 [`ArrowBytesSet`].
///
/// 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.
///
/// # Example
///
/// The following diagram shows how the map would store the four strings
/// "Foo", NULL, "Bar", "TheQuickBrownFox":
///
/// * `hashtable` stores entries for each distinct string that has been
///   inserted. The entries contain the payload as well as information about the
///   value (either an offset or the actual bytes, see `Entry` docs for more
///   details)
///
/// * `offsets` stores offsets into `buffer` for each distinct string value,
///   following the same convention as the offsets in a `StringArray` or
///   `LargeStringArray`.
///
/// * `buffer` stores the actual byte data
///
/// * `null`: stores the index and payload of the null value, in this case the
///   second value (index 1)
///
/// ```text
/// ┌───────────────────────────────────┐    ┌─────┐    ┌────┐
/// │                ...                │    │  0  │    │FooB│
/// │ ┌──────────────────────────────┐  │    │  0  │    │arTh│
/// │ │      <Entry for "Bar">       │  │    │  3  │    │eQui│
/// │ │            len: 3            │  │    │  3  │    │ckBr│
/// │ │   offset_or_inline: "Bar"    │  │    │  6  │    │ownF│
/// │ │         payload:...          │  │    │     │    │ox  │
/// │ └──────────────────────────────┘  │    │     │    │    │
/// │                ...                │    └─────┘    └────┘
/// │ ┌──────────────────────────────┐  │
/// │ │<Entry for "TheQuickBrownFox">│  │    offsets    buffer
/// │ │           len: 16            │  │
/// │ │     offset_or_inline: 6      │  │    ┌───────────────┐
/// │ │         payload: ...         │  │    │    Some(1)    │
/// │ └──────────────────────────────┘  │    │ payload: ...  │
/// │                ...                │    └───────────────┘
/// └───────────────────────────────────┘
///                                              null
///               HashTable
/// ```
///
/// # Entry Format
///
/// Entries stored in a [`ArrowBytesMap`] represents a value that is either
/// stored inline or in the buffer
///
/// This helps the case where there are many short (less than 8 bytes) strings
/// that are the same (e.g. "MA", "CA", "NY", "TX", etc)
///
/// ```text
///                                                                ┌──────────────────┐
///                                                  ─ ─ ─ ─ ─ ─ ─▶│...               │
///                                                 │              │TheQuickBrownFox  │
///                                                                │...               │
///                                                 │              │                  │
///                                                                └──────────────────┘
///                                                 │               buffer of u8
///
///                                                 │
///                        ┌────────────────┬───────────────┬───────────────┐
///  Storing               │                │ starting byte │  length, in   │
///  "TheQuickBrownFox"    │   hash value   │   offset in   │  bytes (not   │
///  (long string)         │                │    buffer     │  characters)  │
///                        └────────────────┴───────────────┴───────────────┘
///                              8 bytes          8 bytes       4 or 8
///
///
///                         ┌───────────────┬─┬─┬─┬─┬─┬─┬─┬─┬───────────────┐
/// Storing "foobar"        │               │ │ │ │ │ │ │ │ │  length, in   │
/// (short string)          │  hash value   │?│?│f│o│o│b│a│r│  bytes (not   │
///                         │               │ │ │ │ │ │ │ │ │  characters)  │
///                         └───────────────┴─┴─┴─┴─┴─┴─┴─┴─┴───────────────┘
///                              8 bytes         8 bytes        4 or 8
/// ```
pub struct ArrowBytesMap<O, V>
where
    O: OffsetSizeTrait,
    V: Debug + PartialEq + Eq + Clone + Copy + Default,
{
    /// Should the output be String or Binary?
    output_type: OutputType,
    /// Underlying hash set for each distinct value
    map: hashbrown::hash_table::HashTable<Entry<O, 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,
    /// Value buffer capacity to re-create the buffer with in [`Self::take`],
    /// for the same reason as `initial_map_capacity`
    initial_buffer_capacity: usize,
    /// In progress buffer containing all values
    buffer: Vec<u8>,
    /// Offsets into `buffer` for each distinct  value. These offsets as used
    /// directly to create the final `GenericBinaryArray`. The `i`th string is
    /// stored in the range `offsets[i]..offsets[i+1]` in `buffer`. Null values
    /// are stored as a zero length string.
    offsets: Vec<O>,
    /// 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
/// [`ArrowBytesMap::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 = 128;
/// The size, in bytes, of the string data buffer pre-allocated by
/// [`ArrowBytesMap::with_capacity`]
pub const INITIAL_BUFFER_CAPACITY: usize = 8 * 1024;

/// Appends `value` to a map's value buffer, growing the buffer on a power of
/// two ladder.
///
/// `Vec` doubles from wherever its first allocation landed, so a buffer started
/// empty by [`ArrowBytesMap::new`] and one started at
/// [`INITIAL_BUFFER_CAPACITY`] by [`ArrowBytesMap::with_capacity`] sit on
/// different ladders, and can hold the same values at capacities differing by
/// up to 2x in either direction depending on the value lengths. Rounding every
/// growth up to a power of two puts both on one ladder, which is what makes a
/// lazily allocated map never larger than a pre-allocated one holding the same
/// values. Growth stays geometric, so appending is still amortized constant
/// time.
fn push_value_bytes(buffer: &mut Vec<u8>, value: &[u8]) {
    let required = buffer.len() + value.len();
    if required > buffer.capacity() {
        let target = required.checked_next_power_of_two().unwrap_or(required);
        buffer.reserve_exact(target - buffer.len());
    }
    buffer.extend_from_slice(value);
}

impl<O: OffsetSizeTrait, V> ArrowBytesMap<O, V>
where
    V: Debug + PartialEq + Eq + Clone + Copy + Default,
{
    /// Creates a map that does not pre-allocate its hash table or value buffer.
    ///
    /// 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::new_inner(output_type, 0, 0)
    }

    /// Creates a map whose hash table is pre-allocated for `map_capacity`
    /// entries and whose value buffer is pre-allocated with
    /// [`INITIAL_BUFFER_CAPACITY`] bytes.
    ///
    /// 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 capacities are preserved across [`Self::take`].
    pub fn with_capacity(output_type: OutputType, map_capacity: usize) -> Self {
        Self::new_inner(output_type, map_capacity, INITIAL_BUFFER_CAPACITY)
    }

    fn new_inner(
        output_type: OutputType,
        map_capacity: usize,
        buffer_capacity: usize,
    ) -> Self {
        Self {
            output_type,
            map: hashbrown::hash_table::HashTable::with_capacity(map_capacity),
            initial_map_capacity: map_capacity,
            initial_buffer_capacity: buffer_capacity,
            buffer: Vec::with_capacity(buffer_capacity),
            offsets: vec![O::default()], // first offset is always 0
            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::new_inner(
            self.output_type,
            self.initial_map_capacity,
            self.initial_buffer_capacity,
        );
        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
    /// capacities 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 capacities are remembered, so the next [`Self::take`]
    /// warms the map up again.
    pub fn clear_and_release(&mut self) {
        let mut released = Self::new_inner(self.output_type, 0, 0);
        released.initial_map_capacity = self.initial_map_capacity;
        released.initial_buffer_capacity = self.initial_buffer_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 array type
        match self.output_type {
            OutputType::Binary => {
                assert!(matches!(
                    values.data_type(),
                    DataType::Binary | DataType::LargeBinary
                ));
                self.insert_if_new_inner::<MP, OP, GenericBinaryType<O>>(
                    values,
                    make_payload_fn,
                    observe_payload_fn,
                )
            }
            OutputType::Utf8 => {
                assert!(matches!(
                    values.data_type(),
                    DataType::Utf8 | DataType::LargeUtf8
                ));
                self.insert_if_new_inner::<MP, OP, GenericStringType<O>>(
                    values,
                    make_payload_fn,
                    observe_payload_fn,
                )
            }
            _ => unreachable!("View types should use `ArrowBytesViewMap`"),
        }
    }

    /// Generic version of [`Self::insert_if_new`] that handles `ByteArrayType`
    /// (both String and Binary)
    ///
    /// Note this is the only function that is generic on [`ByteArrayType`], 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: ByteArrayType,
    {
        // 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_bytes::<B>();

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

        for (value, &hash) in values.iter().zip(batch_hashes.iter()) {
            // handle null value
            let Some(value) = value else {
                let payload = if let Some(&(payload, _offset)) = self.null.as_ref() {
                    payload
                } else {
                    let payload = make_payload_fn(None);
                    let null_index = self.offsets.len() - 1;
                    // nulls need a zero length in the offset buffer
                    let offset = self.buffer.len();
                    self.offsets.push(O::usize_as(offset));
                    self.null = Some((payload, null_index));
                    payload
                };
                observe_payload_fn(payload);
                continue;
            };

            // get the value as bytes
            let value: &[u8] = value.as_ref();
            let value_len = O::usize_as(value.len());

            // value is "small"
            let payload = if value.len() <= SHORT_VALUE_LEN {
                let inline = value.iter().fold(0usize, |acc, &x| (acc << 8) | x as usize);

                // is value is already present in the set?
                let entry = self.map.find_mut(hash, |header| {
                    // compare value if hashes match
                    if header.hash != hash || header.len != value_len {
                        return false;
                    }
                    // value is stored inline so no need to consult buffer
                    // (this is the "small string optimization")
                    inline == header.offset_or_inline
                });

                if let Some(entry) = entry {
                    entry.payload
                }
                // if no existing entry, make a new one
                else {
                    // Put the small values into buffer and offsets so it appears
                    // the output array, but store the actual bytes inline for
                    // comparison
                    push_value_bytes(&mut self.buffer, value);
                    self.offsets.push(O::usize_as(self.buffer.len()));
                    let payload = make_payload_fn(Some(value));
                    let new_header = Entry {
                        hash,
                        len: value_len,
                        offset_or_inline: inline,
                        payload,
                    };
                    self.map
                        .insert_unique(hash, new_header, |header| header.hash);
                    payload
                }
            }
            // value is not "small"
            else {
                // Check if the value is already present in the set
                let entry = self.map.find_mut(hash, |header| {
                    // Without the length test, a short entry colliding on
                    // `hash` builds `range()` from its inlined bytes and
                    // reads past the buffer: memory safety, not just a
                    // wasted comparison.
                    if header.hash != hash || header.len != value_len {
                        return false;
                    }
                    // SAFETY: a long entry, so `offset_or_inline` indexes the
                    // append-only `buffer`, written before the insert.
                    let existing_value =
                        unsafe { self.buffer.get_unchecked(header.range()) };
                    value == existing_value
                });

                if let Some(entry) = entry {
                    entry.payload
                }
                // if no existing entry, make a new one
                else {
                    // Put the small values into buffer and offsets so it
                    // appears the output array, and store that offset
                    // so the bytes can be compared if needed
                    let offset = self.buffer.len(); // offset of start for data
                    push_value_bytes(&mut self.buffer, value);
                    self.offsets.push(O::usize_as(self.buffer.len()));

                    let payload = make_payload_fn(Some(value));
                    let new_header = Entry {
                        hash,
                        len: value_len,
                        offset_or_inline: offset,
                        payload,
                    };
                    self.map
                        .insert_unique(hash, new_header, |header| header.hash);
                    payload
                }
            };
            observe_payload_fn(payload);
        }
        // Check for overflow in offsets (if more data was sent than can be represented)
        assert!(
            O::from_usize(self.buffer.len()).is_some(),
            "Put {} bytes in buffer, more than can be represented by a {}",
            self.buffer.len(),
            type_name::<O>()
        )
    }

    /// Converts this set into a `StringArray`, `LargeStringArray`,
    /// `BinaryArray`, or `LargeBinaryArray` 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(self) -> ArrayRef {
        let Self {
            output_type,
            map: _,
            initial_map_capacity: _,
            initial_buffer_capacity: _,
            offsets,
            buffer,
            random_state: _,
            hashes_buffer: _,
            null,
        } = self;

        // Only make a `NullBuffer` if there was a null value
        let nulls = null.map(|(_payload, null_index)| {
            let num_values = offsets.len() - 1;
            single_null_buffer(num_values, null_index)
        });
        // SAFETY: the offsets were constructed correctly in `insert_if_new` --
        // monotonically increasing, overflows were checked.
        let offsets = unsafe { OffsetBuffer::new_unchecked(ScalarBuffer::from(offsets)) };
        let values = Buffer::from_vec(buffer);

        match output_type {
            OutputType::Binary => {
                // SAFETY: the offsets were constructed correctly
                Arc::new(unsafe {
                    GenericBinaryArray::new_unchecked(offsets, values, nulls)
                })
            }
            OutputType::Utf8 => {
                // SAFETY:
                // 1. the offsets were constructed safely
                //
                // 2. we asserted the input arrays were all the correct type and
                // thus since all the values that went in were valid (e.g. utf8)
                // so are all the values that come out
                Arc::new(unsafe {
                    GenericStringArray::new_unchecked(offsets, values, nulls)
                })
            }
            _ => unreachable!("View types should use `ArrowBytesViewMap`"),
        }
    }

    /// 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 mut output_offsets = Vec::with_capacity(indices.size_hint().0 + 1);
        let mut output_values = BufferBuilder::<u8>::new(0);
        let mut output_nulls = NullBufferBuilder::new(indices.size_hint().0);
        output_offsets.push(O::default());
        let null_index = self.null.map(|(_, index)| index);
        let num_keys = self.offsets.len() - 1;

        for index in indices {
            if index >= num_keys {
                return exec_err!(
                    "Key index {index} is out of bounds for {num_keys} keys"
                );
            }
            let start = self.offsets[index].as_usize();
            let end = self.offsets[index + 1].as_usize();
            output_values.append_slice(&self.buffer.as_slice()[start..end]);
            if O::from_usize(output_values.len()).is_none() {
                return exec_err!("Offset overflow while copying byte map keys");
            }
            output_offsets.push(O::usize_as(output_values.len()));
            output_nulls.append(index != null_index.unwrap_or(usize::MAX));
        }

        // SAFETY: offsets are constructed from the length of `output_values`.
        let offsets =
            unsafe { OffsetBuffer::new_unchecked(ScalarBuffer::from(output_offsets)) };
        let values = output_values.finish();
        let nulls = output_nulls.finish();
        Ok(match self.output_type {
            OutputType::Binary => Arc::new(unsafe {
                GenericBinaryArray::new_unchecked(offsets, values, nulls)
            }),
            OutputType::Utf8 => Arc::new(unsafe {
                GenericStringArray::new_unchecked(offsets, values, nulls)
            }),
            _ => unreachable!("View types should use `ArrowBytesViewMap`"),
        })
    }

    /// 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`
    pub fn size(&self) -> usize {
        // `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<O, V>>()`.
        // It is a constant time layout calculation, not a walk of the table.
        self.map.allocation_size()
            + self.buffer.capacity() * size_of::<u8>()
            + self.offsets.allocated_size()
            + self.hashes_buffer.allocated_size()
    }
}

/// Returns a `NullBuffer` with a single null value at the given index
pub(crate) fn single_null_buffer(num_values: usize, null_index: usize) -> NullBuffer {
    let mut null_builder = NullBufferBuilder::new(num_values);
    null_builder.append_n_non_nulls(null_index);
    null_builder.append_null();
    null_builder.append_n_non_nulls(num_values - null_index - 1);
    // SAFETY: inner builder must be constructed
    null_builder.finish().unwrap()
}

impl<O: OffsetSizeTrait, V> Debug for ArrowBytesMap<O, 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("buffer", &self.buffer)
            .field("random_state", &self.random_state)
            .field("hashes_buffer", &self.hashes_buffer)
            .finish()
    }
}

/// Maximum size of a value that can be inlined in the hash table
const SHORT_VALUE_LEN: usize = size_of::<usize>();

/// Entry in the hash table -- see [`ArrowBytesMap`] for more details
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
struct Entry<O, V>
where
    O: OffsetSizeTrait,
    V: Debug + PartialEq + Eq + Clone + Copy + Default,
{
    /// hash of the value (stored to avoid recomputing it in hash table check)
    hash: u64,
    /// if len =< [`SHORT_VALUE_LEN`]: the data inlined
    /// if len > [`SHORT_VALUE_LEN`], the offset of where the data starts
    offset_or_inline: usize,
    /// length of the value, in bytes (use O here so we use only i32 for
    /// strings, rather 64 bit usize)
    len: O,
    /// value stored by the entry
    payload: V,
}

impl<O, V> Entry<O, V>
where
    O: OffsetSizeTrait,
    V: Debug + PartialEq + Eq + Clone + Copy + Default,
{
    /// returns self.offset..self.offset + self.len
    #[inline(always)]
    fn range(&self) -> Range<usize> {
        self.offset_or_inline..self.offset_or_inline + self.len.as_usize()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use arrow::array::{BinaryArray, LargeBinaryArray, StringArray};
    use std::collections::HashMap;

    /// 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 = ArrowBytesMap::<i32, ()>::new(OutputType::Utf8);

        assert_eq!(map.map.capacity(), 0);
        assert_eq!(map.map.allocation_size(), 0);
        assert_eq!(map.buffer.capacity(), 0);
        // Only the single leading zero offset is allocated.
        assert!(map.size() < 128, "expected {} to be tiny", map.size());
    }

    #[test]
    fn map_with_capacity_reports_the_real_hash_table_allocation() {
        let map = ArrowBytesMap::<i32, ()>::with_capacity(
            OutputType::Utf8,
            INITIAL_MAP_CAPACITY,
        );

        assert!(map.map.capacity() >= INITIAL_MAP_CAPACITY);
        assert_eq!(map.buffer.capacity(), INITIAL_BUFFER_CAPACITY);

        // Before this accounting was corrected the map reported its hash table
        // as costing zero bytes until the table grew past its pre-allocation.
        let table_bytes = map.map.allocation_size();
        let lower_bound = min_table_bytes::<Entry<i32, ()>>(map.map.capacity());
        assert!(
            table_bytes >= lower_bound,
            "expected {table_bytes} to be at least {lower_bound}"
        );
        assert!(
            table_bytes <= 2 * lower_bound + 64,
            "expected {table_bytes} to be within a small factor of {lower_bound}"
        );
        assert!(map.size() >= table_bytes + INITIAL_BUFFER_CAPACITY);
    }

    #[test]
    fn take_preserves_the_capacity_the_map_was_built_with() {
        let mut preallocated = ArrowBytesMap::<i32, ()>::with_capacity(
            OutputType::Utf8,
            INITIAL_MAP_CAPACITY,
        );
        let capacity = preallocated.map.capacity();
        preallocated.take();
        assert_eq!(preallocated.map.capacity(), capacity);
        assert_eq!(preallocated.buffer.capacity(), INITIAL_BUFFER_CAPACITY);

        let mut lazy = ArrowBytesMap::<i32, ()>::new(OutputType::Utf8);
        lazy.take();
        assert_eq!(lazy.map.capacity(), 0);
        assert_eq!(lazy.buffer.capacity(), 0);
    }

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

        let populated_size = map.size();
        assert!(populated_size > INITIAL_BUFFER_CAPACITY);

        // `take` deliberately keeps the map warm, so it does not release the
        // configured capacities.
        map.take();
        let taken_size = map.size();
        assert!(
            taken_size > INITIAL_BUFFER_CAPACITY,
            "expected take to retain the warm up allocations, got {taken_size}"
        );

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

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

    #[test]
    fn push_value_bytes_ignores_an_empty_value() {
        let mut buffer = Vec::new();
        push_value_bytes(&mut buffer, b"");
        assert_eq!(buffer.capacity(), 0);
        assert!(buffer.is_empty());

        push_value_bytes(&mut buffer, b"abcd");
        let capacity = buffer.capacity();
        push_value_bytes(&mut buffer, b"");
        assert_eq!(buffer, b"abcd");
        assert_eq!(buffer.capacity(), capacity);
    }

    #[test]
    fn push_value_bytes_grows_only_past_a_power_of_two() {
        let mut buffer = Vec::new();

        // A first append that is not itself a power of two still lands on the
        // ladder: a plain `Vec` would have stopped at a capacity of 9.
        push_value_bytes(&mut buffer, &[1u8; 9]);
        assert_eq!(buffer.len(), 9);
        assert_eq!(buffer.capacity(), 16);

        // Filling exactly to the capacity does not grow it.
        push_value_bytes(&mut buffer, &[2u8; 7]);
        assert_eq!(buffer.len(), 16);
        assert_eq!(buffer.capacity(), 16);

        // The next byte moves up one rung.
        push_value_bytes(&mut buffer, &[3u8; 1]);
        assert_eq!(buffer.len(), 17);
        assert_eq!(buffer.capacity(), 32);

        // So does an append that overshoots several rungs at once.
        push_value_bytes(&mut buffer, &[4u8; 100]);
        assert_eq!(buffer.len(), 117);
        assert_eq!(buffer.capacity(), 128);

        let mut expected = vec![1u8; 9];
        expected.extend_from_slice(&[2u8; 7]);
        expected.extend_from_slice(&[3u8; 1]);
        expected.extend_from_slice(&[4u8; 100]);
        assert_eq!(buffer, expected);
    }

    #[test]
    fn push_value_bytes_does_not_grow_a_buffer_with_room() {
        let mut buffer = Vec::with_capacity(INITIAL_BUFFER_CAPACITY);
        let start = buffer.as_ptr();

        let value = vec![7u8; 512];
        for _ in 0..16 {
            push_value_bytes(&mut buffer, &value);
        }

        assert_eq!(buffer.len(), INITIAL_BUFFER_CAPACITY);
        assert_eq!(buffer.capacity(), INITIAL_BUFFER_CAPACITY);
        assert!(
            std::ptr::eq(buffer.as_ptr(), start),
            "buffer was reallocated"
        );
        assert!(buffer.iter().all(|&byte| byte == 7));
    }

    #[test]
    fn push_value_bytes_rounds_a_single_oversized_append_up_to_a_power_of_two() {
        let value = vec![9u8; INITIAL_BUFFER_CAPACITY + 1];
        let rounded = (INITIAL_BUFFER_CAPACITY + 1).next_power_of_two();

        // A value larger than the pre-allocation lands on the same rung
        // whether the buffer started empty or pre-allocated, which is what
        // keeps a lazily allocated map from outgrowing a pre-allocated one.
        let mut lazy = Vec::new();
        push_value_bytes(&mut lazy, &value);
        assert_eq!(lazy.len(), value.len());
        assert_eq!(lazy.capacity(), rounded);
        assert_eq!(lazy, value);

        let mut pre_allocated = Vec::with_capacity(INITIAL_BUFFER_CAPACITY);
        push_value_bytes(&mut pre_allocated, &value);
        assert_eq!(pre_allocated.capacity(), rounded);
        assert_eq!(pre_allocated, value);
    }

    #[test]
    fn lazy_and_pre_allocated_buffers_grow_on_the_same_ladder() {
        // Value lengths chosen so the buffer requirement lands between powers
        // of two, which is where the two ladders used to diverge.
        for value_len in [9usize, 13, 24, 37] {
            let mut lazy = ArrowBytesMap::<i32, ()>::new(OutputType::Utf8);
            let mut pre_allocated = ArrowBytesMap::<i32, ()>::with_capacity(
                OutputType::Utf8,
                INITIAL_MAP_CAPACITY,
            );

            for batch in 0..8 {
                let values: ArrayRef =
                    Arc::new(StringArray::from_iter_values((0..1_000).map(|i| {
                        let value = format!("{}:{i}", batch * 1_000 + i);
                        format!("{value:value_len$}")
                    })));
                lazy.insert_if_new(&values, |_| (), |_| ());
                pre_allocated.insert_if_new(&values, |_| (), |_| ());

                assert_eq!(lazy.buffer.len(), pre_allocated.buffer.len());
                assert_eq!(
                    lazy.buffer.capacity(),
                    pre_allocated.buffer.capacity(),
                    "value length {value_len}, batch {batch}: a buffer that \
                     started empty reached {} bytes of capacity against {} for \
                     one that started at INITIAL_BUFFER_CAPACITY",
                    lazy.buffer.capacity(),
                    pre_allocated.buffer.capacity(),
                );
            }
        }
    }

    #[test]
    fn a_lazy_buffer_stays_below_the_pre_allocated_floor_while_it_is_small() {
        let mut lazy = ArrowBytesMap::<i32, ()>::new(OutputType::Utf8);
        let values: ArrayRef = Arc::new(StringArray::from_iter_values(
            (0..10).map(|i| format!("distinct value number {i}")),
        ));
        lazy.insert_if_new(&values, |_| (), |_| ());

        assert!(
            lazy.buffer.capacity() < INITIAL_BUFFER_CAPACITY,
            "expected a small lazy buffer to stay under the {INITIAL_BUFFER_CAPACITY} \
             byte pre-allocation, got {}",
            lazy.buffer.capacity()
        );
    }

    #[test]
    fn string_set_empty() {
        let mut set = ArrowBytesSet::<i32>::new(OutputType::Utf8);
        let array: ArrayRef = Arc::new(StringArray::new_null(0));
        set.insert(&array);
        assert_eq!(set.len(), 0);
        assert_eq!(set.non_null_len(), 0);
        assert_set(set, &[]);
    }

    #[test]
    fn string_set_one_null() {
        let mut set = ArrowBytesSet::<i32>::new(OutputType::Utf8);
        let array: ArrayRef = Arc::new(StringArray::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_set_many_null() {
        let mut set = ArrowBytesSet::<i32>::new(OutputType::Utf8);
        let array: ArrayRef = Arc::new(StringArray::new_null(11));
        set.insert(&array);
        assert_eq!(set.len(), 1);
        assert_eq!(set.non_null_len(), 0);
        assert_set(set, &[None]);
    }

    #[test]
    fn string_set_basic_i32() {
        test_string_set_basic::<i32>();
    }

    #[test]
    fn string_set_basic_i64() {
        test_string_set_basic::<i64>();
    }

    fn test_string_set_basic<O: OffsetSizeTrait>() {
        // basic test for mixed small and large string values
        let values = GenericStringArray::<O>::from(vec![
            Some("a"),
            Some("b"),
            Some("CXCCCCCCCC"), // 10 bytes
            Some(""),
            Some("cbcxx"), // 5 bytes
            None,
            Some("AAAAAAAA"),  // 8 bytes
            Some("BBBBBQBBB"), // 9 bytes
            Some("a"),
            Some("cbcxx"),
            Some("b"),
            Some("cbcxx"),
            Some(""),
            None,
            Some("BBBBBQBBB"),
            Some("BBBBBQBBB"),
            Some("AAAAAAAA"),
            Some("CXCCCCCCCC"),
        ]);

        let mut set = ArrowBytesSet::<O>::new(OutputType::Utf8);
        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("CXCCCCCCCC"),
                Some(""),
                Some("cbcxx"),
                None,
                Some("AAAAAAAA"),
                Some("BBBBBQBBB"),
            ],
        );
    }

    #[test]
    fn string_set_non_utf8_32() {
        test_string_set_non_utf8::<i32>();
    }

    #[test]
    fn string_set_non_utf8_64() {
        test_string_set_non_utf8::<i64>();
    }

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

        let mut set = ArrowBytesSet::<O>::new(OutputType::Utf8);
        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"),
            ],
        );
    }

    /// A short value and a long value whose hashes collide must not be confused,
    /// whichever of them is inserted first.
    ///
    /// A short value keeps its bytes inlined in the entry's `offset_or_inline`
    /// field, while a long one keeps an offset into the value buffer there. An
    /// entry is only examined when its hash matches, so the length has to be
    /// compared before that field is interpreted at all. Each direction fails
    /// differently without that check, and each case below is chosen to make it
    /// actually fail rather than get away with it:
    ///
    /// * long value looked up against a short entry: `header.range()` is built
    ///   out of the inlined bytes, so `"ab"` (0x6162) sends the read tens of
    ///   kilobytes past the end of the buffer;
    /// * short value looked up against a long entry: the inlined bytes are
    ///   compared against that entry's offset, so a single NUL byte (inlined as
    ///   0) matches the long value stored at offset 0 and the two distinct
    ///   values collapse into one.
    ///
    /// `force_hash_collisions` makes every value collide, which is the only way
    /// to reach either path deterministically.
    #[cfg(feature = "force_hash_collisions")]
    #[test]
    fn short_and_long_values_with_colliding_hashes() {
        let long = "a value too long to be inlined";
        assert!(long.len() > SHORT_VALUE_LEN);

        for [first, second] in [[long, "\0"], ["ab", long]] {
            assert!(first.len() <= SHORT_VALUE_LEN || second.len() <= SHORT_VALUE_LEN);
            // The second value is the one looked up against an entry of the
            // other kind; the repeats must match their own entry.
            let values: ArrayRef = Arc::new(StringArray::from(vec![
                Some(first),
                Some(second),
                Some(first),
                Some(second),
            ]));

            let mut map = ArrowBytesMap::<i32, usize>::new(OutputType::Utf8);
            let mut inserted = vec![];
            let mut payloads = 0;
            map.insert_if_new(
                &values,
                |value| {
                    inserted.push(value.expect("no nulls in this test").to_vec());
                    payloads += 1;
                    payloads
                },
                |_| {},
            );

            assert_eq!(
                inserted,
                vec![first.as_bytes().to_vec(), second.as_bytes().to_vec()],
                "inserting {first:?} then {second:?}"
            );
        }
    }

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

    // Test use of binary output type
    #[test]
    fn test_binary_set() {
        let values: ArrayRef = Arc::new(BinaryArray::from_opt_vec(vec![
            Some(b"a"),
            Some(b"CXCCCCCCCC"),
            None,
            Some(b"CXCCCCCCCC"),
        ]));

        let expected: ArrayRef = Arc::new(BinaryArray::from_opt_vec(vec![
            Some(b"a"),
            Some(b"CXCCCCCCCC"),
            None,
        ]));

        let mut set = ArrowBytesSet::<i32>::new(OutputType::Binary);
        set.insert(&values);
        assert_eq!(&set.into_state(), &expected);
    }

    // Test use of binary output type
    #[test]
    fn test_large_binary_set() {
        let values: ArrayRef = Arc::new(LargeBinaryArray::from_opt_vec(vec![
            Some(b"a"),
            Some(b"CXCCCCCCCC"),
            None,
            Some(b"CXCCCCCCCC"),
        ]));

        let expected: ArrayRef = Arc::new(LargeBinaryArray::from_opt_vec(vec![
            Some(b"a"),
            Some(b"CXCCCCCCCC"),
            None,
        ]));

        let mut set = ArrowBytesSet::<i64>::new(OutputType::Binary);
        set.insert(&values);
        assert_eq!(&set.into_state(), &expected);
    }

    #[test]
    #[should_panic(
        expected = "matches!(values.data_type(), DataType::Utf8 | DataType::LargeUtf8)"
    )]
    fn test_mismatched_types() {
        // inserting binary into a set that expects strings should panic
        let values: ArrayRef = Arc::new(LargeBinaryArray::from_opt_vec(vec![Some(b"a")]));

        let mut set = ArrowBytesSet::<i64>::new(OutputType::Utf8);
        set.insert(&values);
    }

    #[test]
    #[should_panic(expected = "byte array")]
    fn test_mismatched_sizes() {
        // inserting large strings into a set that expects small should panic
        let values: ArrayRef = Arc::new(LargeBinaryArray::from_opt_vec(vec![Some(b"a")]));

        let mut set = ArrowBytesSet::<i32>::new(OutputType::Binary);
        set.insert(&values);
    }

    // put more than 2GB in a string set and expect it to panic
    #[test]
    #[should_panic(
        expected = "Put 2147483648 bytes in buffer, more than can be represented by a i32"
    )]
    fn test_string_overflow() {
        let mut set = ArrowBytesSet::<i32>::new(OutputType::Utf8);
        for value in ["a", "b", "c"] {
            // 1GB strings, so 3rd is over 2GB and should panic
            let arr: ArrayRef =
                Arc::new(StringArray::from_iter_values([value.repeat(1 << 30)]));
            set.insert(&arr);
        }
    }

    // inserting strings into the set does not increase reported memory
    #[test]
    fn test_string_set_memory_usage() {
        let strings1 = GenericStringArray::<i32>::from(vec![
            Some("a"),
            Some("b"),
            Some("CXCCCCCCCC"), // 10 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(GenericStringArray::<i32>::from(strings1));

        // Much larger strings in strings2
        let strings2 = GenericStringArray::<i32>::from(vec![
            "FOO".repeat(1000),
            "BAR".repeat(2000),
            "BAZ".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(GenericStringArray::<i32>::from(strings2));

        let mut set = ArrowBytesSet::<i32>::new(OutputType::Utf8);
        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);

        // 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!(size_after_values2 > total_strings1_len + total_strings2_len);
    }

    #[test]
    fn test_map() {
        let input = vec![
            // Note mix of short/long strings
            Some("A"),
            Some("bcdefghijklmnop"),
            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(StringArray::from(input));
        assert_eq!(&test_map.into_array(), &expected_output);
    }

    #[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 [`ArrowBytesMap`], validating its invariants
    struct TestMap {
        map: ArrowBytesMap<i32, TestPayload>,
        // stores distinct strings seen, in order
        strings: Vec<Option<String>>,
        // map strings to index in strings
        indexes: HashMap<Option<String>, usize>,
    }

    impl Debug for TestMap {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.debug_struct("TestMap")
                .field("map", &"...")
                .field("strings", &self.strings)
                .field("indexes", &self.indexes)
                .finish()
        }
    }

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

        /// Inserts strings into the map
        fn insert(&mut self, strings: &[Option<&str>]) {
            let string_array = StringArray::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(StringArray::from(strings));
            assert_eq!(&arr, &expected);
            arr
        }
    }
}