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
use std::cmp::Ordering;
use crate::compute::take;
use crate::error::{Error, Result};
use crate::{
array::{ord, Array, PrimitiveArray},
types::Index,
};
use super::{sort_to_indices, SortOptions};
use crate::array::ord::DynComparator;
type IsValid = Box<dyn Fn(usize) -> bool + Send + Sync>;
#[derive(Clone, Debug)]
pub struct SortColumn<'a> {
pub values: &'a dyn Array,
pub options: Option<SortOptions>,
}
pub fn lexsort<I: Index>(
columns: &[SortColumn],
limit: Option<usize>,
) -> Result<Vec<Box<dyn Array>>> {
let indices = lexsort_to_indices::<I>(columns, limit)?;
columns
.iter()
.map(|c| take::take(c.values, &indices))
.collect()
}
#[inline]
fn build_is_valid(array: &dyn Array) -> IsValid {
if let Some(validity) = array.validity() {
let validity = validity.clone();
Box::new(move |x| unsafe { validity.get_bit_unchecked(x) })
} else {
Box::new(move |_| true)
}
}
pub(crate) fn build_compare(array: &dyn Array, sort_option: SortOptions) -> Result<DynComparator> {
build_compare_impl(array, sort_option, &ord::build_compare)
}
pub(crate) fn build_compare_impl(
array: &dyn Array,
sort_option: SortOptions,
build_compare_fn: &dyn Fn(&dyn Array, &dyn Array) -> Result<DynComparator>,
) -> Result<DynComparator> {
let is_valid = build_is_valid(array);
let comparator = build_compare_fn(array, array)?;
Ok(match (sort_option.descending, sort_option.nulls_first) {
(true, true) => Box::new(move |i: usize, j: usize| match (is_valid(i), is_valid(j)) {
(true, true) => match (comparator)(i, j) {
Ordering::Equal => Ordering::Equal,
other => other.reverse(),
},
(false, true) => Ordering::Less,
(true, false) => Ordering::Greater,
(false, false) => Ordering::Equal,
}),
(false, true) => Box::new(move |i: usize, j: usize| match (is_valid(i), is_valid(j)) {
(true, true) => match (comparator)(i, j) {
Ordering::Equal => Ordering::Equal,
other => other,
},
(false, true) => Ordering::Less,
(true, false) => Ordering::Greater,
(false, false) => Ordering::Equal,
}),
(false, false) => Box::new(move |i: usize, j: usize| match (is_valid(i), is_valid(j)) {
(true, true) => match (comparator)(i, j) {
Ordering::Equal => Ordering::Equal,
other => other,
},
(false, true) => Ordering::Greater,
(true, false) => Ordering::Less,
(false, false) => Ordering::Equal,
}),
(true, false) => Box::new(move |i: usize, j: usize| match (is_valid(i), is_valid(j)) {
(true, true) => match (comparator)(i, j) {
Ordering::Equal => Ordering::Equal,
other => other.reverse(),
},
(false, true) => Ordering::Greater,
(true, false) => Ordering::Less,
(false, false) => Ordering::Equal,
}),
})
}
pub fn lexsort_to_indices<I: Index>(
columns: &[SortColumn],
limit: Option<usize>,
) -> Result<PrimitiveArray<I>> {
lexsort_to_indices_impl(columns, limit, &ord::build_compare)
}
pub fn lexsort_to_indices_impl<I: Index>(
columns: &[SortColumn],
limit: Option<usize>,
build_compare_fn: &dyn Fn(&dyn Array, &dyn Array) -> Result<DynComparator>,
) -> Result<PrimitiveArray<I>> {
if columns.is_empty() {
return Err(Error::InvalidArgumentError(
"Sort requires at least one column".to_string(),
));
}
if columns.len() == 1 {
let column = &columns[0];
if let Ok(indices) =
sort_to_indices(column.values, &column.options.unwrap_or_default(), limit)
{
return Ok(indices);
}
}
let row_count = columns[0].values.len();
if columns.iter().any(|item| item.values.len() != row_count) {
return Err(Error::InvalidArgumentError(
"lexical sort columns have different row counts".to_string(),
));
};
let comparators = columns
.iter()
.map(|column| -> Result<DynComparator> {
build_compare_impl(
column.values,
column.options.unwrap_or_default(),
build_compare_fn,
)
})
.collect::<Result<Vec<DynComparator>>>()?;
let lex_comparator = |a_idx: &I, b_idx: &I| -> Ordering {
let a_idx = a_idx.to_usize();
let b_idx = b_idx.to_usize();
for comparator in comparators.iter() {
match comparator(a_idx, b_idx) {
Ordering::Equal => continue,
other => return other,
}
}
Ordering::Equal
};
let mut values = I::range(0, row_count).unwrap().collect::<Vec<_>>();
if let Some(limit) = limit {
let limit = limit.min(row_count);
let before = if limit < row_count {
let (before, _, _) = values.select_nth_unstable_by(limit, lex_comparator);
before
} else {
&mut values[..]
};
before.sort_unstable_by(lex_comparator);
values.truncate(limit);
values.shrink_to_fit();
} else {
values.sort_unstable_by(lex_comparator);
}
let data_type = I::PRIMITIVE.into();
Ok(PrimitiveArray::<I>::new(data_type, values.into(), None))
}