-
Notifications
You must be signed in to change notification settings - Fork 851
/
Copy pathsort.rs
4468 lines (4199 loc) · 140 KB
/
sort.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 sort kernel for `ArrayRef`
use crate::ord::{build_compare, DynComparator};
use arrow_array::builder::BufferBuilder;
use arrow_array::cast::*;
use arrow_array::types::*;
use arrow_array::*;
use arrow_buffer::{ArrowNativeType, MutableBuffer, NullBuffer};
use arrow_data::ArrayData;
use arrow_data::ArrayDataBuilder;
use arrow_schema::{ArrowError, DataType, IntervalUnit, TimeUnit};
use arrow_select::take::take;
use std::cmp::Ordering;
use std::sync::Arc;
pub use arrow_schema::SortOptions;
/// Sort the `ArrayRef` using `SortOptions`.
///
/// Performs a sort on values and indices. Nulls are ordered according
/// to the `nulls_first` flag in `options`. Floats are sorted using
/// IEEE 754 totalOrder
///
/// Returns an `ArrowError::ComputeError(String)` if the array type is
/// either unsupported by `sort_to_indices` or `take`.
///
/// Note: this is an unstable_sort, meaning it may not preserve the
/// order of equal elements.
///
/// # Example
/// ```rust
/// # use std::sync::Arc;
/// # use arrow_array::Int32Array;
/// # use arrow_ord::sort::sort;
/// let array = Int32Array::from(vec![5, 4, 3, 2, 1]);
/// let sorted_array = sort(&array, None).unwrap();
/// assert_eq!(sorted_array.as_ref(), &Int32Array::from(vec![1, 2, 3, 4, 5]));
/// ```
pub fn sort(
values: &dyn Array,
options: Option<SortOptions>,
) -> Result<ArrayRef, ArrowError> {
if let DataType::RunEndEncoded(_, _) = values.data_type() {
return sort_run(values, options, None);
}
let indices = sort_to_indices(values, options, None)?;
take(values, &indices, None)
}
/// Sort the `ArrayRef` partially.
///
/// If `limit` is specified, the resulting array will contain only
/// first `limit` in the sort order. Any data data after the limit
/// will be discarded.
///
/// Note: this is an unstable_sort, meaning it may not preserve the
/// order of equal elements.
///
/// # Example
/// ```rust
/// # use std::sync::Arc;
/// # use arrow_array::Int32Array;
/// # use arrow_ord::sort::{sort_limit, SortOptions};
/// let array = Int32Array::from(vec![5, 4, 3, 2, 1]);
///
/// // Find the the top 2 items
/// let sorted_array = sort_limit(&array, None, Some(2)).unwrap();
/// assert_eq!(sorted_array.as_ref(), &Int32Array::from(vec![1, 2]));
///
/// // Find the bottom top 2 items
/// let options = Some(SortOptions {
/// descending: true,
/// ..Default::default()
/// });
/// let sorted_array = sort_limit(&array, options, Some(2)).unwrap();
/// assert_eq!(sorted_array.as_ref(), &Int32Array::from(vec![5, 4]));
/// ```
pub fn sort_limit(
values: &dyn Array,
options: Option<SortOptions>,
limit: Option<usize>,
) -> Result<ArrayRef, ArrowError> {
if let DataType::RunEndEncoded(_, _) = values.data_type() {
return sort_run(values, options, limit);
}
let indices = sort_to_indices(values, options, limit)?;
take(values, &indices, None)
}
/// we can only do this if the T is primitive
#[inline]
fn sort_unstable_by<T, F>(array: &mut [T], limit: usize, cmp: F)
where
F: FnMut(&T, &T) -> Ordering,
{
if array.len() == limit {
array.sort_unstable_by(cmp);
} else {
partial_sort(array, limit, cmp);
}
}
fn cmp<T>(l: T, r: T) -> Ordering
where
T: Ord,
{
l.cmp(&r)
}
// partition indices into valid and null indices
fn partition_validity(array: &dyn Array) -> (Vec<u32>, Vec<u32>) {
match array.null_count() {
// faster path
0 => ((0..(array.len() as u32)).collect(), vec![]),
_ => {
let indices = 0..(array.len() as u32);
indices.partition(|index| array.is_valid(*index as usize))
}
}
}
/// Sort elements from `ArrayRef` into an unsigned integer (`UInt32Array`) of indices.
/// For floating point arrays any NaN values are considered to be greater than any other non-null value.
/// `limit` is an option for [partial_sort].
pub fn sort_to_indices(
values: &dyn Array,
options: Option<SortOptions>,
limit: Option<usize>,
) -> Result<UInt32Array, ArrowError> {
let options = options.unwrap_or_default();
let (v, n) = partition_validity(values);
Ok(match values.data_type() {
DataType::Decimal128(_, _) => {
sort_primitive::<Decimal128Type, _>(values, v, n, cmp, &options, limit)
}
DataType::Decimal256(_, _) => {
sort_primitive::<Decimal256Type, _>(values, v, n, cmp, &options, limit)
}
DataType::Boolean => sort_boolean(values, v, n, &options, limit),
DataType::Int8 => {
sort_primitive::<Int8Type, _>(values, v, n, cmp, &options, limit)
}
DataType::Int16 => {
sort_primitive::<Int16Type, _>(values, v, n, cmp, &options, limit)
}
DataType::Int32 => {
sort_primitive::<Int32Type, _>(values, v, n, cmp, &options, limit)
}
DataType::Int64 => {
sort_primitive::<Int64Type, _>(values, v, n, cmp, &options, limit)
}
DataType::UInt8 => {
sort_primitive::<UInt8Type, _>(values, v, n, cmp, &options, limit)
}
DataType::UInt16 => {
sort_primitive::<UInt16Type, _>(values, v, n, cmp, &options, limit)
}
DataType::UInt32 => {
sort_primitive::<UInt32Type, _>(values, v, n, cmp, &options, limit)
}
DataType::UInt64 => {
sort_primitive::<UInt64Type, _>(values, v, n, cmp, &options, limit)
}
DataType::Float16 => sort_primitive::<Float16Type, _>(
values,
v,
n,
|x, y| x.total_cmp(&y),
&options,
limit,
),
DataType::Float32 => sort_primitive::<Float32Type, _>(
values,
v,
n,
|x, y| x.total_cmp(&y),
&options,
limit,
),
DataType::Float64 => sort_primitive::<Float64Type, _>(
values,
v,
n,
|x, y| x.total_cmp(&y),
&options,
limit,
),
DataType::Date32 => {
sort_primitive::<Date32Type, _>(values, v, n, cmp, &options, limit)
}
DataType::Date64 => {
sort_primitive::<Date64Type, _>(values, v, n, cmp, &options, limit)
}
DataType::Time32(TimeUnit::Second) => {
sort_primitive::<Time32SecondType, _>(values, v, n, cmp, &options, limit)
}
DataType::Time32(TimeUnit::Millisecond) => {
sort_primitive::<Time32MillisecondType, _>(values, v, n, cmp, &options, limit)
}
DataType::Time64(TimeUnit::Microsecond) => {
sort_primitive::<Time64MicrosecondType, _>(values, v, n, cmp, &options, limit)
}
DataType::Time64(TimeUnit::Nanosecond) => {
sort_primitive::<Time64NanosecondType, _>(values, v, n, cmp, &options, limit)
}
DataType::Timestamp(TimeUnit::Second, _) => {
sort_primitive::<TimestampSecondType, _>(values, v, n, cmp, &options, limit)
}
DataType::Timestamp(TimeUnit::Millisecond, _) => {
sort_primitive::<TimestampMillisecondType, _>(
values, v, n, cmp, &options, limit,
)
}
DataType::Timestamp(TimeUnit::Microsecond, _) => {
sort_primitive::<TimestampMicrosecondType, _>(
values, v, n, cmp, &options, limit,
)
}
DataType::Timestamp(TimeUnit::Nanosecond, _) => {
sort_primitive::<TimestampNanosecondType, _>(
values, v, n, cmp, &options, limit,
)
}
DataType::Interval(IntervalUnit::YearMonth) => {
sort_primitive::<IntervalYearMonthType, _>(values, v, n, cmp, &options, limit)
}
DataType::Interval(IntervalUnit::DayTime) => {
sort_primitive::<IntervalDayTimeType, _>(values, v, n, cmp, &options, limit)
}
DataType::Interval(IntervalUnit::MonthDayNano) => {
sort_primitive::<IntervalMonthDayNanoType, _>(
values, v, n, cmp, &options, limit,
)
}
DataType::Duration(TimeUnit::Second) => {
sort_primitive::<DurationSecondType, _>(values, v, n, cmp, &options, limit)
}
DataType::Duration(TimeUnit::Millisecond) => {
sort_primitive::<DurationMillisecondType, _>(
values, v, n, cmp, &options, limit,
)
}
DataType::Duration(TimeUnit::Microsecond) => {
sort_primitive::<DurationMicrosecondType, _>(
values, v, n, cmp, &options, limit,
)
}
DataType::Duration(TimeUnit::Nanosecond) => {
sort_primitive::<DurationNanosecondType, _>(
values, v, n, cmp, &options, limit,
)
}
DataType::Utf8 => sort_string::<i32>(values, v, n, &options, limit),
DataType::LargeUtf8 => sort_string::<i64>(values, v, n, &options, limit),
DataType::List(field) | DataType::FixedSizeList(field, _) => {
match field.data_type() {
DataType::Int8 => sort_list::<i32>(values, v, n, &options, limit),
DataType::Int16 => sort_list::<i32>(values, v, n, &options, limit),
DataType::Int32 => sort_list::<i32>(values, v, n, &options, limit),
DataType::Int64 => sort_list::<i32>(values, v, n, &options, limit),
DataType::UInt8 => sort_list::<i32>(values, v, n, &options, limit),
DataType::UInt16 => sort_list::<i32>(values, v, n, &options, limit),
DataType::UInt32 => sort_list::<i32>(values, v, n, &options, limit),
DataType::UInt64 => sort_list::<i32>(values, v, n, &options, limit),
DataType::Float16 => sort_list::<i32>(values, v, n, &options, limit),
DataType::Float32 => sort_list::<i32>(values, v, n, &options, limit),
DataType::Float64 => sort_list::<i32>(values, v, n, &options, limit),
t => {
return Err(ArrowError::ComputeError(format!(
"Sort not supported for list type {t:?}"
)));
}
}
}
DataType::LargeList(field) => match field.data_type() {
DataType::Int8 => sort_list::<i64>(values, v, n, &options, limit),
DataType::Int16 => sort_list::<i64>(values, v, n, &options, limit),
DataType::Int32 => sort_list::<i64>(values, v, n, &options, limit),
DataType::Int64 => sort_list::<i64>(values, v, n, &options, limit),
DataType::UInt8 => sort_list::<i64>(values, v, n, &options, limit),
DataType::UInt16 => sort_list::<i64>(values, v, n, &options, limit),
DataType::UInt32 => sort_list::<i64>(values, v, n, &options, limit),
DataType::UInt64 => sort_list::<i64>(values, v, n, &options, limit),
DataType::Float16 => sort_list::<i64>(values, v, n, &options, limit),
DataType::Float32 => sort_list::<i64>(values, v, n, &options, limit),
DataType::Float64 => sort_list::<i64>(values, v, n, &options, limit),
t => {
return Err(ArrowError::ComputeError(format!(
"Sort not supported for list type {t:?}"
)));
}
},
DataType::Dictionary(_, _) => {
let value_null_first = if options.descending {
// When sorting dictionary in descending order, we take inverse of of null ordering
// when sorting the values. Because if `nulls_first` is true, null must be in front
// of non-null value. As we take the sorted order of value array to sort dictionary
// keys, these null values will be treated as smallest ones and be sorted to the end
// of sorted result. So we set `nulls_first` to false when sorting dictionary value
// array to make them as largest ones, then null values will be put at the beginning
// of sorted dictionary result.
!options.nulls_first
} else {
options.nulls_first
};
let value_options = Some(SortOptions {
descending: false,
nulls_first: value_null_first,
});
downcast_dictionary_array!(
values => match values.values().data_type() {
dt if DataType::is_primitive(dt) => {
let dict_values = values.values();
let sorted_value_indices = sort_to_indices(dict_values, value_options, None)?;
let value_indices_map = sorted_rank(&sorted_value_indices);
sort_primitive_dictionary::<_, _>(values, &value_indices_map, v, n, options, limit, cmp)
},
DataType::Utf8 => {
let dict_values = values.values();
let sorted_value_indices = sort_to_indices(dict_values, value_options, None)?;
let value_indices_map = sorted_rank(&sorted_value_indices);
sort_string_dictionary::<_>(values, &value_indices_map, v, n, &options, limit)
},
t => return Err(ArrowError::ComputeError(format!(
"Unsupported dictionary value type {t}"
))),
},
t => return Err(ArrowError::ComputeError(format!(
"Unsupported datatype {t}"
))),
)
}
DataType::Binary | DataType::FixedSizeBinary(_) => {
sort_binary::<i32>(values, v, n, &options, limit)
}
DataType::LargeBinary => sort_binary::<i64>(values, v, n, &options, limit),
DataType::RunEndEncoded(run_ends_field, _) => match run_ends_field.data_type() {
DataType::Int16 => sort_run_to_indices::<Int16Type>(values, &options, limit),
DataType::Int32 => sort_run_to_indices::<Int32Type>(values, &options, limit),
DataType::Int64 => sort_run_to_indices::<Int64Type>(values, &options, limit),
dt => {
return Err(ArrowError::ComputeError(format!(
"Invalid run end data type: {dt}"
)))
}
},
t => {
return Err(ArrowError::ComputeError(format!(
"Sort not supported for data type {t:?}"
)));
}
})
}
/// Sort boolean values
///
/// when a limit is present, the sort is pair-comparison based as k-select might be more efficient,
/// when the limit is absent, binary partition is used to speed up (which is linear).
///
/// TODO maybe partition_validity call can be eliminated in this case
/// and [tri-color sort](https://en.wikipedia.org/wiki/Dutch_national_flag_problem)
/// can be used instead.
fn sort_boolean(
values: &dyn Array,
value_indices: Vec<u32>,
mut null_indices: Vec<u32>,
options: &SortOptions,
limit: Option<usize>,
) -> UInt32Array {
let values = values
.as_any()
.downcast_ref::<BooleanArray>()
.expect("Unable to downcast to boolean array");
let descending = options.descending;
let valids_len = value_indices.len();
let nulls_len = null_indices.len();
let mut len = values.len();
let valids = if let Some(limit) = limit {
len = limit.min(len);
// create tuples that are used for sorting
let mut valids = value_indices
.into_iter()
.map(|index| (index, values.value(index as usize)))
.collect::<Vec<(u32, bool)>>();
sort_valids(descending, &mut valids, &mut null_indices, len, cmp);
valids
} else {
// when limit is not present, we have a better way than sorting: we can just partition
// the vec into [false..., true...] or [true..., false...] when descending
// TODO when https://github.com/rust-lang/rust/issues/62543 is merged we can use partition_in_place
let (mut a, b): (Vec<_>, Vec<_>) = value_indices
.into_iter()
.map(|index| (index, values.value(index as usize)))
.partition(|(_, value)| *value == descending);
a.extend(b);
if descending {
null_indices.reverse();
}
a
};
let nulls = null_indices;
// collect results directly into a buffer instead of a vec to avoid another aligned allocation
let result_capacity = len * std::mem::size_of::<u32>();
let mut result = MutableBuffer::new(result_capacity);
// sets len to capacity so we can access the whole buffer as a typed slice
result.resize(result_capacity, 0);
let result_slice: &mut [u32] = result.typed_data_mut();
if options.nulls_first {
let size = nulls_len.min(len);
result_slice[0..size].copy_from_slice(&nulls[0..size]);
if nulls_len < len {
insert_valid_values(result_slice, nulls_len, &valids[0..len - size]);
}
} else {
// nulls last
let size = valids.len().min(len);
insert_valid_values(result_slice, 0, &valids[0..size]);
if len > size {
result_slice[valids_len..].copy_from_slice(&nulls[0..(len - valids_len)]);
}
}
let result_data = unsafe {
ArrayData::new_unchecked(
DataType::UInt32,
len,
Some(0),
None,
0,
vec![result.into()],
vec![],
)
};
UInt32Array::from(result_data)
}
/// Sort primitive values
fn sort_primitive<T, F>(
values: &dyn Array,
value_indices: Vec<u32>,
null_indices: Vec<u32>,
cmp: F,
options: &SortOptions,
limit: Option<usize>,
) -> UInt32Array
where
T: ArrowPrimitiveType,
T::Native: PartialOrd,
F: Fn(T::Native, T::Native) -> Ordering,
{
// create tuples that are used for sorting
let valids = {
let values = values.as_primitive::<T>();
value_indices
.into_iter()
.map(|index| (index, values.value(index as usize)))
.collect::<Vec<(u32, T::Native)>>()
};
sort_primitive_inner(values.len(), null_indices, cmp, options, limit, valids)
}
/// Given a list of indices that yield a sorted order, returns the ordered
/// rank of each index
///
/// e.g. [2, 4, 3, 1, 0] -> [4, 3, 0, 2, 1]
fn sorted_rank(sorted_value_indices: &UInt32Array) -> Vec<u32> {
assert_eq!(sorted_value_indices.null_count(), 0);
let sorted_indices = sorted_value_indices.values();
let mut out: Vec<_> = vec![0_u32; sorted_indices.len()];
for (ix, val) in sorted_indices.iter().enumerate() {
out[*val as usize] = ix as u32;
}
out
}
/// Sort dictionary encoded primitive values
fn sort_primitive_dictionary<K, F>(
values: &DictionaryArray<K>,
value_indices_map: &[u32],
value_indices: Vec<u32>,
null_indices: Vec<u32>,
options: SortOptions,
limit: Option<usize>,
cmp: F,
) -> UInt32Array
where
K: ArrowDictionaryKeyType,
F: Fn(u32, u32) -> Ordering,
{
let keys: &PrimitiveArray<K> = values.keys();
// create tuples that are used for sorting
let valids = value_indices
.into_iter()
.map(|index| {
let key: K::Native = keys.value(index as usize);
(index, value_indices_map[key.as_usize()])
})
.collect::<Vec<(u32, u32)>>();
sort_primitive_inner::<_, _>(keys.len(), null_indices, cmp, &options, limit, valids)
}
// sort is instantiated a lot so we only compile this inner version for each native type
fn sort_primitive_inner<T, F>(
value_len: usize,
null_indices: Vec<u32>,
cmp: F,
options: &SortOptions,
limit: Option<usize>,
mut valids: Vec<(u32, T)>,
) -> UInt32Array
where
T: ArrowNativeType,
T: PartialOrd,
F: Fn(T, T) -> Ordering,
{
let mut nulls = null_indices;
let valids_len = valids.len();
let nulls_len = nulls.len();
let mut len = value_len;
if let Some(limit) = limit {
len = limit.min(len);
}
sort_valids(options.descending, &mut valids, &mut nulls, len, cmp);
// collect results directly into a buffer instead of a vec to avoid another aligned allocation
let result_capacity = len * std::mem::size_of::<u32>();
let mut result = MutableBuffer::new(result_capacity);
// sets len to capacity so we can access the whole buffer as a typed slice
result.resize(result_capacity, 0);
let result_slice: &mut [u32] = result.typed_data_mut();
if options.nulls_first {
let size = nulls_len.min(len);
result_slice[0..size].copy_from_slice(&nulls[0..size]);
if nulls_len < len {
insert_valid_values(result_slice, nulls_len, &valids[0..len - size]);
}
} else {
// nulls last
let size = valids.len().min(len);
insert_valid_values(result_slice, 0, &valids[0..size]);
if len > size {
result_slice[valids_len..].copy_from_slice(&nulls[0..(len - valids_len)]);
}
}
let result_data = unsafe {
ArrayData::new_unchecked(
DataType::UInt32,
len,
Some(0),
None,
0,
vec![result.into()],
vec![],
)
};
UInt32Array::from(result_data)
}
// insert valid and nan values in the correct order depending on the descending flag
fn insert_valid_values<T>(result_slice: &mut [u32], offset: usize, valids: &[(u32, T)]) {
let valids_len = valids.len();
// helper to append the index part of the valid tuples
let append_valids = move |dst_slice: &mut [u32]| {
debug_assert_eq!(dst_slice.len(), valids_len);
dst_slice
.iter_mut()
.zip(valids.iter())
.for_each(|(dst, src)| *dst = src.0)
};
append_valids(&mut result_slice[offset..offset + valids.len()]);
}
// Sort run array and return sorted run array.
// The output RunArray will be encoded at the same level as input run array.
// For e.g. an input RunArray { run_ends = [2,4,6,8], values = [1,2,1,2] }
// will result in output RunArray { run_ends = [2,4,6,8], values = [1,1,2,2] }
// and not RunArray { run_ends = [4,8], values = [1,2] }
fn sort_run(
values: &dyn Array,
options: Option<SortOptions>,
limit: Option<usize>,
) -> Result<ArrayRef, ArrowError> {
match values.data_type() {
DataType::RunEndEncoded(run_ends_field, _) => match run_ends_field.data_type() {
DataType::Int16 => sort_run_downcasted::<Int16Type>(values, options, limit),
DataType::Int32 => sort_run_downcasted::<Int32Type>(values, options, limit),
DataType::Int64 => sort_run_downcasted::<Int64Type>(values, options, limit),
dt => unreachable!("Not valid run ends data type {dt}"),
},
dt => Err(ArrowError::InvalidArgumentError(format!(
"Input is not a run encoded array. Input data type {dt}"
))),
}
}
fn sort_run_downcasted<R: RunEndIndexType>(
values: &dyn Array,
options: Option<SortOptions>,
limit: Option<usize>,
) -> Result<ArrayRef, ArrowError> {
let run_array = values.as_any().downcast_ref::<RunArray<R>>().unwrap();
// Determine the length of output run array.
let output_len = if let Some(limit) = limit {
limit.min(run_array.len())
} else {
run_array.len()
};
let run_ends = run_array.run_ends();
let mut new_run_ends_builder = BufferBuilder::<R::Native>::new(run_ends.len());
let mut new_run_end: usize = 0;
let mut new_physical_len: usize = 0;
let consume_runs = |run_length, _| {
new_run_end += run_length;
new_physical_len += 1;
new_run_ends_builder.append(R::Native::from_usize(new_run_end).unwrap());
};
let (values_indices, run_values) =
sort_run_inner(run_array, options, output_len, consume_runs);
let new_run_ends = unsafe {
// Safety:
// The function builds a valid run_ends array and hence need not be validated.
ArrayDataBuilder::new(R::DATA_TYPE)
.len(new_physical_len)
.add_buffer(new_run_ends_builder.finish())
.build_unchecked()
};
// slice the sorted value indices based on limit.
let new_values_indices: PrimitiveArray<UInt32Type> = values_indices
.slice(0, new_run_ends.len())
.into_data()
.into();
let new_values = take(&run_values, &new_values_indices, None)?;
// Build sorted run array
let builder = ArrayDataBuilder::new(run_array.data_type().clone())
.len(new_run_end)
.add_child_data(new_run_ends)
.add_child_data(new_values.into_data());
let array_data: RunArray<R> = unsafe {
// Safety:
// This function builds a valid run array and hence can skip validation.
builder.build_unchecked().into()
};
Ok(Arc::new(array_data))
}
// Sort to indices for run encoded array.
// This function will be slow for run array as it decodes the physical indices to
// logical indices and to get the run array back, the logical indices has to be
// encoded back to run array.
fn sort_run_to_indices<R: RunEndIndexType>(
values: &dyn Array,
options: &SortOptions,
limit: Option<usize>,
) -> UInt32Array {
let run_array = values.as_any().downcast_ref::<RunArray<R>>().unwrap();
let output_len = if let Some(limit) = limit {
limit.min(run_array.len())
} else {
run_array.len()
};
let mut result: Vec<u32> = Vec::with_capacity(output_len);
//Add all logical indices belonging to a physical index to the output
let consume_runs = |run_length, logical_start| {
result.extend(logical_start as u32..(logical_start + run_length) as u32);
};
sort_run_inner(run_array, Some(*options), output_len, consume_runs);
UInt32Array::from(result)
}
fn sort_run_inner<R: RunEndIndexType, F>(
run_array: &RunArray<R>,
options: Option<SortOptions>,
output_len: usize,
mut consume_runs: F,
) -> (PrimitiveArray<UInt32Type>, ArrayRef)
where
F: FnMut(usize, usize),
{
// slice the run_array.values based on offset and length.
let start_physical_index = run_array.get_start_physical_index();
let end_physical_index = run_array.get_end_physical_index();
let physical_len = end_physical_index - start_physical_index + 1;
let run_values = run_array.values().slice(start_physical_index, physical_len);
// All the values have to be sorted irrespective of input limit.
let values_indices = sort_to_indices(&run_values, options, None).unwrap();
let mut remaining_len = output_len;
let run_ends = run_array.run_ends().values();
assert_eq!(
0,
values_indices.null_count(),
"The output of sort_to_indices should not have null values. Its values is {}",
values_indices.null_count()
);
// Calculate `run length` of sorted value indices.
// Find the `logical index` at which the run starts.
// Call the consumer using the run length and starting logical index.
for physical_index in values_indices.values() {
// As the values were sliced with offset = start_physical_index, it has to be added back
// before accessing `RunArray::run_ends`
let physical_index = *physical_index as usize + start_physical_index;
// calculate the run length and logical index of sorted values
let (run_length, logical_index_start) = unsafe {
// Safety:
// The index will be within bounds as its in bounds of start_physical_index
// and len, both of which are within bounds of run_array
if physical_index == start_physical_index {
(
run_ends.get_unchecked(physical_index).as_usize()
- run_array.offset(),
0,
)
} else if physical_index == end_physical_index {
let prev_run_end = run_ends.get_unchecked(physical_index - 1).as_usize();
(
run_array.offset() + run_array.len() - prev_run_end,
prev_run_end - run_array.offset(),
)
} else {
let prev_run_end = run_ends.get_unchecked(physical_index - 1).as_usize();
(
run_ends.get_unchecked(physical_index).as_usize() - prev_run_end,
prev_run_end - run_array.offset(),
)
}
};
let new_run_length = run_length.min(remaining_len);
consume_runs(new_run_length, logical_index_start);
remaining_len -= new_run_length;
if remaining_len == 0 {
break;
}
}
if remaining_len > 0 {
panic!("Remaining length should be zero its values is {remaining_len}")
}
(values_indices, run_values)
}
/// Sort strings
fn sort_string<Offset: OffsetSizeTrait>(
values: &dyn Array,
value_indices: Vec<u32>,
null_indices: Vec<u32>,
options: &SortOptions,
limit: Option<usize>,
) -> UInt32Array {
let values = values
.as_any()
.downcast_ref::<GenericStringArray<Offset>>()
.unwrap();
sort_string_helper(
values,
value_indices,
null_indices,
options,
limit,
|array, idx| array.value(idx as usize),
)
}
/// Sort dictionary encoded strings
fn sort_string_dictionary<T: ArrowDictionaryKeyType>(
values: &DictionaryArray<T>,
value_indices_map: &[u32],
value_indices: Vec<u32>,
null_indices: Vec<u32>,
options: &SortOptions,
limit: Option<usize>,
) -> UInt32Array {
let keys: &PrimitiveArray<T> = values.keys();
// create tuples that are used for sorting
let valids = value_indices
.into_iter()
.map(|index| {
let key: T::Native = keys.value(index as usize);
(index, value_indices_map[key.as_usize()])
})
.collect::<Vec<(u32, u32)>>();
sort_primitive_inner::<_, _>(keys.len(), null_indices, cmp, options, limit, valids)
}
/// shared implementation between dictionary encoded and plain string arrays
#[inline]
fn sort_string_helper<'a, A: Array, F>(
values: &'a A,
value_indices: Vec<u32>,
null_indices: Vec<u32>,
options: &SortOptions,
limit: Option<usize>,
value_fn: F,
) -> UInt32Array
where
F: Fn(&'a A, u32) -> &str,
{
let mut valids = value_indices
.into_iter()
.map(|index| (index, value_fn(values, index)))
.collect::<Vec<(u32, &str)>>();
let mut nulls = null_indices;
let descending = options.descending;
let mut len = values.len();
if let Some(limit) = limit {
len = limit.min(len);
}
sort_valids(descending, &mut valids, &mut nulls, len, cmp);
// collect the order of valid tuplies
let mut valid_indices: Vec<u32> = valids.iter().map(|tuple| tuple.0).collect();
if options.nulls_first {
nulls.append(&mut valid_indices);
nulls.truncate(len);
UInt32Array::from(nulls)
} else {
// no need to sort nulls as they are in the correct order already
valid_indices.append(&mut nulls);
valid_indices.truncate(len);
UInt32Array::from(valid_indices)
}
}
fn sort_list<S>(
values: &dyn Array,
value_indices: Vec<u32>,
null_indices: Vec<u32>,
options: &SortOptions,
limit: Option<usize>,
) -> UInt32Array
where
S: OffsetSizeTrait,
{
sort_list_inner::<S>(values, value_indices, null_indices, options, limit)
}
fn sort_list_inner<S>(
values: &dyn Array,
value_indices: Vec<u32>,
mut null_indices: Vec<u32>,
options: &SortOptions,
limit: Option<usize>,
) -> UInt32Array
where
S: OffsetSizeTrait,
{
let mut valids: Vec<(u32, ArrayRef)> = values
.as_any()
.downcast_ref::<FixedSizeListArray>()
.map_or_else(
|| {
let values = as_generic_list_array::<S>(values);
value_indices
.iter()
.copied()
.map(|index| (index, values.value(index as usize)))
.collect()
},
|values| {
value_indices
.iter()
.copied()
.map(|index| (index, values.value(index as usize)))
.collect()
},
);
let mut len = values.len();
let descending = options.descending;
if let Some(limit) = limit {
len = limit.min(len);
}
sort_valids_array(descending, &mut valids, &mut null_indices, len);
let mut valid_indices: Vec<u32> = valids.iter().map(|tuple| tuple.0).collect();
if options.nulls_first {
null_indices.append(&mut valid_indices);
null_indices.truncate(len);
UInt32Array::from(null_indices)
} else {
valid_indices.append(&mut null_indices);
valid_indices.truncate(len);
UInt32Array::from(valid_indices)
}
}
fn sort_binary<S>(
values: &dyn Array,
value_indices: Vec<u32>,
mut null_indices: Vec<u32>,
options: &SortOptions,
limit: Option<usize>,
) -> UInt32Array
where
S: OffsetSizeTrait,
{
let mut valids: Vec<(u32, &[u8])> = values
.as_any()
.downcast_ref::<FixedSizeBinaryArray>()
.map_or_else(
|| {
let values = as_generic_binary_array::<S>(values);
value_indices
.iter()
.copied()
.map(|index| (index, values.value(index as usize)))
.collect()
},
|values| {
value_indices
.iter()
.copied()
.map(|index| (index, values.value(index as usize)))
.collect()
},
);
let mut len = values.len();
let descending = options.descending;
if let Some(limit) = limit {
len = limit.min(len);
}
sort_valids(descending, &mut valids, &mut null_indices, len, cmp);
let mut valid_indices: Vec<u32> = valids.iter().map(|tuple| tuple.0).collect();
if options.nulls_first {
null_indices.append(&mut valid_indices);
null_indices.truncate(len);
UInt32Array::from(null_indices)
} else {
valid_indices.append(&mut null_indices);
valid_indices.truncate(len);
UInt32Array::from(valid_indices)
}
}
/// Compare two `Array`s based on the ordering defined in [build_compare]
fn cmp_array(a: &dyn Array, b: &dyn Array) -> Ordering {
let cmp_op = build_compare(a, b).unwrap();
let length = a.len().max(b.len());