Repository navigation
Expand file tree
/
Copy pathfilter.rs
More file actions
2789 lines (2452 loc) · 103 KB
/
Copy pathfilter.rs
File metadata and controls
2789 lines (2452 loc) · 103 KB
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
// 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
//! Defines filter kernels
use std::ops::AddAssign;
use std::sync::Arc;
use arrow_array::builder::BooleanBufferBuilder;
use arrow_array::cast::AsArray;
use arrow_array::types::{
ArrowDictionaryKeyType, ArrowPrimitiveType, ByteArrayType, ByteViewType, RunEndIndexType,
};
use arrow_array::*;
use arrow_buffer::bit_chunk_iterator::BitChunks;
use arrow_buffer::{
ArrowNativeType, BooleanBuffer, NullBuffer, OffsetBuffer, RunEndBuffer, ScalarBuffer, bit_util,
};
use arrow_buffer::{Buffer, MutableBuffer};
use arrow_data::bit_iterator::{BitIndexIterator, BitSliceIterator};
use arrow_data::transform::MutableArrayData;
use arrow_schema::*;
/// If the filter selects more than this fraction of rows, use
/// [`SlicesIterator`] to copy ranges of values. Otherwise iterate
/// over individual rows using [`IndexIterator`]
///
/// Threshold of 0.8 chosen based on <https://dl.acm.org/doi/abs/10.1145/3465998.3466009>
///
const FILTER_SLICES_SELECTIVITY_THRESHOLD: f64 = 0.8;
/// An iterator of `(usize, usize)` each representing an interval
/// `[start, end)` whose slots of a bitmap [Buffer] are true.
///
/// Each interval corresponds to a contiguous region of memory to be
/// "taken" from an array to be filtered.
///
/// ## Notes:
///
/// 1. Ignores the validity bitmap (ignores nulls)
///
/// 2. Only performant for filters that copy across long contiguous runs
#[derive(Debug)]
pub struct SlicesIterator<'a>(BitSliceIterator<'a>);
impl<'a> SlicesIterator<'a> {
/// Creates a new iterator from a [BooleanArray]
pub fn new(filter: &'a BooleanArray) -> Self {
filter.values().into()
}
}
impl<'a> From<&'a BooleanBuffer> for SlicesIterator<'a> {
fn from(filter: &'a BooleanBuffer) -> Self {
Self(filter.set_slices())
}
}
impl Iterator for SlicesIterator<'_> {
type Item = (usize, usize);
#[inline]
fn next(&mut self) -> Option<Self::Item> {
self.0.next()
}
}
/// An iterator of `usize` whose index in [`BooleanArray`] is true
///
/// This provides the best performance on most predicates, apart from those which keep
/// large runs and therefore favour [`SlicesIterator`]
pub(crate) struct IndexIterator<'a> {
remaining: usize,
iter: BitIndexIterator<'a>,
}
impl<'a> IndexIterator<'a> {
pub(crate) fn new(filter: &'a BooleanArray, remaining: usize) -> Self {
assert_eq!(filter.null_count(), 0);
let iter = filter.values().set_indices();
Self { remaining, iter }
}
/// Collect this iterator as a [`Vec`]
/// This is more efficient than the standard `collect` as we can
/// pre-allocate the entire uninitialized buffer and then fill it (roughly 1.6x faster)
pub fn collect(mut self) -> Vec<usize> {
let len = self.remaining;
let mut result = Vec::with_capacity(len);
let ptr: *mut usize = result.as_mut_ptr();
for i in 0..len {
// SAFETY: we have allocated enough space in `result` and remaining
// correctly tracks the number of elements
let next = self.iter.next();
debug_assert!(next.is_some(), "IndexIterator exhausted early");
unsafe {
*ptr.add(i) = next.unwrap_unchecked();
}
}
// SAFETY: we have initialized `len` elements
unsafe {
result.set_len(len);
}
result
}
}
impl Iterator for IndexIterator<'_> {
type Item = usize;
fn next(&mut self) -> Option<Self::Item> {
if self.remaining != 0 {
// Fascinatingly swapping these two lines around results in a 50%
// performance regression for some benchmarks
let next = self.iter.next().expect("IndexIterator exhausted early");
self.remaining -= 1;
// Must panic if exhausted early as trusted length iterator
return Some(next);
}
None
}
fn size_hint(&self) -> (usize, Option<usize>) {
(self.remaining, Some(self.remaining))
}
}
/// Convert all null values in `BooleanArray` to `false`
///
/// This is useful for filter-like operations which select only `true`
/// values, but not `false` or `NULL` values
///
/// Internally this is implemented as a bitwise `AND` operation with null bits
/// and the boolean bits.
///
/// # Example
/// ```
/// # use arrow_array::{Array, BooleanArray};
/// # use arrow_select::filter::prep_null_mask_filter;
/// let filter = BooleanArray::from(vec![
/// Some(true),
/// Some(false),
/// None
/// ]);
/// // convert Boolean array to a filter mask
/// let null_mask = prep_null_mask_filter(&filter);
/// // there are no nulls in the output mask
/// assert!(null_mask.nulls().is_none());
/// assert_eq!(null_mask, BooleanArray::from(vec![
/// true,
/// false,
/// false, // Null is converted to false
/// ]));
/// ```
pub fn prep_null_mask_filter(filter: &BooleanArray) -> BooleanArray {
let nulls = filter.nulls().unwrap();
let mask = filter.values() & nulls.inner();
BooleanArray::new(mask, None)
}
/// Returns a filtered `values` [`Array`] where the corresponding elements of
/// `predicate` are `true`.
///
/// `predicate` may be shorter than `values`. Rows beyond the end of `predicate`
/// are not selected.
///
/// If multiple arrays (or record batches) need to be filtered using the same predicate array,
/// consider using [FilterBuilder] to create a single [FilterPredicate] and then
/// calling [FilterPredicate::filter_record_batch].
///
/// In contrast to this function, it is then the responsibility of the caller
/// to use [FilterBuilder::optimize] if appropriate.
///
/// If the number of rows that `predicate` selects is already known,
/// [`FilterBuilder::with_count`] avoids counting them again.
///
/// # See also
/// * [`FilterBuilder`] for more control over the filtering process.
/// * [`filter_record_batch`] to filter a [`RecordBatch`]
/// * [`BatchCoalescer`]: to filter multiple [`RecordBatch`] and coalesce
/// the results into a single array.
///
/// [`BatchCoalescer`]: crate::coalesce::BatchCoalescer
///
/// # Example
/// ```rust
/// # use arrow_array::{Int32Array, BooleanArray};
/// # use arrow_select::filter::filter;
/// let array = Int32Array::from(vec![5, 6, 7, 8, 9]);
/// // Rows beyond the end of the predicate are not selected.
/// let filter_array = BooleanArray::from(vec![true, false, true]);
/// let c = filter(&array, &filter_array).unwrap();
/// let c = c.as_any().downcast_ref::<Int32Array>().unwrap();
/// assert_eq!(c, &Int32Array::from(vec![5, 7]));
/// ```
pub fn filter(values: &dyn Array, predicate: &BooleanArray) -> Result<ArrayRef, ArrowError> {
let mut filter_builder = FilterBuilder::new(predicate);
if FilterBuilder::is_optimize_beneficial(values.data_type()) {
// Only optimize if filtering more than one array
// Otherwise, the overhead of optimization can be more than the benefit
filter_builder = filter_builder.optimize();
}
let predicate = filter_builder.build();
filter_array(values, &predicate)
}
/// Returns a filtered [RecordBatch] where the corresponding elements of
/// `predicate` are true.
///
/// This is the equivalent of calling [filter] on each column of the [RecordBatch].
///
/// `predicate` may be shorter than the batch. Rows beyond the end of `predicate`
/// are not selected.
///
/// If multiple record batches (or arrays) need to be filtered using the same predicate array,
/// consider using [FilterBuilder] to create a single [FilterPredicate] and then
/// calling [FilterPredicate::filter_record_batch].
/// In contrast to this function, it is then the responsibility of the caller
/// to use [FilterBuilder::optimize] if appropriate.
///
/// If the number of rows that `predicate` selects is already known,
/// [`FilterBuilder::with_count`] avoids counting them again.
pub fn filter_record_batch(
record_batch: &RecordBatch,
predicate: &BooleanArray,
) -> Result<RecordBatch, ArrowError> {
let mut filter_builder = FilterBuilder::new(predicate);
let num_cols = record_batch.num_columns();
if num_cols > 1
|| (num_cols > 0
&& FilterBuilder::is_optimize_beneficial(
record_batch.schema_ref().field(0).data_type(),
))
{
// Only optimize if filtering more than one column or if the column contains multiple internal arrays
// Otherwise, the overhead of optimization can be more than the benefit
filter_builder = filter_builder.optimize();
}
let filter = filter_builder.build();
filter.filter_record_batch(record_batch)
}
/// A builder to construct [`FilterPredicate`]
#[derive(Debug)]
pub struct FilterBuilder {
filter: BooleanArray,
/// The number of rows `filter` selects, if provided by [`Self::with_count`]
count: Option<usize>,
optimize: bool,
}
impl FilterBuilder {
/// Create a new [`FilterBuilder`] that can be used to construct a [`FilterPredicate`]
pub fn new(filter: &BooleanArray) -> Self {
let filter = match filter.null_count() {
0 => filter.clone(),
_ => prep_null_mask_filter(filter),
};
Self {
filter,
count: None,
optimize: false,
}
}
/// Set the number of rows that the filter selects, so that [`Self::build`]
/// does not have to count them.
///
/// Callers that build a mask row by row, or derive it from a validity
/// buffer with a cached null count, often already hold this number.
///
/// # Safety
///
/// `count` must equal [`BooleanArray::true_count`] of the filter passed to
/// [`Self::new`]: the number of `true` values that are not null.
///
/// # Example
/// ```
/// # use arrow_array::{BooleanArray, Int32Array};
/// # use arrow_select::filter::FilterBuilder;
/// let values = Int32Array::from(vec![1, 2, 3, 4]);
/// let mask = BooleanArray::from(vec![Some(true), None, Some(true), Some(false)]);
/// // The null is not selected, so the mask selects two rows.
/// // SAFETY: the count matches the mask.
/// let predicate = unsafe { FilterBuilder::new(&mask).with_count(2) }.build();
/// assert_eq!(predicate.count(), 2);
/// let filtered = predicate.filter(&values).unwrap();
/// assert_eq!(filtered.as_ref(), &Int32Array::from(vec![1, 3]));
/// ```
pub unsafe fn with_count(mut self, count: usize) -> Self {
debug_assert_eq!(
count,
self.filter.true_count(),
"count must match the number of rows the filter selects"
);
self.count = Some(count);
self
}
/// Compute an optimized representation of the provided `filter` mask in
/// [`Self::build`], so that it can be applied to an array more quickly.
///
/// When filtering multiple arrays (e.g. a [`RecordBatch`] or a
/// [`StructArray`] with multiple fields), optimizing the filter can provide
/// significant performance benefits.
///
/// However, optimization takes time and can have a larger memory footprint
/// than the original mask, so it is often faster to filter a single array,
/// without filter optimization.
pub fn optimize(mut self) -> Self {
self.optimize = true;
self
}
/// Determines if calling [FilterBuilder::optimize] is beneficial for the
/// given type even when filtering just a single array.
///
/// See [`FilterBuilder::optimize`] for more details.
pub fn is_optimize_beneficial(data_type: &DataType) -> bool {
match data_type {
DataType::Struct(fields) => {
fields.len() > 1
|| fields.len() == 1
&& FilterBuilder::is_optimize_beneficial(fields[0].data_type())
}
DataType::Union(fields, UnionMode::Sparse) => !fields.is_empty(),
_ => false,
}
}
/// Construct the final `FilterPredicate`
pub fn build(self) -> FilterPredicate {
let count = self.count.unwrap_or_else(|| self.filter.true_count());
let mut strategy = IterationStrategy::default_strategy(self.filter.len(), count);
if self.optimize {
match strategy {
IterationStrategy::SlicesIterator => {
let slices = SlicesIterator::new(&self.filter).collect();
strategy = IterationStrategy::Slices(slices)
}
IterationStrategy::IndexIterator => {
let indices = IndexIterator::new(&self.filter, count).collect();
strategy = IterationStrategy::Indices(indices)
}
_ => {}
}
}
FilterPredicate {
filter: self.filter,
count,
strategy,
}
}
}
/// The iteration strategy used to evaluate [`FilterPredicate`]
#[derive(Debug)]
enum IterationStrategy {
/// A lazily evaluated iterator of ranges
SlicesIterator,
/// A lazily evaluated iterator of indices
IndexIterator,
/// A precomputed list of indices
Indices(Vec<usize>),
/// A precomputed array of ranges
Slices(Vec<(usize, usize)>),
/// Select all rows
All,
/// Select no rows
None,
}
impl IterationStrategy {
/// The default [`IterationStrategy`] for a filter of length `filter_length`
/// and selecting `filter_count` rows
fn default_strategy(filter_length: usize, filter_count: usize) -> Self {
if filter_length == 0 || filter_count == 0 {
return IterationStrategy::None;
}
if filter_count == filter_length {
return IterationStrategy::All;
}
// Compute the selectivity of the predicate by dividing the number of true
// bits in the predicate by the predicate's total length
//
// This can then be used as a heuristic for the optimal iteration strategy
let selectivity_frac = filter_count as f64 / filter_length as f64;
if selectivity_frac > FILTER_SLICES_SELECTIVITY_THRESHOLD {
return IterationStrategy::SlicesIterator;
}
IterationStrategy::IndexIterator
}
}
/// Borrowed description of which rows a [`FilterPredicate`] selects.
///
/// This is used for filtering multiple arrays with the same predicate without
/// having to clone the predicate's internal data structures (e.g. the list of
/// indices or slices).
pub(crate) enum FilterSelection<'a> {
/// No rows are selected
None,
/// All `len` rows are selected
All { len: usize },
/// Iterator of `(start, end)` slices, each a run of contiguous selected rows
Slices(FilterSlices<'a>),
/// Iterator of the indices of the selected rows
Indices(FilterIndices<'a>),
}
pub(crate) type FilterSlices<'a> =
FilterIterator<std::iter::Copied<std::slice::Iter<'a, (usize, usize)>>, SlicesIterator<'a>>;
pub(crate) type FilterIndices<'a> =
FilterIterator<std::iter::Copied<std::slice::Iter<'a, usize>>, IndexIterator<'a>>;
/// Internal implementation of [`FilterSelection`] that holds either an iterator
/// over a precomputed (materialized) list of rows, or a lazy iterator that
/// derives the selected rows from the predicate on the fly.
///
/// This does not implement [`Iterator`] on purpose. Callers use
/// [`Self::for_each`] or [`Self::try_for_each`] so the enum is matched once
/// before the loop, not once per row in `next`.
pub(crate) enum FilterIterator<M, I> {
Materialized(M),
Lazy(I),
}
impl<M, I> FilterIterator<M, I>
where
M: Iterator,
I: Iterator<Item = M::Item>,
{
/// Call the infallible function `f` for each item in this [`FilterIterator`]
pub(crate) fn for_each<F>(self, f: F)
where
F: FnMut(M::Item),
{
match self {
Self::Materialized(iter) => iter.for_each(f),
Self::Lazy(iter) => iter.for_each(f),
}
}
/// Call the fallible function `f` for each item in this [`FilterIterator`],
/// stopping and returning the error if `f` returns `Err`.
pub(crate) fn try_for_each<F, E>(self, mut f: F) -> Result<(), E>
where
F: FnMut(M::Item) -> Result<(), E>,
{
match self {
Self::Materialized(iter) => {
for item in iter {
f(item)?;
}
}
Self::Lazy(iter) => {
for item in iter {
f(item)?;
}
}
}
Ok(())
}
}
/// A filtering predicate that can be applied to an [`Array`]
#[derive(Debug)]
pub struct FilterPredicate {
filter: BooleanArray,
count: usize,
/// Precomputed strategy for iterating over the selected rows of this predicate
strategy: IterationStrategy,
}
impl FilterPredicate {
/// Selects rows from `values` based on this [`FilterPredicate`]
///
/// This predicate may be shorter than `values`. Rows beyond its length are not selected.
pub fn filter(&self, values: &dyn Array) -> Result<ArrayRef, ArrowError> {
filter_array(values, self)
}
/// Returns a filtered [`RecordBatch`] containing only the rows that are selected by this
/// [`FilterPredicate`].
///
/// This is the equivalent of calling [filter] on each column of the [`RecordBatch`].
///
/// This predicate may be shorter than the batch. Rows beyond its length are not selected.
pub fn filter_record_batch(
&self,
record_batch: &RecordBatch,
) -> Result<RecordBatch, ArrowError> {
let filtered_arrays = record_batch
.columns()
.iter()
.map(|a| filter_array(a, self))
.collect::<Result<Vec<_>, _>>()?;
// SAFETY: we know that the set of filtered arrays will match the schema of the original
// record batch
unsafe {
Ok(RecordBatch::new_unchecked(
record_batch.schema(),
filtered_arrays,
self.count,
))
}
}
/// Number of rows being selected based on this [`FilterPredicate`]
pub fn count(&self) -> usize {
self.count
}
/// Length of the filter mask, including rows that are not selected
pub(crate) fn filter_len(&self) -> usize {
self.filter.len()
}
/// Returns the normalized filter mask, with nulls replaced by `false`.
pub(crate) fn filter_mask(&self) -> &BooleanBuffer {
self.filter.values()
}
/// Returns whether bit filtering should gather precomputed indices instead of compressing.
pub(crate) fn uses_sparse_indices(&self) -> bool {
self.count <= self.filter.len() / 64
&& matches!(self.strategy, IterationStrategy::Indices(_))
}
/// Return a [`FilterSelection`] for iterating over the rows selected by
/// this [`FilterPredicate`].
pub(crate) fn selection(&self) -> FilterSelection<'_> {
match &self.strategy {
IterationStrategy::None => FilterSelection::None,
IterationStrategy::All => FilterSelection::All { len: self.count },
IterationStrategy::Slices(slices) => {
FilterSelection::Slices(FilterIterator::Materialized(slices.iter().copied()))
}
IterationStrategy::SlicesIterator => {
FilterSelection::Slices(FilterIterator::Lazy(SlicesIterator::new(&self.filter)))
}
IterationStrategy::Indices(indices) => {
FilterSelection::Indices(FilterIterator::Materialized(indices.iter().copied()))
}
IterationStrategy::IndexIterator => FilterSelection::Indices(FilterIterator::Lazy(
IndexIterator::new(&self.filter, self.count),
)),
}
}
/// Filters the given `nulls` buffer using this predicate.
///
/// Returns `None` when there is nothing to track in the output, either
/// because the input `nulls` was `None`, the input had no nulls, or the
/// filtered result has no nulls. Otherwise returns the filtered
/// [`NullBuffer`] with its precomputed null count.
///
/// # Panics
///
/// Panics if the input contains nulls and is shorter than this predicate.
pub fn filter_nulls(&self, nulls: Option<&NullBuffer>) -> Option<NullBuffer> {
let nulls = nulls?;
if nulls.null_count() == 0 {
return None;
}
assert!(nulls.len() >= self.filter.len());
match self.strategy {
IterationStrategy::None => return None,
IterationStrategy::All => {
let nulls = nulls.slice(0, self.count);
return (nulls.null_count() != 0).then_some(nulls);
}
_ => {}
}
let nulls = filter_bits(nulls.inner(), self);
// The filtered `nulls` has a length of `self.count` bits and therefore
// the null count is this minus the number of valid bits
let null_count = self.count - nulls.count_set_bits_offset(0, self.count);
if null_count == 0 {
return None;
}
let buffer = BooleanBuffer::new(nulls, 0, self.count);
debug_assert_eq!(null_count, buffer.len() - buffer.count_set_bits());
// SAFETY: `null_count` was derived from `buffer` above, so it matches
// the number of unset bits as required by `new_unchecked`.
Some(unsafe { NullBuffer::new_unchecked(buffer, null_count) })
}
}
fn filter_array(values: &dyn Array, predicate: &FilterPredicate) -> Result<ArrayRef, ArrowError> {
if predicate.filter.len() > values.len() {
return Err(ArrowError::InvalidArgumentError(format!(
"Filter predicate of length {} is larger than target array of length {}",
predicate.filter.len(),
values.len()
)));
}
match predicate.strategy {
IterationStrategy::None => Ok(new_empty_array(values.data_type())),
IterationStrategy::All => Ok(values.slice(0, predicate.count)),
// actually filter
_ => downcast_primitive_array! {
values => Ok(Arc::new(filter_primitive(values, predicate))),
DataType::Boolean => {
let values = values.as_any().downcast_ref::<BooleanArray>().unwrap();
Ok(Arc::new(filter_boolean(values, predicate)))
}
DataType::Utf8 => {
Ok(Arc::new(filter_bytes(values.as_string::<i32>(), predicate)))
}
DataType::LargeUtf8 => {
Ok(Arc::new(filter_bytes(values.as_string::<i64>(), predicate)))
}
DataType::Utf8View => {
Ok(Arc::new(filter_byte_view(values.as_string_view(), predicate)))
}
DataType::Binary => {
Ok(Arc::new(filter_bytes(values.as_binary::<i32>(), predicate)))
}
DataType::LargeBinary => {
Ok(Arc::new(filter_bytes(values.as_binary::<i64>(), predicate)))
}
DataType::BinaryView => {
Ok(Arc::new(filter_byte_view(values.as_binary_view(), predicate)))
}
DataType::FixedSizeBinary(_) => {
Ok(Arc::new(filter_fixed_size_binary(
values.as_fixed_size_binary(),
predicate,
)?))
}
DataType::ListView(_) => {
Ok(Arc::new(filter_list_view::<i32>(values.as_list_view(), predicate)))
}
DataType::LargeListView(_) => {
Ok(Arc::new(filter_list_view::<i64>(values.as_list_view(), predicate)))
}
DataType::RunEndEncoded(_, _) => {
downcast_run_array!{
values => Ok(Arc::new(filter_run_end_array(values, predicate)?)),
t => unimplemented!("Filter not supported for RunEndEncoded type {:?}", t)
}
}
DataType::Dictionary(_, _) => downcast_dictionary_array! {
values => Ok(Arc::new(filter_dict(values, predicate))),
t => unimplemented!("Filter not supported for dictionary type {:?}", t)
}
DataType::Struct(_) => {
Ok(Arc::new(filter_struct(values.as_struct(), predicate)?))
}
DataType::Union(_, UnionMode::Sparse) => {
Ok(Arc::new(filter_sparse_union(values.as_union(), predicate)?))
}
_ => {
let data = values.to_data();
// fallback to using MutableArrayData
let mut mutable = MutableArrayData::try_new(
vec![&data],
false,
predicate.count,
)?;
match &predicate.strategy {
IterationStrategy::Slices(slices) => {
for (start, end) in slices {
mutable.try_extend(0, *start, *end)?;
}
}
_ => {
let iter = SlicesIterator::new(&predicate.filter);
for (start, end) in iter {
mutable.try_extend(0, start, end)?;
}
}
}
let data = mutable.freeze();
Ok(make_array(data))
}
},
}
}
/// Filter any supported [`RunArray`] based on a [`FilterPredicate`]
fn filter_run_end_array<R: RunEndIndexType>(
array: &RunArray<R>,
predicate: &FilterPredicate,
) -> Result<RunArray<R>, ArrowError>
where
R::Native: Into<i64> + From<bool>,
R::Native: AddAssign,
{
let run_ends: &RunEndBuffer<R::Native> = array.run_ends();
let start_physical = run_ends.get_start_physical_index();
let end_physical = run_ends.get_end_physical_index();
let physical_len = end_physical - start_physical + 1;
let mut new_run_ends = vec![R::default_value(); physical_len];
let offset = run_ends.offset() as u64;
let mut start = 0u64;
let mut j = 0;
let mut count = R::default_value();
let filter_values = predicate.filter.values();
let run_ends = run_ends.inner();
let pred: BooleanArray = BooleanBuffer::collect_bool(physical_len, |i| {
let mut keep = false;
let mut end = (run_ends[i + start_physical].into() as u64).saturating_sub(offset);
let difference = end.saturating_sub(filter_values.len() as u64);
end -= difference;
// Safety: we subtract the difference off `end` so we are always within bounds
for pred in (start..end).map(|i| unsafe { filter_values.value_unchecked(i as usize) }) {
count += R::Native::from(pred);
keep |= pred
}
// this is to avoid branching
new_run_ends[j] = count;
j += keep as usize;
start = end;
keep
})
.into();
new_run_ends.truncate(j);
let values = array.values_slice();
let values = filter(values.as_ref(), &pred)?;
let run_ends = PrimitiveArray::<R>::try_new(new_run_ends.into(), None)?;
RunArray::try_new(&run_ends, &values)
}
/// Filter the packed bitmask `buffer` with `predicate`, choosing between the
/// strategy-based and compress-based kernels by filter density
fn filter_bits(buffer: &BooleanBuffer, predicate: &FilterPredicate) -> Buffer {
// Compressing scans the whole mask a word at a time, so it loses to the
// slices strategies once fewer than one bit per word is dropped, and to
// precomputed `Indices` once fewer than one bit per word is kept. The lazy
// `IndexIterator` scans the mask anyway, so it never beats compressing
let len = predicate.filter.len();
let count = predicate.count;
let dense = count >= len - len / 64;
let sparse_indices = predicate.uses_sparse_indices();
if !dense && !sparse_indices {
return filter_bits_compress(buffer, predicate);
}
filter_bits_strategy(buffer, predicate)
}
/// Filter the packed bitmask `buffer` with `predicate` using its
/// [`IterationStrategy`]
fn filter_bits_strategy(buffer: &BooleanBuffer, predicate: &FilterPredicate) -> Buffer {
let src = buffer.values();
let offset = buffer.offset();
assert!(buffer.len() >= predicate.filter.len());
match &predicate.strategy {
IterationStrategy::IndexIterator => {
let bits =
// SAFETY: IndexIterator uses the filter predicate to derive indices
IndexIterator::new(&predicate.filter, predicate.count).map(|src_idx| unsafe {
bit_util::get_bit_raw(buffer.values().as_ptr(), src_idx + offset)
});
// SAFETY: `IndexIterator` reports its size correctly
unsafe { MutableBuffer::from_trusted_len_iter_bool(bits).into() }
}
IterationStrategy::Indices(indices) => {
// SAFETY: indices were derived from the filter predicate
let bits = indices.iter().map(|src_idx| unsafe {
bit_util::get_bit_raw(buffer.values().as_ptr(), *src_idx + offset)
});
// SAFETY: `Vec::iter()` reports its size correctly
unsafe { MutableBuffer::from_trusted_len_iter_bool(bits).into() }
}
IterationStrategy::SlicesIterator => {
let mut builder = BooleanBufferBuilder::new(predicate.count);
for (start, end) in SlicesIterator::new(&predicate.filter) {
builder.append_packed_range(start + offset..end + offset, src)
}
builder.into()
}
IterationStrategy::Slices(slices) => {
let mut builder = BooleanBufferBuilder::new(predicate.count);
for (start, end) in slices {
builder.append_packed_range(*start + offset..*end + offset, src)
}
builder.into()
}
IterationStrategy::All | IterationStrategy::None => unreachable!(),
}
}
/// Packs bits selected from successive words into complete output words.
#[derive(Default)]
pub(crate) struct Packer {
/// Bits waiting to be written.
current: u64,
/// Number of populated low bits in `current`.
filled: u32,
}
impl Packer {
#[inline(always)]
pub(crate) fn push(&mut self, values: u64, mask: u64) -> Option<u64> {
let bits = bit_util::compress(values, mask);
self.current |= bits << self.filled;
let total = self.filled + mask.count_ones();
if total < 64 {
self.filled = total;
return None;
}
let complete = self.current;
// `bits >> (64 - filled)`, written so that `filled == 0`
// shifts everything out
self.current = (bits >> 1) >> (63 - self.filled);
self.filled = total - 64;
Some(complete)
}
#[inline]
pub(crate) fn finish(self) -> Option<(u64, usize)> {
(self.filled != 0).then_some((self.current, self.filled as usize))
}
}
/// Filter the packed bitmask `buffer` with `predicate` by extracting the kept
/// bits of each 64-bit word with [`bit_util::compress`] (`pext`).
///
/// Not inlined: within `filter_array` the packing state spills to the stack.
#[inline(never)]
fn filter_bits_compress(buffer: &BooleanBuffer, predicate: &FilterPredicate) -> Buffer {
assert!(buffer.len() >= predicate.filter.len());
let mask_chunks = predicate.filter.values().bit_chunks();
let value_chunks = BitChunks::new(buffer.values(), buffer.offset(), predicate.filter.len());
// `predicate.count` is the filter's set bit count, which determines the
// output capacity and bounds the raw writes below. Both chunk views cover
// `predicate.filter.len()` bits, so indexing `value_chunks` by the
// position in `mask_chunks` stays in bounds.
debug_assert_eq!(predicate.count, predicate.filter.true_count());
debug_assert_eq!(mask_chunks.chunk_len(), value_chunks.chunk_len());
// One word beyond the complete ones for the trailing partial word
let mut out: Vec<u64> = Vec::with_capacity(predicate.count / 64 + 1);
let ptr = out.as_mut_ptr();
let mut idx = 0;
let mut packer = Packer::default();
for (index, mask) in mask_chunks.iter().enumerate() {
// Words with no kept bits are skipped before the corresponding values
// are read, so only the mask is touched for them
if mask == 0 {
continue;
}
if let Some(complete) = packer.push(value_chunks.chunk(index), mask) {
debug_assert!(idx < out.capacity());
// SAFETY: `complete` contains 64 of the `predicate.count` selected
// bits. Therefore `idx < predicate.count / 64` before this write,
// while `out` has capacity at least `predicate.count / 64 + 1`.
unsafe { ptr.add(idx).write(complete) };
idx += 1;
}
}
if let Some(complete) = packer.push(value_chunks.remainder_bits(), mask_chunks.remainder_bits())
{
debug_assert!(idx < out.capacity());
// SAFETY: this completed word also contains 64 of the
// `predicate.count` selected bits, so the same
// `idx < predicate.count / 64 < out.capacity()` bound applies.
unsafe { ptr.add(idx).write(complete) };
idx += 1;
}
if let Some((pending, _)) = packer.finish() {
debug_assert!(idx < out.capacity());
// SAFETY: `pending` exists only when the selected bit count is not a
// multiple of 64. All prior writes were complete words, so
// `idx == predicate.count / 64 < out.capacity()`.
unsafe { ptr.add(idx).write(pending) };
idx += 1;
}
// SAFETY: every word below `idx` was initialized above
unsafe { out.set_len(idx) };
let mut out = MutableBuffer::from(out);
out.truncate(bit_util::ceil(predicate.count, 8));
out.into()
}
/// `filter` implementation for boolean buffers
fn filter_boolean(array: &BooleanArray, predicate: &FilterPredicate) -> BooleanArray {
let buffer = filter_bits(array.values(), predicate);
let values = BooleanBuffer::new(buffer, 0, predicate.count);
let nulls = predicate.filter_nulls(array.nulls());
BooleanArray::new(values, nulls)
}
#[inline(never)]
pub(crate) fn filter_native<T: ArrowNativeType>(
values: &[T],
predicate: &FilterPredicate,
) -> Buffer {
assert!(values.len() >= predicate.filter.len());
match &predicate.strategy {
IterationStrategy::SlicesIterator => {
let mut buffer = Vec::with_capacity(predicate.count);
for (start, end) in SlicesIterator::new(&predicate.filter) {
// SAFETY: indices were derived from the filter predicate
buffer.extend_from_slice(unsafe { values.get_unchecked(start..end) });
}
buffer.into()
}
IterationStrategy::Slices(slices) => {
let mut buffer = Vec::with_capacity(predicate.count);
for (start, end) in slices {
// SAFETY: indices were derived from the filter predicate
buffer.extend_from_slice(unsafe { values.get_unchecked(*start..*end) });
}
buffer.into()
}
IterationStrategy::IndexIterator => {
// SAFETY: indices were derived from the filter predicate
let iter = IndexIterator::new(&predicate.filter, predicate.count)
.map(|x| unsafe { *values.get_unchecked(x) });
// SAFETY: IndexIterator is trusted length
unsafe { MutableBuffer::from_trusted_len_iter(iter) }.into()
}
IterationStrategy::Indices(indices) => {
// SAFETY: indices were derived from the filter predicate
let iter = indices.iter().map(|x| unsafe { *values.get_unchecked(*x) });
iter.collect::<Vec<_>>().into()
}
IterationStrategy::All | IterationStrategy::None => unreachable!(),
}
}
/// `filter` implementation for primitive arrays
fn filter_primitive<T>(array: &PrimitiveArray<T>, predicate: &FilterPredicate) -> PrimitiveArray<T>
where
T: ArrowPrimitiveType,
{
let buffer = filter_native(array.values(), predicate);
let values = ScalarBuffer::new(buffer, 0, predicate.count);
let nulls = predicate.filter_nulls(array.nulls());
let filtered = PrimitiveArray::new(values, nulls);
// Avoid the compatibility check when the physical type already matches.
if array.data_type() == &T::DATA_TYPE {
filtered
} else {
filtered.with_data_type(array.data_type().clone())
}
}
/// [`FilterBytes`] is created from a source [`GenericByteArray`] and can be
/// used to build a new [`GenericByteArray`] by copying values from the source
///
/// TODO(raphael): Could this be used for the take kernel as well?
struct FilterBytes<'a, OffsetSize> {
src_offsets: &'a [OffsetSize],
src_values: &'a [u8],
dst_offsets: Vec<OffsetSize>,
dst_values: Vec<u8>,
cur_offset: OffsetSize,
}
impl<'a, OffsetSize> FilterBytes<'a, OffsetSize>
where
OffsetSize: OffsetSizeTrait,
{
fn new<T>(capacity: usize, array: &'a GenericByteArray<T>) -> Self
where
T: ByteArrayType<Offset = OffsetSize>,
{
let dst_values = Vec::new();
let mut dst_offsets: Vec<OffsetSize> = Vec::with_capacity(capacity + 1);
let cur_offset = OffsetSize::from_usize(0).unwrap();