arrow-select 60.2.0

Selection kernels for arrow arrays
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
// 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

//! [`merge`] and [`merge_n`]: Combine values from two or more arrays

use crate::filter::{SlicesIterator, prep_null_mask_filter};
use crate::zip::zip;
use arrow_array::{
    Array, ArrayRef, BooleanArray, Datum, make_array, new_empty_array, new_null_array,
};
use arrow_data::ArrayData;
use arrow_data::transform::MutableArrayData;
use arrow_schema::ArrowError;

/// An index for the [merge_n] function.
///
/// This trait allows the indices argument for [merge_n] to be stored using a more
/// compact representation than `usize` when the input arrays are small.
/// If the number of input arrays is less than 256 for instance, the indices can be stored as `u8`.
///
/// Implementation must ensure that all values which return `None` from [MergeIndex::index] are
/// considered equal by the [PartialEq] and [Eq] implementations.
pub trait MergeIndex: PartialEq + Eq + Copy {
    /// Returns the index value as an `Option<usize>`.
    ///
    /// `None` values returned by this function indicate holes in the index array and will result
    /// in null values in the array created by [merge].
    fn index(&self) -> Option<usize>;
}

impl MergeIndex for usize {
    fn index(&self) -> Option<usize> {
        Some(*self)
    }
}

impl MergeIndex for Option<usize> {
    fn index(&self) -> Option<usize> {
        *self
    }
}

/// Merges elements by index from a list of [`Array`], creating a new [`Array`] from
/// those values.
///
/// Each element in `indices` is the index of an array in `values`. The `indices` array is processed
/// sequentially. The first occurrence of index value `n` will be mapped to the first
/// value of the array at index `n`. The second occurrence to the second value, and so on.
/// An index value where `MergeIndex::index` returns `None` is interpreted as a null value.
///
/// # Implementation notes
///
/// This algorithm is similar in nature to both [zip] and
/// [interleave](crate::interleave::interleave), but there are some important differences.
///
/// In contrast to [zip], this function supports multiple input arrays. Instead of
/// a boolean selection vector, an index array is to take values from the input arrays, and a special
/// marker values can be used to indicate null values.
///
/// In contrast to [interleave](crate::interleave::interleave), this function does not use pairs of
/// indices. The values in `indices` serve the same purpose as the first value in the pairs passed
/// to `interleave`.
/// The index in the array is implicit and is derived from the number of times a particular array
/// index occurs.
/// The more constrained indexing mechanism used by this algorithm makes it easier to copy values
/// in contiguous slices. In the example below, the two subsequent elements from array `2` can be
/// copied in a single operation from the source array instead of copying them one by one.
/// Long spans of null values are also especially cheap because they do not need to be represented
/// in an input array.
///
/// # Panics
///
/// This function does not check that the number of occurrences of any particular array index matches
/// the length of the corresponding input array. If an array contains more values than required, the
/// spurious values will be ignored. If an array contains fewer values than necessary, this function
/// will panic.
///
/// # Example
///
/// ```text
/// ┌───────────┐  ┌─────────┐                             ┌─────────┐
/// │┌─────────┐│  │   None  │                             │   NULL  │
/// ││    A    ││  ├─────────┤                             ├─────────┤
/// │└─────────┘│  │    1    │                             │    B    │
/// │┌─────────┐│  ├─────────┤                             ├─────────┤
/// ││    B    ││  │    0    │    merge(values, indices)   │    A    │
/// │└─────────┘│  ├─────────┤  ─────────────────────────▶ ├─────────┤
/// │┌─────────┐│  │   None  │                             │   NULL  │
/// ││    C    ││  ├─────────┤                             ├─────────┤
/// │├─────────┤│  │    2    │                             │    C    │
/// ││    D    ││  ├─────────┤                             ├─────────┤
/// │└─────────┘│  │    2    │                             │    D    │
/// └───────────┘  └─────────┘                             └─────────┘
///    values        indices                                  result
///
/// ```
pub fn merge_n(values: &[&dyn Array], indices: &[impl MergeIndex]) -> Result<ArrayRef, ArrowError> {
    if values.is_empty() {
        return Err(ArrowError::InvalidArgumentError(
            "merge_n requires at least one value array".to_string(),
        ));
    }

    let data_type = values[0].data_type();

    for array in values.iter().skip(1) {
        if array.data_type() != data_type {
            return Err(ArrowError::InvalidArgumentError(format!(
                "It is not possible to merge arrays of different data types ({} and {})",
                data_type,
                array.data_type()
            )));
        }
    }

    if indices.is_empty() {
        return Ok(new_empty_array(data_type));
    }

    #[cfg(debug_assertions)]
    for ix in indices {
        if let Some(index) = ix.index() {
            assert!(
                index < values.len(),
                "Index out of bounds: {} >= {}",
                index,
                values.len()
            );
        }
    }

    let data: Vec<ArrayData> = values.iter().map(|a| a.to_data()).collect();
    let data_refs = data.iter().collect();

    let mut mutable = match MutableArrayData::try_new(data_refs, true, indices.len()) {
        Ok(mutable) => mutable,
        // `MutableArrayData` concatenates the dictionaries, which can overflow
        // the key type even when their merged values fit, so let `interleave`
        // merge them instead
        Err(ArrowError::DictionaryKeyOverflowError) => {
            return merge_n_with_interleave(values, indices);
        }
        Err(e) => return Err(e),
    };

    // This loop extends the mutable array by taking slices from the partial results.
    //
    // take_offsets keeps track of how many values have been taken from each array.
    let mut take_offsets = vec![0; values.len() + 1];
    let mut start_row_ix = 0;
    loop {
        let array_ix = indices[start_row_ix];

        // Determine the length of the slice to take.
        let mut end_row_ix = start_row_ix + 1;
        while end_row_ix < indices.len() && indices[end_row_ix] == array_ix {
            end_row_ix += 1;
        }
        let slice_length = end_row_ix - start_row_ix;

        // Extend mutable with either nulls or with values from the array.
        match array_ix.index() {
            None => mutable.try_extend_nulls(slice_length)?,
            Some(index) => {
                let start_offset = take_offsets[index];
                let end_offset = start_offset + slice_length;
                mutable.try_extend(index, start_offset, end_offset)?;
                take_offsets[index] = end_offset;
            }
        }

        if end_row_ix == indices.len() {
            break;
        }
        // Set the start_row_ix for the next slice.
        start_row_ix = end_row_ix;
    }

    Ok(make_array(mutable.freeze()))
}

/// [merge_n] through [interleave](crate::interleave::interleave), which merges
/// dictionaries instead of concatenating them
fn merge_n_with_interleave(
    values: &[&dyn Array],
    indices: &[impl MergeIndex],
) -> Result<ArrayRef, ArrowError> {
    // `interleave` has no null index, so null rows read from an extra
    // single null array
    let nulls = new_null_array(values[0].data_type(), 1);
    let mut arrays = values.to_vec();
    arrays.push(nulls.as_ref());

    let mut take_offsets = vec![0; values.len()];
    let interleave_indices: Vec<_> = indices
        .iter()
        .map(|ix| match ix.index() {
            None => (values.len(), 0),
            Some(index) => {
                let offset = take_offsets[index];
                take_offsets[index] += 1;
                (index, offset)
            }
        })
        .collect();
    crate::interleave::interleave(&arrays, &interleave_indices)
}

/// [merge] through [interleave](crate::interleave::interleave), which merges
/// dictionaries instead of concatenating them
fn merge_with_interleave(
    mask: &BooleanArray,
    truthy: &dyn Array,
    truthy_is_scalar: bool,
    falsy: &dyn Array,
    falsy_is_scalar: bool,
) -> Result<ArrayRef, ArrowError> {
    let mut truthy_offset = 0;
    let mut falsy_offset = 0;
    let indices: Vec<_> = (0..mask.len())
        .map(|idx| {
            // Nulls in the mask are treated as false
            if mask.is_valid(idx) && mask.value(idx) {
                let offset = if truthy_is_scalar { 0 } else { truthy_offset };
                truthy_offset += 1;
                (0, offset)
            } else {
                let offset = if falsy_is_scalar { 0 } else { falsy_offset };
                falsy_offset += 1;
                (1, offset)
            }
        })
        .collect();
    crate::interleave::interleave(&[truthy, falsy], &indices)
}

/// Merges two arrays in the order specified by a boolean mask.
///
/// This algorithm is a variant of [zip] that does not require the truthy and
/// falsy arrays to have the same length.
///
/// When truthy of falsy are [Scalar](arrow_array::Scalar), the single
/// scalar value is repeated whenever the mask array contains true or false respectively.
///
/// # Example
///
/// ```text
///  truthy
/// ┌─────────┐  mask
/// │    A    │  ┌─────────┐                             ┌─────────┐
/// ├─────────┤  │  true   │                             │    A    │
/// │    C    │  ├─────────┤                             ├─────────┤
/// ├─────────┤  │  true   │                             │    C    │
/// │   NULL  │  ├─────────┤                             ├─────────┤
/// ├─────────┤  │  false  │  merge(mask, truthy, falsy) │    B    │
/// │    D    │  ├─────────┤  ─────────────────────────▶ ├─────────┤
/// └─────────┘  │  true   │                             │   NULL  │
///  falsy       ├─────────┤                             ├─────────┤
/// ┌─────────┐  │  false  │                             │    E    │
/// │    B    │  ├─────────┤                             ├─────────┤
/// ├─────────┤  │  true   │                             │    D    │
/// │    E    │  └─────────┘                             └─────────┘
/// └─────────┘
/// ```
pub fn merge(
    mask: &BooleanArray,
    truthy: &dyn Datum,
    falsy: &dyn Datum,
) -> Result<ArrayRef, ArrowError> {
    let (truthy_array, truthy_is_scalar) = truthy.get();
    let (falsy_array, falsy_is_scalar) = falsy.get();

    if truthy_is_scalar && falsy_is_scalar {
        // When both truthy and falsy are scalars, we can use `zip` since the result is the same
        // and zip has optimized code for scalars.
        return zip(mask, truthy, falsy);
    }

    if truthy_array.data_type() != falsy_array.data_type() {
        return Err(ArrowError::InvalidArgumentError(
            "arguments need to have the same data type".into(),
        ));
    }

    if truthy_is_scalar && truthy_array.len() != 1 {
        return Err(ArrowError::InvalidArgumentError(
            "scalar arrays must have 1 element".into(),
        ));
    }
    if falsy_is_scalar && falsy_array.len() != 1 {
        return Err(ArrowError::InvalidArgumentError(
            "scalar arrays must have 1 element".into(),
        ));
    }

    let falsy = falsy_array.to_data();
    let truthy = truthy_array.to_data();

    let mut mutable = match MutableArrayData::try_new(vec![&truthy, &falsy], false, mask.len()) {
        Ok(mutable) => mutable,
        // See `merge_n`: let `interleave` merge the dictionaries
        Err(ArrowError::DictionaryKeyOverflowError) => {
            return merge_with_interleave(
                mask,
                truthy_array,
                truthy_is_scalar,
                falsy_array,
                falsy_is_scalar,
            );
        }
        Err(e) => return Err(e),
    };

    // the SlicesIterator slices only the true values. So the gaps left by this iterator we need to
    // fill with falsy values

    // keep track of how much is filled
    let mut filled = 0;
    let mut falsy_offset = 0;
    let mut truthy_offset = 0;

    // Ensure nulls are treated as false
    let mask_buffer = match mask.null_count() {
        0 => mask.values().clone(),
        _ => prep_null_mask_filter(mask).into_parts().0,
    };

    for (start, end) in SlicesIterator::from(&mask_buffer) {
        // the gap needs to be filled with falsy values
        if start > filled {
            if falsy_is_scalar {
                for _ in filled..start {
                    // Copy the first item from the 'falsy' array into the output buffer.
                    mutable.try_extend(1, 0, 1)?;
                }
            } else {
                let falsy_length = start - filled;
                let falsy_end = falsy_offset + falsy_length;
                mutable.try_extend(1, falsy_offset, falsy_end)?;
                falsy_offset = falsy_end;
            }
        }
        // fill with truthy values
        if truthy_is_scalar {
            for _ in start..end {
                // Copy the first item from the 'truthy' array into the output buffer.
                mutable.try_extend(0, 0, 1)?;
            }
        } else {
            let truthy_length = end - start;
            let truthy_end = truthy_offset + truthy_length;
            mutable.try_extend(0, truthy_offset, truthy_end)?;
            truthy_offset = truthy_end;
        }
        filled = end;
    }
    // the remaining part is falsy
    if filled < mask.len() {
        if falsy_is_scalar {
            for _ in filled..mask.len() {
                // Copy the first item from the 'falsy' array into the output buffer.
                mutable.try_extend(1, 0, 1)?;
            }
        } else {
            let falsy_length = mask.len() - filled;
            let falsy_end = falsy_offset + falsy_length;
            mutable.try_extend(1, falsy_offset, falsy_end)?;
        }
    }

    let data = mutable.freeze();
    Ok(make_array(data))
}

#[cfg(test)]
mod tests {
    use crate::merge::{MergeIndex, merge, merge_n};
    use arrow_array::cast::AsArray;
    use arrow_array::types::Int8Type;
    use arrow_array::{
        Array, ArrayRef, BooleanArray, Datum, DictionaryArray, Int8Array, Int32Array, Scalar,
        StringArray, UInt64Array,
    };
    use arrow_schema::ArrowError::InvalidArgumentError;
    use std::sync::Arc;

    #[derive(PartialEq, Eq, Copy, Clone)]
    struct CompactMergeIndex {
        index: u8,
    }

    impl MergeIndex for CompactMergeIndex {
        fn index(&self) -> Option<usize> {
            if self.index == u8::MAX {
                None
            } else {
                Some(self.index as usize)
            }
        }
    }

    #[test]
    fn test_merge() {
        let a1 = StringArray::from(vec![Some("A"), Some("B"), Some("E"), None]);
        let a2 = StringArray::from(vec![Some("C"), Some("D")]);

        let indices = BooleanArray::from(vec![true, false, true, false, true, true]);

        let merged = merge(&indices, &a1, &a2).unwrap();
        let merged = merged.as_string::<i32>();

        assert_eq!(merged.len(), indices.len());
        assert!(merged.is_valid(0));
        assert_eq!(merged.value(0), "A");
        assert!(merged.is_valid(1));
        assert_eq!(merged.value(1), "C");
        assert!(merged.is_valid(2));
        assert_eq!(merged.value(2), "B");
        assert!(merged.is_valid(3));
        assert_eq!(merged.value(3), "D");
        assert!(merged.is_valid(4));
        assert_eq!(merged.value(4), "E");
        assert!(!merged.is_valid(5));
    }

    #[test]
    fn test_merge_null_is_false() {
        let a1 = StringArray::from(vec![Some("A"), Some("B"), Some("E"), None]);
        let a2 = StringArray::from(vec![Some("C"), Some("D")]);

        let indices = BooleanArray::from(vec![
            Some(true),
            None,
            Some(true),
            None,
            Some(true),
            Some(true),
        ]);

        let merged = merge(&indices, &a1, &a2).unwrap();
        let merged = merged.as_string::<i32>();

        assert_eq!(merged.len(), indices.len());
        assert!(merged.is_valid(0));
        assert_eq!(merged.value(0), "A");
        assert!(merged.is_valid(1));
        assert_eq!(merged.value(1), "C");
        assert!(merged.is_valid(2));
        assert_eq!(merged.value(2), "B");
        assert!(merged.is_valid(3));
        assert_eq!(merged.value(3), "D");
        assert!(merged.is_valid(4));
        assert_eq!(merged.value(4), "E");
        assert!(!merged.is_valid(5));
    }

    #[test]
    fn test_merge_false_tail() {
        let a1 = StringArray::from(vec![Some("A"), Some("B"), Some("E"), None]);
        let a2 = StringArray::from(vec![Some("C"), Some("D"), None, Some("F")]);

        let indices = BooleanArray::from(vec![true, false, true, false, true, true, false, false]);

        let merged = merge(&indices, &a1, &a2).unwrap();
        let merged = merged.as_string::<i32>();

        assert_eq!(merged.len(), indices.len());
        assert!(merged.is_valid(0));
        assert_eq!(merged.value(0), "A");
        assert!(merged.is_valid(1));
        assert_eq!(merged.value(1), "C");
        assert!(merged.is_valid(2));
        assert_eq!(merged.value(2), "B");
        assert!(merged.is_valid(3));
        assert_eq!(merged.value(3), "D");
        assert!(merged.is_valid(4));
        assert_eq!(merged.value(4), "E");
        assert!(!merged.is_valid(5));
        assert!(!merged.is_valid(6));
        assert!(merged.is_valid(7));
        assert_eq!(merged.value(7), "F");
    }

    #[test]
    fn test_merge_scalars() {
        let truthy = Scalar::new(StringArray::from(vec![Some("A")]));
        let falsy = Scalar::new(StringArray::from(vec![Some("B")]));

        let mask = BooleanArray::from(vec![true, false, false, true]);

        let merged = merge(&mask, &truthy, &falsy).unwrap();
        let merged = merged.as_string::<i32>();

        assert_eq!(merged.len(), mask.len());
        assert!(merged.is_valid(0));
        assert_eq!(merged.value(0), "A");
        assert!(merged.is_valid(1));
        assert_eq!(merged.value(1), "B");
        assert!(merged.is_valid(2));
        assert_eq!(merged.value(2), "B");
        assert!(merged.is_valid(3));
        assert_eq!(merged.value(3), "A");
    }

    #[test]
    fn test_merge_scalar_and_array() {
        let truthy = Scalar::new(StringArray::from(vec![Some("A")]));
        let falsy = StringArray::from(vec![Some("B"), Some("C")]);

        let mask = BooleanArray::from(vec![true, false, false, true]);

        let merged = merge(&mask, &truthy, &falsy).unwrap();
        let merged = merged.as_string::<i32>();

        assert_eq!(merged.len(), mask.len());
        assert!(merged.is_valid(0));
        assert_eq!(merged.value(0), "A");
        assert!(merged.is_valid(1));
        assert_eq!(merged.value(1), "B");
        assert!(merged.is_valid(2));
        assert_eq!(merged.value(2), "C");
        assert!(merged.is_valid(3));
        assert_eq!(merged.value(3), "A");
    }

    #[test]
    fn test_merge_array_and_scalar() {
        let truthy = StringArray::from(vec![Some("B"), Some("C")]);
        let falsy = Scalar::new(StringArray::from(vec![Some("A")]));

        let mask = BooleanArray::from(vec![true, false, false, true, false, false]);

        let merged = merge(&mask, &truthy, &falsy).unwrap();
        let merged = merged.as_string::<i32>();

        assert_eq!(merged.len(), mask.len());
        assert!(merged.is_valid(0));
        assert_eq!(merged.value(0), "B");
        assert!(merged.is_valid(1));
        assert_eq!(merged.value(1), "A");
        assert!(merged.is_valid(2));
        assert_eq!(merged.value(2), "A");
        assert!(merged.is_valid(3));
        assert_eq!(merged.value(3), "C");
        assert!(merged.is_valid(4));
        assert_eq!(merged.value(4), "A");
        assert!(merged.is_valid(5));
        assert_eq!(merged.value(5), "A");
    }

    #[test]
    fn test_merge_empty_mask() {
        let a1 = StringArray::from(vec![Some("A")]);
        let a2 = StringArray::from(vec![Some("B")]);
        let mask: Vec<bool> = vec![];
        let mask = BooleanArray::from(mask);
        let result = merge(&mask, &a1, &a2).unwrap();
        assert_eq!(result.len(), 0);
    }

    #[derive(Debug, Copy, Clone)]
    pub struct UnsafeScalar<T: Array>(T);

    impl<T: Array> Datum for UnsafeScalar<T> {
        fn get(&self) -> (&dyn Array, bool) {
            (&self.0, true)
        }
    }

    #[test]
    fn test_merge_invalid_truthy_scalar() {
        let truthy = UnsafeScalar(StringArray::from(vec![Some("A"), Some("C")]));
        let falsy = StringArray::from(vec![Some("B"), Some("D")]);
        let mask = BooleanArray::from(vec![true, false, true, false]);
        let merged = merge(&mask, &truthy, &falsy);
        assert!(matches!(merged, Err(InvalidArgumentError { .. })));
    }

    #[test]
    fn test_merge_invalid_falsy_scalar() {
        let truthy = StringArray::from(vec![Some("A"), Some("C")]);
        let falsy = UnsafeScalar(StringArray::from(vec![Some("B"), Some("D")]));
        let mask = vec![true, false, true, false];
        let mask = BooleanArray::from(mask);
        let merged = merge(&mask, &truthy, &falsy);
        assert!(matches!(merged, Err(InvalidArgumentError { .. })));
    }

    #[test]
    fn test_merge_incompatible_arrays() {
        let truthy = StringArray::from(vec![Some("A"), Some("B")]);
        let falsy = Int32Array::from(vec![1, 2]);
        let mask = BooleanArray::from(vec![true, false, true, false]);
        let merged = merge(&mask, &truthy, &falsy);
        assert!(matches!(merged, Err(InvalidArgumentError { .. })));
    }

    #[test]
    fn test_merge_n() {
        let a1 = StringArray::from(vec![Some("A")]);
        let a2 = StringArray::from(vec![Some("B"), None, None]);
        let a3 = StringArray::from(vec![Some("C"), Some("D")]);

        let indices = vec![
            CompactMergeIndex { index: u8::MAX },
            CompactMergeIndex { index: 1 },
            CompactMergeIndex { index: 0 },
            CompactMergeIndex { index: u8::MAX },
            CompactMergeIndex { index: 2 },
            CompactMergeIndex { index: 2 },
            CompactMergeIndex { index: 1 },
            CompactMergeIndex { index: 1 },
        ];

        let arrays = [a1, a2, a3];
        let array_refs = arrays.iter().map(|a| a as &dyn Array).collect::<Vec<_>>();
        let merged = merge_n(&array_refs, &indices).unwrap();
        let merged = merged.as_string::<i32>();

        assert_eq!(merged.len(), indices.len());
        assert!(!merged.is_valid(0));
        assert!(merged.is_valid(1));
        assert_eq!(merged.value(1), "B");
        assert!(merged.is_valid(2));
        assert_eq!(merged.value(2), "A");
        assert!(!merged.is_valid(3));
        assert!(merged.is_valid(4));
        assert_eq!(merged.value(4), "C");
        assert!(merged.is_valid(5));
        assert_eq!(merged.value(5), "D");
        assert!(!merged.is_valid(6));
        assert!(!merged.is_valid(7));
    }

    #[test]
    // The message differs between debug and release: in release the
    // `cfg(debug_assertions)` bounds check in `merge_n` is compiled out and the
    // slice index panics instead.
    #[should_panic(expected = "out of bounds")]
    fn test_merge_n_invalid_indices() {
        let a1 = StringArray::from(vec![Some("A")]);

        let indices = vec![CompactMergeIndex { index: 99 }];

        let arrays = [a1];
        let array_refs = arrays.iter().map(|a| a as &dyn Array).collect::<Vec<_>>();
        let _ = merge_n(&array_refs, &indices);
    }

    #[test]
    fn test_merge_n_empty_indices() {
        let a1 = StringArray::from(vec![Some("A")]);
        let a2 = StringArray::from(vec![Some("B"), None, None]);
        let a3 = StringArray::from(vec![Some("C"), Some("D")]);

        let indices: Vec<CompactMergeIndex> = vec![];

        let arrays = [a1, a2, a3];
        let array_refs = arrays.iter().map(|a| a as &dyn Array).collect::<Vec<_>>();
        let merged = merge_n(&array_refs, &indices).unwrap();

        assert_eq!(merged.len(), indices.len());
    }

    #[test]
    fn test_merge_n_empty_values() {
        let indices: Vec<CompactMergeIndex> = vec![];

        let arrays: Vec<&dyn Array> = vec![];
        let merged = merge_n(&arrays, &indices);

        assert!(matches!(merged, Err(InvalidArgumentError { .. })));
    }

    #[test]
    fn test_merge_n_incompatible_arrays() {
        let a1: Box<dyn Array> = Box::new(StringArray::from(vec![Some("A")]));
        let a2: Box<dyn Array> = Box::new(Int32Array::from(vec![1, 2, 3]));
        let a3: Box<dyn Array> = Box::new(UInt64Array::from(vec![42, 314]));

        let indices: Vec<CompactMergeIndex> = vec![];

        let arrays = [a1.as_ref(), a2.as_ref(), a3.as_ref()];
        let merged = merge_n(&arrays, &indices);

        assert!(matches!(merged, Err(InvalidArgumentError { .. })));
    }

    /// Two dictionaries of 100 values, the same in both. Concatenating them
    /// overflows Int8 keys, but the merged dictionary fits
    fn overflowing_dictionary(keys: Vec<Option<i8>>) -> ArrayRef {
        let values: Vec<String> = (0..100).map(|i| format!("v{i}")).collect();
        Arc::new(
            DictionaryArray::<Int8Type>::try_new(
                Int8Array::from(keys),
                Arc::new(StringArray::from(values)),
            )
            .unwrap(),
        )
    }

    fn dictionary_strings(array: &dyn Array) -> Vec<Option<&str>> {
        array
            .as_dictionary::<Int8Type>()
            .downcast_dict::<StringArray>()
            .unwrap()
            .into_iter()
            .collect()
    }

    #[test]
    fn test_merge_dictionaries_whose_combined_values_overflow_the_key_type() {
        let mask = BooleanArray::from(vec![Some(true), Some(false), None, Some(true), Some(false)]);
        let truthy = overflowing_dictionary(vec![Some(0), None, Some(2)]);
        let falsy = overflowing_dictionary(vec![Some(10), Some(20), Some(30)]);
        let truthy_scalar = Scalar::new(overflowing_dictionary(vec![Some(7)]));
        let falsy_scalar = Scalar::new(overflowing_dictionary(vec![Some(5)]));

        let check =
            |truthy_datum: &dyn Datum, falsy_datum: &dyn Datum, expected: [Option<&str>; 5]| {
                let merged = merge(&mask, truthy_datum, falsy_datum).unwrap();
                assert_eq!(merged.data_type(), truthy.data_type());
                assert_eq!(dictionary_strings(merged.as_ref()), expected);
            };
        check(
            &truthy,
            &falsy,
            [Some("v0"), Some("v10"), Some("v20"), None, Some("v30")],
        );
        check(
            &truthy,
            &falsy_scalar,
            [Some("v0"), Some("v5"), Some("v5"), None, Some("v5")],
        );
        check(
            &truthy_scalar,
            &falsy,
            [
                Some("v7"),
                Some("v10"),
                Some("v20"),
                Some("v7"),
                Some("v30"),
            ],
        );
    }

    #[test]
    fn test_merge_n_dictionaries_whose_combined_values_overflow_the_key_type() {
        let a = overflowing_dictionary(vec![Some(0), Some(1)]);
        let b = overflowing_dictionary(vec![Some(50), None]);
        let indices = vec![Some(1), None, Some(0), Some(0), Some(1), None];

        let merged = merge_n(&[a.as_ref(), b.as_ref()], &indices).unwrap();

        assert_eq!(merged.data_type(), a.data_type());
        assert_eq!(
            dictionary_strings(merged.as_ref()),
            [Some("v50"), None, Some("v0"), Some("v1"), None, None]
        );
    }
}