forked from apache/arrow-rs
/
take.rs
2041 lines (1838 loc) · 69 KB
/
take.rs
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
//! Defines take kernel for [Array]
use std::{ops::AddAssign, sync::Arc};
use crate::buffer::{Buffer, MutableBuffer};
use crate::compute::util::{
take_value_indices_from_fixed_size_list, take_value_indices_from_list,
};
use crate::datatypes::*;
use crate::error::{ArrowError, Result};
use crate::util::bit_util;
use crate::{array::*, buffer::buffer_bin_and};
use num::{ToPrimitive, Zero};
use TimeUnit::*;
macro_rules! downcast_take {
($type: ty, $values: expr, $indices: expr) => {{
let values = $values
.as_any()
.downcast_ref::<PrimitiveArray<$type>>()
.expect("Unable to downcast to a primitive array");
Ok(Arc::new(take_primitive::<$type, _>(&values, $indices)?))
}};
}
macro_rules! downcast_dict_take {
($type: ty, $values: expr, $indices: expr) => {{
let values = $values
.as_any()
.downcast_ref::<DictionaryArray<$type>>()
.expect("Unable to downcast to a dictionary array");
Ok(Arc::new(take_dict::<$type, _>(values, $indices)?))
}};
}
/// Take elements by index from [Array], creating a new [Array] from those indexes.
///
/// ```text
/// ┌─────────────────┐ ┌─────────┐ ┌─────────────────┐
/// │ A │ │ 0 │ │ A │
/// ├─────────────────┤ ├─────────┤ ├─────────────────┤
/// │ D │ │ 2 │ │ B │
/// ├─────────────────┤ ├─────────┤ take(values, indicies) ├─────────────────┤
/// │ B │ │ 3 │ ─────────────────────────▶ │ C │
/// ├─────────────────┤ ├─────────┤ ├─────────────────┤
/// │ C │ │ 1 │ │ D │
/// ├─────────────────┤ └─────────┘ └─────────────────┘
/// │ E │
/// └─────────────────┘
/// values array indicies array result
/// ```
///
/// # Errors
/// This function errors whenever:
/// * An index cannot be casted to `usize` (typically 32 bit architectures)
/// * An index is out of bounds and `options` is set to check bounds.
/// # Safety
/// When `options` is not set to check bounds (default), taking indexes after `len` is undefined behavior.
/// # Examples
/// ```
/// use arrow::array::{StringArray, UInt32Array};
/// use arrow::error::Result;
/// use arrow::compute::take;
/// # fn main() -> Result<()> {
/// let values = StringArray::from(vec!["zero", "one", "two"]);
///
/// // Take items at index 2, and 1:
/// let indices = UInt32Array::from(vec![2, 1]);
/// let taken = take(&values, &indices, None)?;
/// let taken = taken.as_any().downcast_ref::<StringArray>().unwrap();
///
/// assert_eq!(*taken, StringArray::from(vec!["two", "one"]));
/// # Ok(())
/// # }
/// ```
pub fn take<IndexType>(
values: &dyn Array,
indices: &PrimitiveArray<IndexType>,
options: Option<TakeOptions>,
) -> Result<ArrayRef>
where
IndexType: ArrowNumericType,
IndexType::Native: ToPrimitive,
{
take_impl(values, indices, options)
}
fn take_impl<IndexType>(
values: &dyn Array,
indices: &PrimitiveArray<IndexType>,
options: Option<TakeOptions>,
) -> Result<ArrayRef>
where
IndexType: ArrowNumericType,
IndexType::Native: ToPrimitive,
{
let options = options.unwrap_or_default();
if options.check_bounds {
let len = values.len();
if indices.null_count() > 0 {
indices.iter().flatten().try_for_each(|index| {
let ix = ToPrimitive::to_usize(&index).ok_or_else(|| {
ArrowError::ComputeError("Cast to usize failed".to_string())
})?;
if ix >= len {
return Err(ArrowError::ComputeError(
format!("Array index out of bounds, cannot get item at index {} from {} entries", ix, len))
);
}
Ok(())
})?;
} else {
indices.values().iter().try_for_each(|index| {
let ix = ToPrimitive::to_usize(index).ok_or_else(|| {
ArrowError::ComputeError("Cast to usize failed".to_string())
})?;
if ix >= len {
return Err(ArrowError::ComputeError(
format!("Array index out of bounds, cannot get item at index {} from {} entries", ix, len))
);
}
Ok(())
})?
}
}
match values.data_type() {
DataType::Boolean => {
let values = values.as_any().downcast_ref::<BooleanArray>().unwrap();
Ok(Arc::new(take_boolean(values, indices)?))
}
DataType::Decimal(_, _) => {
let decimal_values = values.as_any().downcast_ref::<DecimalArray>().unwrap();
Ok(Arc::new(take_decimal128(decimal_values, indices)?))
}
DataType::Int8 => downcast_take!(Int8Type, values, indices),
DataType::Int16 => downcast_take!(Int16Type, values, indices),
DataType::Int32 => downcast_take!(Int32Type, values, indices),
DataType::Int64 => downcast_take!(Int64Type, values, indices),
DataType::UInt8 => downcast_take!(UInt8Type, values, indices),
DataType::UInt16 => downcast_take!(UInt16Type, values, indices),
DataType::UInt32 => downcast_take!(UInt32Type, values, indices),
DataType::UInt64 => downcast_take!(UInt64Type, values, indices),
DataType::Float32 => downcast_take!(Float32Type, values, indices),
DataType::Float64 => downcast_take!(Float64Type, values, indices),
DataType::Date32 => downcast_take!(Date32Type, values, indices),
DataType::Date64 => downcast_take!(Date64Type, values, indices),
DataType::Time32(Second) => downcast_take!(Time32SecondType, values, indices),
DataType::Time32(Millisecond) => {
downcast_take!(Time32MillisecondType, values, indices)
}
DataType::Time64(Microsecond) => {
downcast_take!(Time64MicrosecondType, values, indices)
}
DataType::Time64(Nanosecond) => {
downcast_take!(Time64NanosecondType, values, indices)
}
DataType::Timestamp(Second, _) => {
downcast_take!(TimestampSecondType, values, indices)
}
DataType::Timestamp(Millisecond, _) => {
downcast_take!(TimestampMillisecondType, values, indices)
}
DataType::Timestamp(Microsecond, _) => {
downcast_take!(TimestampMicrosecondType, values, indices)
}
DataType::Timestamp(Nanosecond, _) => {
downcast_take!(TimestampNanosecondType, values, indices)
}
DataType::Interval(IntervalUnit::YearMonth) => {
downcast_take!(IntervalYearMonthType, values, indices)
}
DataType::Interval(IntervalUnit::DayTime) => {
downcast_take!(IntervalDayTimeType, values, indices)
}
DataType::Interval(IntervalUnit::MonthDayNano) => {
downcast_take!(IntervalMonthDayNanoType, values, indices)
}
DataType::Duration(TimeUnit::Second) => {
downcast_take!(DurationSecondType, values, indices)
}
DataType::Duration(TimeUnit::Millisecond) => {
downcast_take!(DurationMillisecondType, values, indices)
}
DataType::Duration(TimeUnit::Microsecond) => {
downcast_take!(DurationMicrosecondType, values, indices)
}
DataType::Duration(TimeUnit::Nanosecond) => {
downcast_take!(DurationNanosecondType, values, indices)
}
DataType::Utf8 => {
let values = values
.as_any()
.downcast_ref::<GenericStringArray<i32>>()
.unwrap();
Ok(Arc::new(take_string::<i32, _>(values, indices)?))
}
DataType::LargeUtf8 => {
let values = values
.as_any()
.downcast_ref::<GenericStringArray<i64>>()
.unwrap();
Ok(Arc::new(take_string::<i64, _>(values, indices)?))
}
DataType::List(_) => {
let values = values
.as_any()
.downcast_ref::<GenericListArray<i32>>()
.unwrap();
Ok(Arc::new(take_list::<_, Int32Type>(values, indices)?))
}
DataType::LargeList(_) => {
let values = values
.as_any()
.downcast_ref::<GenericListArray<i64>>()
.unwrap();
Ok(Arc::new(take_list::<_, Int64Type>(values, indices)?))
}
DataType::FixedSizeList(_, length) => {
let values = values
.as_any()
.downcast_ref::<FixedSizeListArray>()
.unwrap();
Ok(Arc::new(take_fixed_size_list(
values,
indices,
*length as u32,
)?))
}
DataType::Struct(fields) => {
let struct_: &StructArray =
values.as_any().downcast_ref::<StructArray>().unwrap();
let arrays: Result<Vec<ArrayRef>> = struct_
.columns()
.iter()
.map(|a| take_impl(a.as_ref(), indices, Some(options.clone())))
.collect();
let arrays = arrays?;
let fields: Vec<(Field, ArrayRef)> =
fields.clone().into_iter().zip(arrays).collect();
// Create the null bit buffer.
let is_valid: Buffer = indices
.iter()
.map(|index| {
if let Some(index) = index {
struct_.is_valid(ArrowNativeType::to_usize(&index).unwrap())
} else {
false
}
})
.collect();
Ok(Arc::new(StructArray::from((fields, is_valid))) as ArrayRef)
}
DataType::Dictionary(key_type, _) => match key_type.as_ref() {
DataType::Int8 => downcast_dict_take!(Int8Type, values, indices),
DataType::Int16 => downcast_dict_take!(Int16Type, values, indices),
DataType::Int32 => downcast_dict_take!(Int32Type, values, indices),
DataType::Int64 => downcast_dict_take!(Int64Type, values, indices),
DataType::UInt8 => downcast_dict_take!(UInt8Type, values, indices),
DataType::UInt16 => downcast_dict_take!(UInt16Type, values, indices),
DataType::UInt32 => downcast_dict_take!(UInt32Type, values, indices),
DataType::UInt64 => downcast_dict_take!(UInt64Type, values, indices),
t => unimplemented!("Take not supported for dictionary key type {:?}", t),
},
DataType::Binary => {
let values = values
.as_any()
.downcast_ref::<GenericBinaryArray<i32>>()
.unwrap();
Ok(Arc::new(take_binary(values, indices)?))
}
DataType::LargeBinary => {
let values = values
.as_any()
.downcast_ref::<GenericBinaryArray<i64>>()
.unwrap();
Ok(Arc::new(take_binary(values, indices)?))
}
DataType::FixedSizeBinary(_) => {
let values = values
.as_any()
.downcast_ref::<FixedSizeBinaryArray>()
.unwrap();
Ok(Arc::new(take_fixed_size_binary(values, indices)?))
}
DataType::Null => {
// Take applied to a null array produces a null array.
if values.len() >= indices.len() {
// If the existing null array is as big as the indices, we can use a slice of it
// to avoid allocating a new null array.
Ok(values.slice(0, indices.len()))
} else {
// If the existing null array isn't big enough, create a new one.
Ok(new_null_array(&DataType::Null, indices.len()))
}
}
t => unimplemented!("Take not supported for data type {:?}", t),
}
}
/// Options that define how `take` should behave
#[derive(Clone, Debug, Default)]
pub struct TakeOptions {
/// Perform bounds check before taking indices from values.
/// If enabled, an `ArrowError` is returned if the indices are out of bounds.
/// If not enabled, and indices exceed bounds, the kernel will panic.
pub check_bounds: bool,
}
#[inline(always)]
fn maybe_usize<I: ArrowNativeType>(index: I) -> Result<usize> {
index
.to_usize()
.ok_or_else(|| ArrowError::ComputeError("Cast to usize failed".to_string()))
}
// take implementation when neither values nor indices contain nulls
fn take_no_nulls<T, I>(values: &[T], indices: &[I]) -> Result<(Buffer, Option<Buffer>)>
where
T: ArrowNativeType,
I: ArrowNativeType,
{
let values = indices
.iter()
.map(|index| Result::Ok(values[maybe_usize::<I>(*index)?]));
// Soundness: `slice.map` is `TrustedLen`.
let buffer = unsafe { Buffer::try_from_trusted_len_iter(values)? };
Ok((buffer, None))
}
// take implementation when only values contain nulls
fn take_values_nulls<T, I>(
values: &PrimitiveArray<T>,
indices: &[I],
) -> Result<(Buffer, Option<Buffer>)>
where
T: ArrowPrimitiveType,
I: ArrowNativeType,
{
take_values_nulls_inner(values.data(), values.values(), indices)
}
fn take_values_nulls_inner<T, I>(
values_data: &ArrayData,
values: &[T],
indices: &[I],
) -> Result<(Buffer, Option<Buffer>)>
where
T: ArrowNativeType,
I: ArrowNativeType,
{
let num_bytes = bit_util::ceil(indices.len(), 8);
let mut nulls = MutableBuffer::new(num_bytes).with_bitset(num_bytes, true);
let null_slice = nulls.as_slice_mut();
let mut null_count = 0;
let values = indices.iter().enumerate().map(|(i, index)| {
let index = maybe_usize::<I>(*index)?;
if values_data.is_null(index) {
null_count += 1;
bit_util::unset_bit(null_slice, i);
}
Result::Ok(values[index])
});
// Soundness: `slice.map` is `TrustedLen`.
let buffer = unsafe { Buffer::try_from_trusted_len_iter(values)? };
let nulls = if null_count == 0 {
// if only non-null values were taken
None
} else {
Some(nulls.into())
};
Ok((buffer, nulls))
}
// take implementation when only indices contain nulls
fn take_indices_nulls<T, I>(
values: &[T],
indices: &PrimitiveArray<I>,
) -> Result<(Buffer, Option<Buffer>)>
where
T: ArrowNativeType,
I: ArrowNumericType,
I::Native: ToPrimitive,
{
take_indices_nulls_inner(values, indices.values(), indices.data())
}
fn take_indices_nulls_inner<T, I>(
values: &[T],
indices: &[I],
indices_data: &ArrayData,
) -> Result<(Buffer, Option<Buffer>)>
where
T: ArrowNativeType,
I: ArrowNativeType,
{
let values = indices.iter().map(|index| {
let index = maybe_usize::<I>(*index)?;
Result::Ok(match values.get(index) {
Some(value) => *value,
None => {
if indices_data.is_null(index) {
T::default()
} else {
panic!("Out-of-bounds index {}", index)
}
}
})
});
// Soundness: `slice.map` is `TrustedLen`.
let buffer = unsafe { Buffer::try_from_trusted_len_iter(values)? };
Ok((
buffer,
indices_data
.null_buffer()
.map(|b| b.bit_slice(indices_data.offset(), indices.len())),
))
}
// take implementation when both values and indices contain nulls
fn take_values_indices_nulls<T, I>(
values: &PrimitiveArray<T>,
indices: &PrimitiveArray<I>,
) -> Result<(Buffer, Option<Buffer>)>
where
T: ArrowPrimitiveType,
I: ArrowNumericType,
I::Native: ToPrimitive,
{
take_values_indices_nulls_inner(
values.values(),
values.data(),
indices.values(),
indices.data(),
)
}
fn take_values_indices_nulls_inner<T, I>(
values: &[T],
values_data: &ArrayData,
indices: &[I],
indices_data: &ArrayData,
) -> Result<(Buffer, Option<Buffer>)>
where
T: ArrowNativeType,
I: ArrowNativeType,
{
let num_bytes = bit_util::ceil(indices.len(), 8);
let mut nulls = MutableBuffer::new(num_bytes).with_bitset(num_bytes, true);
let null_slice = nulls.as_slice_mut();
let mut null_count = 0;
let values = indices.iter().enumerate().map(|(i, &index)| {
if indices_data.is_null(i) {
null_count += 1;
bit_util::unset_bit(null_slice, i);
Ok(T::default())
} else {
let index = maybe_usize::<I>(index)?;
if values_data.is_null(index) {
null_count += 1;
bit_util::unset_bit(null_slice, i);
}
Result::Ok(values[index])
}
});
// Soundness: `slice.map` is `TrustedLen`.
let buffer = unsafe { Buffer::try_from_trusted_len_iter(values)? };
let nulls = if null_count == 0 {
// if only non-null values were taken
None
} else {
Some(nulls.into())
};
Ok((buffer, nulls))
}
/// `take` implementation for decimal arrays
fn take_decimal128<IndexType>(
decimal_values: &DecimalArray,
indices: &PrimitiveArray<IndexType>,
) -> Result<DecimalArray>
where
IndexType: ArrowNumericType,
IndexType::Native: ToPrimitive,
{
indices
.iter()
.map(|index| {
// Use type annotations below for readability (was blowing
// my mind otherwise)
let t: Option<Result<Option<_>>> = index.map(|index| {
let index = ToPrimitive::to_usize(&index).ok_or_else(|| {
ArrowError::ComputeError("Cast to usize failed".to_string())
})?;
if decimal_values.is_null(index) {
Ok(None)
} else {
Ok(Some(decimal_values.value(index).as_i128()))
}
});
let t: Result<Option<Option<_>>> = t.transpose();
let t: Result<Option<_>> = t.map(|t| t.flatten());
t
})
.collect::<Result<DecimalArray>>()?
// PERF: we could avoid re-validating that the data in
// DecimalArray was in range as we know it came from a valid DecimalArray
.with_precision_and_scale(decimal_values.precision(), decimal_values.scale())
}
/// `take` implementation for all primitive arrays
///
/// This checks if an `indices` slot is populated, and gets the value from `values`
/// as the populated index.
/// If the `indices` slot is null, a null value is returned.
/// For example, given:
/// values: [1, 2, 3, null, 5]
/// indices: [0, null, 4, 3]
/// The result is: [1 (slot 0), null (null slot), 5 (slot 4), null (slot 3)]
fn take_primitive<T, I>(
values: &PrimitiveArray<T>,
indices: &PrimitiveArray<I>,
) -> Result<PrimitiveArray<T>>
where
T: ArrowPrimitiveType,
I: ArrowNumericType,
I::Native: ToPrimitive,
{
let indices_has_nulls = indices.null_count() > 0;
let values_has_nulls = values.null_count() > 0;
// note: this function should only panic when "an index is not null and out of bounds".
// if the index is null, its value is undefined and therefore we should not read from it.
let (buffer, nulls) = match (values_has_nulls, indices_has_nulls) {
(false, false) => {
// * no nulls
// * all `indices.values()` are valid
take_no_nulls::<T::Native, I::Native>(values.values(), indices.values())?
}
(true, false) => {
// * nulls come from `values` alone
// * all `indices.values()` are valid
take_values_nulls::<T, I::Native>(values, indices.values())?
}
(false, true) => {
// in this branch it is unsound to read and use `index.values()`,
// as doing so is UB when they come from a null slot.
take_indices_nulls::<T::Native, I>(values.values(), indices)?
}
(true, true) => {
// in this branch it is unsound to read and use `index.values()`,
// as doing so is UB when they come from a null slot.
take_values_indices_nulls::<T, I>(values, indices)?
}
};
let data = unsafe {
ArrayData::new_unchecked(
values.data_type().clone(),
indices.len(),
None,
nulls,
0,
vec![buffer],
vec![],
)
};
Ok(PrimitiveArray::<T>::from(data))
}
/// `take` implementation for boolean arrays
fn take_boolean<IndexType>(
values: &BooleanArray,
indices: &PrimitiveArray<IndexType>,
) -> Result<BooleanArray>
where
IndexType: ArrowNumericType,
IndexType::Native: ToPrimitive,
{
let data_len = indices.len();
let num_byte = bit_util::ceil(data_len, 8);
let mut val_buf = MutableBuffer::from_len_zeroed(num_byte);
let val_slice = val_buf.as_slice_mut();
let null_count = values.null_count();
let nulls = if null_count == 0 {
(0..data_len).try_for_each::<_, Result<()>>(|i| {
let index = ToPrimitive::to_usize(&indices.value(i)).ok_or_else(|| {
ArrowError::ComputeError("Cast to usize failed".to_string())
})?;
if values.value(index) {
bit_util::set_bit(val_slice, i);
}
Ok(())
})?;
indices.data_ref().null_buffer().cloned()
} else {
let mut null_buf = MutableBuffer::new(num_byte).with_bitset(num_byte, true);
let null_slice = null_buf.as_slice_mut();
(0..data_len).try_for_each::<_, Result<()>>(|i| {
let index = ToPrimitive::to_usize(&indices.value(i)).ok_or_else(|| {
ArrowError::ComputeError("Cast to usize failed".to_string())
})?;
if values.is_null(index) {
bit_util::unset_bit(null_slice, i);
} else if values.value(index) {
bit_util::set_bit(val_slice, i);
}
Ok(())
})?;
match indices.data_ref().null_buffer() {
Some(buffer) => Some(buffer_bin_and(
buffer,
indices.offset(),
&null_buf.into(),
0,
indices.len(),
)),
None => Some(null_buf.into()),
}
};
let data = unsafe {
ArrayData::new_unchecked(
DataType::Boolean,
indices.len(),
None,
nulls,
0,
vec![val_buf.into()],
vec![],
)
};
Ok(BooleanArray::from(data))
}
/// `take` implementation for string arrays
fn take_string<OffsetSize, IndexType>(
array: &GenericStringArray<OffsetSize>,
indices: &PrimitiveArray<IndexType>,
) -> Result<GenericStringArray<OffsetSize>>
where
OffsetSize: Zero + AddAssign + OffsetSizeTrait,
IndexType: ArrowNumericType,
IndexType::Native: ToPrimitive,
{
let data_len = indices.len();
let bytes_offset = (data_len + 1) * std::mem::size_of::<OffsetSize>();
let mut offsets_buffer = MutableBuffer::from_len_zeroed(bytes_offset);
// Safety: the buffer is always treated as as a type of `OffsetSize` in the code below
let offsets = unsafe { offsets_buffer.typed_data_mut() };
let mut values = MutableBuffer::new(0);
let mut length_so_far = OffsetSize::zero();
offsets[0] = length_so_far;
let nulls;
if array.null_count() == 0 && indices.null_count() == 0 {
for (i, offset) in offsets.iter_mut().skip(1).enumerate() {
let index = ToPrimitive::to_usize(&indices.value(i)).ok_or_else(|| {
ArrowError::ComputeError("Cast to usize failed".to_string())
})?;
let s = array.value(index);
length_so_far += OffsetSize::from_usize(s.len()).unwrap();
values.extend_from_slice(s.as_bytes());
*offset = length_so_far;
}
nulls = None
} else if indices.null_count() == 0 {
let num_bytes = bit_util::ceil(data_len, 8);
let mut null_buf = MutableBuffer::new(num_bytes).with_bitset(num_bytes, true);
let null_slice = null_buf.as_slice_mut();
for (i, offset) in offsets.iter_mut().skip(1).enumerate() {
let index = ToPrimitive::to_usize(&indices.value(i)).ok_or_else(|| {
ArrowError::ComputeError("Cast to usize failed".to_string())
})?;
if array.is_valid(index) {
let s = array.value(index);
length_so_far += OffsetSize::from_usize(s.len()).unwrap();
values.extend_from_slice(s.as_bytes());
} else {
bit_util::unset_bit(null_slice, i);
}
*offset = length_so_far;
}
nulls = Some(null_buf.into());
} else if array.null_count() == 0 {
for (i, offset) in offsets.iter_mut().skip(1).enumerate() {
if indices.is_valid(i) {
let index =
ToPrimitive::to_usize(&indices.value(i)).ok_or_else(|| {
ArrowError::ComputeError("Cast to usize failed".to_string())
})?;
let s = array.value(index);
length_so_far += OffsetSize::from_usize(s.len()).unwrap();
values.extend_from_slice(s.as_bytes());
}
*offset = length_so_far;
}
nulls = indices.data_ref().null_buffer().cloned();
} else {
let num_bytes = bit_util::ceil(data_len, 8);
let mut null_buf = MutableBuffer::new(num_bytes).with_bitset(num_bytes, true);
let null_slice = null_buf.as_slice_mut();
for (i, offset) in offsets.iter_mut().skip(1).enumerate() {
let index = ToPrimitive::to_usize(&indices.value(i)).ok_or_else(|| {
ArrowError::ComputeError("Cast to usize failed".to_string())
})?;
if array.is_valid(index) && indices.is_valid(i) {
let s = array.value(index);
length_so_far += OffsetSize::from_usize(s.len()).unwrap();
values.extend_from_slice(s.as_bytes());
} else {
// set null bit
bit_util::unset_bit(null_slice, i);
}
*offset = length_so_far;
}
nulls = match indices.data_ref().null_buffer() {
Some(buffer) => {
Some(buffer_bin_and(buffer, 0, &null_buf.into(), 0, data_len))
}
None => Some(null_buf.into()),
};
}
let array_data =
ArrayData::builder(GenericStringArray::<OffsetSize>::get_data_type())
.len(data_len)
.add_buffer(offsets_buffer.into())
.add_buffer(values.into())
.null_bit_buffer(nulls);
let array_data = unsafe { array_data.build_unchecked() };
Ok(GenericStringArray::<OffsetSize>::from(array_data))
}
/// `take` implementation for list arrays
///
/// Calculates the index and indexed offset for the inner array,
/// applying `take` on the inner array, then reconstructing a list array
/// with the indexed offsets
fn take_list<IndexType, OffsetType>(
values: &GenericListArray<OffsetType::Native>,
indices: &PrimitiveArray<IndexType>,
) -> Result<GenericListArray<OffsetType::Native>>
where
IndexType: ArrowNumericType,
IndexType::Native: ToPrimitive,
OffsetType: ArrowNumericType,
OffsetType::Native: ToPrimitive + OffsetSizeTrait,
PrimitiveArray<OffsetType>: From<Vec<Option<OffsetType::Native>>>,
{
// TODO: Some optimizations can be done here such as if it is
// taking the whole list or a contiguous sublist
let (list_indices, offsets) =
take_value_indices_from_list::<IndexType, OffsetType>(values, indices)?;
let taken = take_impl::<OffsetType>(values.values().as_ref(), &list_indices, None)?;
// determine null count and null buffer, which are a function of `values` and `indices`
let mut null_count = 0;
let num_bytes = bit_util::ceil(indices.len(), 8);
let mut null_buf = MutableBuffer::new(num_bytes).with_bitset(num_bytes, true);
{
let null_slice = null_buf.as_slice_mut();
offsets[..].windows(2).enumerate().for_each(
|(i, window): (usize, &[OffsetType::Native])| {
if window[0] == window[1] {
// offsets are equal, slot is null
bit_util::unset_bit(null_slice, i);
null_count += 1;
}
},
);
}
let value_offsets = Buffer::from_slice_ref(&offsets);
// create a new list with taken data and computed null information
let list_data = ArrayDataBuilder::new(values.data_type().clone())
.len(indices.len())
.null_bit_buffer(Some(null_buf.into()))
.offset(0)
.add_child_data(taken.data().clone())
.add_buffer(value_offsets);
let list_data = unsafe { list_data.build_unchecked() };
Ok(GenericListArray::<OffsetType::Native>::from(list_data))
}
/// `take` implementation for `FixedSizeListArray`
///
/// Calculates the index and indexed offset for the inner array,
/// applying `take` on the inner array, then reconstructing a list array
/// with the indexed offsets
fn take_fixed_size_list<IndexType>(
values: &FixedSizeListArray,
indices: &PrimitiveArray<IndexType>,
length: <UInt32Type as ArrowPrimitiveType>::Native,
) -> Result<FixedSizeListArray>
where
IndexType: ArrowNumericType,
IndexType::Native: ToPrimitive,
{
let list_indices = take_value_indices_from_fixed_size_list(values, indices, length)?;
let taken = take_impl::<UInt32Type>(values.values().as_ref(), &list_indices, None)?;
// determine null count and null buffer, which are a function of `values` and `indices`
let num_bytes = bit_util::ceil(indices.len(), 8);
let mut null_buf = MutableBuffer::new(num_bytes).with_bitset(num_bytes, true);
let null_slice = null_buf.as_slice_mut();
for i in 0..indices.len() {
let index = ToPrimitive::to_usize(&indices.value(i)).ok_or_else(|| {
ArrowError::ComputeError("Cast to usize failed".to_string())
})?;
if !indices.is_valid(i) || values.is_null(index) {
bit_util::unset_bit(null_slice, i);
}
}
let list_data = ArrayDataBuilder::new(values.data_type().clone())
.len(indices.len())
.null_bit_buffer(Some(null_buf.into()))
.offset(0)
.add_child_data(taken.data().clone());
let list_data = unsafe { list_data.build_unchecked() };
Ok(FixedSizeListArray::from(list_data))
}
fn take_binary<IndexType, OffsetType>(
values: &GenericBinaryArray<OffsetType>,
indices: &PrimitiveArray<IndexType>,
) -> Result<GenericBinaryArray<OffsetType>>
where
OffsetType: OffsetSizeTrait,
IndexType: ArrowNumericType,
IndexType::Native: ToPrimitive,
{
let data_ref = values.data_ref();
let array_iter = indices
.values()
.iter()
.map(|idx| {
let idx = maybe_usize::<IndexType::Native>(*idx)?;
if data_ref.is_valid(idx) {
Ok(Some(values.value(idx)))
} else {
Ok(None)
}
})
.collect::<Result<Vec<_>>>()?
.into_iter();
Ok(array_iter.collect::<GenericBinaryArray<OffsetType>>())
}
fn take_fixed_size_binary<IndexType>(
values: &FixedSizeBinaryArray,
indices: &PrimitiveArray<IndexType>,
) -> Result<FixedSizeBinaryArray>
where
IndexType: ArrowNumericType,
IndexType::Native: ToPrimitive,
{
let data_ref = values.data_ref();
let array_iter = indices
.values()
.iter()
.map(|idx| {
let idx = maybe_usize::<IndexType::Native>(*idx)?;
if data_ref.is_valid(idx) {
Ok(Some(values.value(idx)))
} else {
Ok(None)
}
})
.collect::<Result<Vec<_>>>()?
.into_iter();
FixedSizeBinaryArray::try_from_sparse_iter(array_iter)
}
/// `take` implementation for dictionary arrays
///
/// applies `take` to the keys of the dictionary array and returns a new dictionary array
/// with the same dictionary values and reordered keys
fn take_dict<T, I>(
values: &DictionaryArray<T>,
indices: &PrimitiveArray<I>,
) -> Result<DictionaryArray<T>>
where
T: ArrowPrimitiveType,
T::Native: num::Num,
I: ArrowNumericType,
I::Native: ToPrimitive,
{
let new_keys = take_primitive::<T, I>(values.keys(), indices)?;
let new_keys_data = new_keys.data_ref();
let data = unsafe {
ArrayData::new_unchecked(
values.data_type().clone(),
new_keys.len(),
Some(new_keys_data.null_count()),
new_keys_data.null_buffer().cloned(),
0,
new_keys_data.buffers().to_vec(),
values.data().child_data().to_vec(),
)
};
Ok(DictionaryArray::<T>::from(data))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::compute::util::tests::build_fixed_size_list_nullable;
fn test_take_decimal_arrays(
data: Vec<Option<i128>>,
index: &UInt32Array,
options: Option<TakeOptions>,
expected_data: Vec<Option<i128>>,
precision: &usize,
scale: &usize,
) -> Result<()> {
let output = data
.into_iter()
.collect::<DecimalArray>()
.with_precision_and_scale(*precision, *scale)
.unwrap();
let expected = expected_data
.into_iter()
.collect::<DecimalArray>()
.with_precision_and_scale(*precision, *scale)
.unwrap();
let expected = Arc::new(expected) as ArrayRef;
let output = take(&output, index, options).unwrap();
assert_eq!(&output, &expected);
Ok(())
}