1use crate::null_sentinel;
19use arrow_array::types::ByteArrayType;
20use arrow_array::*;
21use arrow_buffer::bit_util::ceil;
22use arrow_buffer::{
23 ArrowNativeType, BooleanBuffer, MutableBuffer, NullBuffer, OffsetBuffer, ScalarBuffer,
24};
25use arrow_data::MAX_INLINE_VIEW_LEN;
26use arrow_schema::SortOptions;
27use builder::make_view;
28
29pub const BLOCK_SIZE: usize = 32;
31
32pub const MINI_BLOCK_COUNT: usize = 4;
36
37pub const MINI_BLOCK_SIZE: usize = BLOCK_SIZE / MINI_BLOCK_COUNT;
39
40pub const BLOCK_CONTINUATION: u8 = 0xFF;
42
43pub const EMPTY_SENTINEL: u8 = 1;
45
46pub const NON_EMPTY_SENTINEL: u8 = 2;
48
49pub const NULL_VALUE_SENTINEL: u8 = 3;
51
52#[inline]
54pub fn padded_length(a: Option<usize>) -> usize {
55 match a {
56 Some(a) => non_null_padded_length(a),
57 None => 1,
58 }
59}
60
61#[inline]
63pub(crate) fn non_null_padded_length(len: usize) -> usize {
64 if len <= BLOCK_SIZE {
65 1 + ceil(len, MINI_BLOCK_SIZE) * (MINI_BLOCK_SIZE + 1)
66 } else {
67 MINI_BLOCK_COUNT + ceil(len, BLOCK_SIZE) * (BLOCK_SIZE + 1)
70 }
71}
72
73pub(crate) fn decode_nulls_sentinel(rows: &[&[u8]], options: SortOptions) -> Option<NullBuffer> {
76 let null_sentinel = null_sentinel(options);
77 let nulls = BooleanBuffer::collect_bool(rows.len(), |x| rows[x][0] != null_sentinel);
78 let nulls = NullBuffer::new(nulls);
79 (nulls.null_count() > 0).then_some(nulls)
80}
81
82pub fn encode<'a, I: Iterator<Item = Option<&'a [u8]>>>(
94 data: &mut [u8],
95 offsets: &mut [usize],
96 i: I,
97 opts: SortOptions,
98) {
99 for (offset, maybe_val) in offsets.iter_mut().skip(1).zip(i) {
100 *offset += encode_one(&mut data[*offset..], maybe_val, opts);
101 }
102}
103
104pub(crate) fn encode_generic_byte_array<T: ByteArrayType>(
106 data: &mut [u8],
107 offsets: &mut [usize],
108 input_array: &GenericByteArray<T>,
109 opts: SortOptions,
110) {
111 let input_offsets = input_array.value_offsets();
112 let bytes = input_array.values().as_slice();
113
114 if let Some(null_buffer) = input_array.nulls().filter(|x| x.null_count() > 0) {
115 let input_iter =
116 input_offsets
117 .windows(2)
118 .zip(null_buffer.iter())
119 .map(|(start_end, is_valid)| {
120 if is_valid {
121 let item_range = start_end[0].as_usize()..start_end[1].as_usize();
122 let item = unsafe { bytes.get_unchecked(item_range) };
125 Some(item)
126 } else {
127 None
128 }
129 });
130
131 encode(data, offsets, input_iter, opts);
132 } else {
133 let input_iter = input_offsets.windows(2).map(|start_end| {
135 let item_range = start_end[0].as_usize()..start_end[1].as_usize();
136 let item = unsafe { bytes.get_unchecked(item_range) };
139 Some(item)
140 });
141
142 encode(data, offsets, input_iter, opts);
143 }
144}
145
146pub fn encode_null(out: &mut [u8], opts: SortOptions) -> usize {
147 out[0] = null_sentinel(opts);
148 1
149}
150
151pub fn encode_empty(out: &mut [u8], opts: SortOptions) -> usize {
152 out[0] = match opts.descending {
153 true => !EMPTY_SENTINEL,
154 false => EMPTY_SENTINEL,
155 };
156 1
157}
158
159pub fn encode_null_value(out: &mut [u8], opts: SortOptions) -> usize {
161 out[0] = match opts.descending {
162 true => !NON_EMPTY_SENTINEL,
163 false => NON_EMPTY_SENTINEL,
164 };
165 out[1] = match opts.descending {
166 true => !NULL_VALUE_SENTINEL,
167 false => NULL_VALUE_SENTINEL,
168 };
169 2
170}
171
172#[inline]
173pub fn encode_one(out: &mut [u8], val: Option<&[u8]>, opts: SortOptions) -> usize {
174 match val {
175 None => encode_null(out, opts),
176 Some([]) => encode_empty(out, opts),
177 Some(val) => {
178 out[0] = NON_EMPTY_SENTINEL;
180
181 let len = if val.len() <= BLOCK_SIZE {
182 1 + encode_blocks::<MINI_BLOCK_SIZE>(&mut out[1..], val)
183 } else {
184 let (initial, rem) = val.split_at(BLOCK_SIZE);
185 let offset = encode_blocks::<MINI_BLOCK_SIZE>(&mut out[1..], initial);
186 out[offset] = BLOCK_CONTINUATION;
187 1 + offset + encode_blocks::<BLOCK_SIZE>(&mut out[1 + offset..], rem)
188 };
189
190 if opts.descending {
191 out[..len].iter_mut().for_each(|v| *v = !*v)
193 }
194 len
195 }
196 }
197}
198
199#[inline]
201fn encode_blocks<const SIZE: usize>(out: &mut [u8], val: &[u8]) -> usize {
202 let block_count = ceil(val.len(), SIZE);
203 let end_offset = block_count * (SIZE + 1);
204 let to_write = &mut out[..end_offset];
205
206 let (chunks, remainder) = val.as_chunks::<SIZE>();
207 #[expect(clippy::chunks_exact_to_as_chunks)]
208 let to_write_chunks = to_write.chunks_exact_mut(SIZE + 1);
210 for (input, output) in chunks.iter().zip(to_write_chunks) {
211 let out_block: &mut [u8; SIZE] = (&mut output[..SIZE]).try_into().unwrap();
212
213 *out_block = *input;
214
215 output[SIZE] = BLOCK_CONTINUATION;
217 }
218
219 if !remainder.is_empty() {
220 let start_offset = (block_count - 1) * (SIZE + 1);
221 to_write[start_offset..start_offset + remainder.len()].copy_from_slice(remainder);
222 *to_write.last_mut().unwrap() = remainder.len() as u8;
223 } else {
224 *to_write.last_mut().unwrap() = SIZE as u8;
226 }
227 end_offset
228}
229
230pub fn decode_blocks(row: &[u8], options: SortOptions, mut f: impl FnMut(&[u8])) -> usize {
233 let (non_empty_sentinel, continuation) = match options.descending {
234 true => (!NON_EMPTY_SENTINEL, !BLOCK_CONTINUATION),
235 false => (NON_EMPTY_SENTINEL, BLOCK_CONTINUATION),
236 };
237
238 if row[0] != non_empty_sentinel {
239 return 1;
241 }
242
243 let block_len = |sentinel: u8| match options.descending {
245 true => !sentinel as usize,
246 false => sentinel as usize,
247 };
248
249 let mut idx = 1;
250 for _ in 0..MINI_BLOCK_COUNT {
251 let sentinel = row[idx + MINI_BLOCK_SIZE];
252 if sentinel != continuation {
253 f(&row[idx..idx + block_len(sentinel)]);
254 return idx + MINI_BLOCK_SIZE + 1;
255 }
256 f(&row[idx..idx + MINI_BLOCK_SIZE]);
257 idx += MINI_BLOCK_SIZE + 1;
258 }
259
260 loop {
261 let sentinel = row[idx + BLOCK_SIZE];
262 if sentinel != continuation {
263 f(&row[idx..idx + block_len(sentinel)]);
264 return idx + BLOCK_SIZE + 1;
265 }
266 f(&row[idx..idx + BLOCK_SIZE]);
267 idx += BLOCK_SIZE + 1;
268 }
269}
270
271fn decoded_len(row: &[u8], options: SortOptions) -> usize {
273 let mut len = 0;
274 decode_blocks(row, options, |block| len += block.len());
275 len
276}
277
278pub fn decode_binary<I: OffsetSizeTrait>(
280 rows: &mut [&[u8]],
281 options: SortOptions,
282) -> GenericBinaryArray<I> {
283 let len = rows.len();
284 let nulls = decode_nulls_sentinel(rows, options);
285
286 let values_capacity = rows.iter().map(|row| decoded_len(row, options)).sum();
287 let mut offsets = Vec::<I>::with_capacity(len + 1);
288 offsets.push(I::zero());
289 let mut values = MutableBuffer::new(values_capacity);
290
291 for row in rows {
292 let offset = decode_blocks(row, options, |b| values.extend_from_slice(b));
293 *row = &row[offset..];
294 offsets.push(I::from_usize(values.len()).expect("offset overflow"))
295 }
296
297 if options.descending {
298 values.as_slice_mut().iter_mut().for_each(|o| *o = !*o)
299 }
300
301 unsafe {
304 GenericBinaryArray::new_unchecked(
305 OffsetBuffer::new(ScalarBuffer::from(offsets)),
306 values.into(),
307 nulls,
308 )
309 }
310}
311
312fn decode_binary_view_inner<const VALIDATE_UTF8: bool>(
313 rows: &mut [&[u8]],
314 options: SortOptions,
315) -> BinaryViewArray {
316 let len = rows.len();
317 let inline_str_max_len = MAX_INLINE_VIEW_LEN as usize;
318
319 let nulls = decode_nulls_sentinel(rows, options);
320
321 let mut values_capacity = inline_str_max_len;
323 let mut inline_capacity = 0;
324 for row in rows.iter() {
325 let len = decoded_len(row, options);
326 if len > inline_str_max_len {
327 values_capacity += len;
328 } else if VALIDATE_UTF8 {
329 inline_capacity += len;
330 }
331 }
332 let mut values = MutableBuffer::new(values_capacity);
333 let mut view_utf8_validation_buffer = if VALIDATE_UTF8 {
334 Vec::with_capacity(inline_capacity)
335 } else {
336 Vec::new()
337 };
338
339 let null_sentinel = null_sentinel(options);
340 let mut views = vec![0_u128; len];
341 for (i, row) in rows.iter_mut().enumerate() {
342 let start_offset = values.len();
343 let offset = decode_blocks(row, options, |b| values.extend_from_slice(b));
344 let decoded_len = values.len() - start_offset;
348 if row[0] == null_sentinel {
349 debug_assert_eq!(offset, 1);
350 debug_assert_eq!(start_offset, values.len());
351 } else {
352 let val = unsafe { values.get_unchecked_mut(start_offset..) };
354
355 if options.descending {
356 val.iter_mut().for_each(|o| *o = !*o);
357 }
358
359 views[i] = make_view(val, 0, start_offset as u32);
360
361 if decoded_len <= inline_str_max_len {
362 if VALIDATE_UTF8 {
363 view_utf8_validation_buffer.extend_from_slice(val);
364 }
365 values.truncate(start_offset);
366 }
367 }
368 *row = &row[offset..];
369 }
370
371 if VALIDATE_UTF8 {
372 std::str::from_utf8(&values).unwrap();
373 std::str::from_utf8(&view_utf8_validation_buffer).unwrap();
374 }
375
376 unsafe { BinaryViewArray::new_unchecked(views.into(), [values.into()].into(), nulls) }
379}
380
381pub fn decode_binary_view(rows: &mut [&[u8]], options: SortOptions) -> BinaryViewArray {
383 decode_binary_view_inner::<false>(rows, options)
384}
385
386pub unsafe fn decode_string<I: OffsetSizeTrait>(
392 rows: &mut [&[u8]],
393 options: SortOptions,
394 validate_utf8: bool,
395) -> GenericStringArray<I> {
396 let decoded = decode_binary::<I>(rows, options);
397
398 if validate_utf8 {
399 return GenericStringArray::from(decoded);
400 }
401
402 let (offsets, values, nulls) = decoded.into_parts();
403
404 unsafe { GenericStringArray::new_unchecked(offsets, values, nulls) }
407}
408
409pub unsafe fn decode_string_view(
415 rows: &mut [&[u8]],
416 options: SortOptions,
417 validate_utf8: bool,
418) -> StringViewArray {
419 let view = if validate_utf8 {
420 decode_binary_view_inner::<true>(rows, options)
421 } else {
422 decode_binary_view_inner::<false>(rows, options)
423 };
424 unsafe { view.to_string_view_unchecked() }
425}
426
427pub fn decode_null_value(rows: &mut [&[u8]], options: SortOptions) {
428 for row in rows.iter_mut() {
429 let (sentinel1, sentinel2) = match options.descending {
430 true => (!NON_EMPTY_SENTINEL, !NULL_VALUE_SENTINEL),
431 false => (NON_EMPTY_SENTINEL, NULL_VALUE_SENTINEL),
432 };
433 debug_assert_eq!(row[0], sentinel1, "Expected NULL_VALUE_SENTINEL at byte 0");
434 debug_assert_eq!(row[1], sentinel2, "Expected NULL_VALUE_SENTINEL at byte 1");
435 *row = &row[2..];
436 }
437}