Skip to main content

arrow_row/
run.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use crate::{RowConverter, Rows, SortField, variable};
6use arrow_array::types::RunEndIndexType;
7use arrow_array::{PrimitiveArray, RunArray};
8use arrow_buffer::{ArrowNativeType, ScalarBuffer};
9use arrow_schema::{ArrowError, SortOptions};
10
11/// Computes the lengths of each row for a RunEndEncodedArray
12pub fn compute_lengths<R: RunEndIndexType>(
13    lengths: &mut [usize],
14    rows: &Rows,
15    array: &RunArray<R>,
16) {
17    let run_ends = array.run_ends().sliced_values();
18    let mut logical_start = 0;
19
20    // Iterate over each run and apply the same length to all logical positions in the run
21    for (physical_idx, run_end) in run_ends.enumerate() {
22        let logical_end = run_end.as_usize();
23        let row_len = rows.row_len(physical_idx);
24        let encoded_len = variable::padded_length(Some(row_len));
25
26        // Add the same length for all logical positions in this run
27        for length in &mut lengths[logical_start..logical_end] {
28            *length += encoded_len;
29        }
30
31        logical_start = logical_end;
32    }
33}
34
35/// Encodes the provided `RunEndEncodedArray` to `out` with the provided `SortOptions`
36///
37/// `rows` should contain the encoded values
38pub fn encode<R: RunEndIndexType>(
39    data: &mut [u8],
40    offsets: &mut [usize],
41    rows: &Rows,
42    opts: SortOptions,
43    array: &RunArray<R>,
44) {
45    let run_ends = array.run_ends().sliced_values();
46    let mut logical_idx = 0;
47    let mut offset_idx = 1; // Skip first offset
48
49    // Iterate over each run
50    for (physical_idx, run_end) in run_ends.enumerate() {
51        let run_end = run_end.as_usize();
52        let iteration_count = run_end - logical_idx;
53
54        let first_offset = offsets[offset_idx];
55        let out = &mut data[first_offset..];
56        let bytes_written = variable::encode_one(out, Some(rows.row(physical_idx).data), opts);
57        offsets[offset_idx] += bytes_written;
58        // now if there are multiple logical positions in this run, we can just copy the same encoded data to the next offsets without re-encoding
59        for i in 1..iteration_count {
60            let dst = offsets[offset_idx + i];
61            data.copy_within(first_offset..first_offset + bytes_written, dst);
62            offsets[offset_idx + i] += bytes_written;
63        }
64        logical_idx = run_end;
65        offset_idx += iteration_count;
66    }
67}
68
69/// Decodes a RunEndEncodedArray from `rows` with the provided `options`
70///
71/// # Safety
72///
73/// `rows` must contain valid data for the provided `converter`
74pub unsafe fn decode<R: RunEndIndexType>(
75    converter: &RowConverter,
76    rows: &mut [&[u8]],
77    field: &SortField,
78    validate_utf8: bool,
79) -> Result<RunArray<R>, ArrowError> {
80    if rows.is_empty() {
81        let values = unsafe { converter.convert_raw(&mut [], validate_utf8) }?;
82        let run_ends_array = PrimitiveArray::<R>::try_new(ScalarBuffer::from(vec![]), None)?;
83        return RunArray::<R>::try_new(&run_ends_array, &values[0]);
84    }
85
86    // Decode each row's REE data and collect the decoded values
87    let mut decoded_values = Vec::new();
88    let mut run_ends = Vec::new();
89    let mut unique_row_indices = Vec::new();
90
91    // Process each row to extract its REE data (following decode_binary pattern)
92    let mut decoded_data = Vec::new();
93    for (idx, row) in rows.iter_mut().enumerate() {
94        decoded_data.clear();
95        // Extract the decoded value data from this row
96        let consumed = variable::decode_blocks(row, field.options, |block| {
97            decoded_data.extend_from_slice(block);
98        });
99
100        // Handle bit inversion for descending sort (following decode_binary pattern)
101        if field.options.descending {
102            decoded_data.iter_mut().for_each(|b| *b = !*b);
103        }
104
105        // Update the row to point past the consumed REE data
106        *row = &row[consumed..];
107
108        // Check if this decoded value is the same as the previous one to identify runs
109        let is_new_run =
110            idx == 0 || decoded_data != decoded_values[*unique_row_indices.last().unwrap()];
111
112        if is_new_run {
113            // This is a new unique value - end the previous run if any
114            if idx > 0 {
115                run_ends.push(R::Native::usize_as(idx));
116            }
117            unique_row_indices.push(decoded_values.len());
118            let capacity = decoded_data.capacity();
119            decoded_values.push(std::mem::replace(
120                &mut decoded_data,
121                Vec::with_capacity(capacity),
122            ));
123        }
124    }
125    // Add the final run end
126    run_ends.push(R::Native::usize_as(rows.len()));
127
128    // Convert the unique decoded values using the row converter
129    let mut unique_rows: Vec<&[u8]> = decoded_values.iter().map(|v| v.as_slice()).collect();
130    let values = if unique_rows.is_empty() {
131        unsafe { converter.convert_raw(&mut [], validate_utf8) }?
132    } else {
133        unsafe { converter.convert_raw(&mut unique_rows, validate_utf8) }?
134    };
135
136    // Create run ends array
137    let run_ends_array = PrimitiveArray::<R>::try_new(ScalarBuffer::from(run_ends), None)?;
138
139    // Create the RunEndEncodedArray
140    RunArray::<R>::try_new(&run_ends_array, &values[0])
141}
142
143#[cfg(test)]
144mod tests {
145    use crate::{RowConverter, SortField};
146    use arrow_array::cast::AsArray;
147    use arrow_array::types::{Int16Type, Int32Type, Int64Type, RunEndIndexType};
148    use arrow_array::{Array, Int64Array, PrimitiveArray, RunArray, StringArray};
149    use arrow_schema::{DataType, Field, SortOptions};
150    use std::sync::Arc;
151
152    fn assert_roundtrip<R: RunEndIndexType>(
153        array: &RunArray<R>,
154        run_end_type: DataType,
155        values_type: DataType,
156        sort_options: Option<SortOptions>,
157    ) {
158        let sort_field = if let Some(options) = sort_options {
159            SortField::new_with_options(
160                DataType::RunEndEncoded(
161                    Arc::new(Field::new(
162                        Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
163                        run_end_type,
164                        false,
165                    )),
166                    Arc::new(Field::new(
167                        Field::REE_VALUES_FIELD_DEFAULT_NAME,
168                        values_type,
169                        true,
170                    )),
171                ),
172                options,
173            )
174        } else {
175            SortField::new(DataType::RunEndEncoded(
176                Arc::new(Field::new(
177                    Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
178                    run_end_type,
179                    false,
180                )),
181                Arc::new(Field::new(
182                    Field::REE_VALUES_FIELD_DEFAULT_NAME,
183                    values_type,
184                    true,
185                )),
186            ))
187        };
188
189        let converter = RowConverter::new(vec![sort_field]).unwrap();
190
191        let rows = converter
192            .convert_columns(&[Arc::new(array.clone())])
193            .unwrap();
194
195        let arrays = converter.convert_rows(&rows).unwrap();
196        let result = arrays[0].as_any().downcast_ref::<RunArray<R>>().unwrap();
197
198        assert_eq!(array, result);
199    }
200
201    #[test]
202    fn test_run_end_encoded_supports_datatype() {
203        // Test that the RowConverter correctly supports run-end encoded arrays
204        assert!(RowConverter::supports_datatype(&DataType::RunEndEncoded(
205            Arc::new(Field::new(
206                Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
207                DataType::Int32,
208                false
209            )),
210            Arc::new(Field::new(
211                Field::REE_VALUES_FIELD_DEFAULT_NAME,
212                DataType::Utf8,
213                true
214            )),
215        )));
216    }
217
218    #[test]
219    fn test_run_end_encoded_round_trip_int16_int64s() {
220        // Test round-trip correctness for RunEndEncodedArray with Int64 values making sure it
221        // doesn't just work with eg. strings (which are all the other tests).
222
223        let values = Int64Array::from(vec![100, 200, 100, 300]);
224        let run_ends = vec![2, 3, 5, 6];
225        let array: RunArray<Int16Type> =
226            RunArray::try_new(&PrimitiveArray::from(run_ends), &values).unwrap();
227
228        assert_roundtrip(&array, DataType::Int16, DataType::Int64, None);
229    }
230
231    #[test]
232    fn test_run_end_encoded_round_trip_int32_int64s() {
233        // Test round-trip correctness for RunEndEncodedArray with Int64 values making sure it
234        // doesn't just work with eg. strings (which are all the other tests).
235
236        let values = Int64Array::from(vec![100, 200, 100, 300]);
237        let run_ends = vec![2, 3, 5, 6];
238        let array: RunArray<Int32Type> =
239            RunArray::try_new(&PrimitiveArray::from(run_ends), &values).unwrap();
240
241        assert_roundtrip(&array, DataType::Int32, DataType::Int64, None);
242    }
243
244    #[test]
245    fn test_run_end_encoded_round_trip_int64_int64s() {
246        // Test round-trip correctness for RunEndEncodedArray with Int64 values making sure it
247        // doesn't just work with eg. strings (which are all the other tests).
248
249        let values = Int64Array::from(vec![100, 200, 100, 300]);
250        let run_ends = vec![2, 3, 5, 6];
251        let array: RunArray<Int64Type> =
252            RunArray::try_new(&PrimitiveArray::from(run_ends), &values).unwrap();
253
254        assert_roundtrip(&array, DataType::Int64, DataType::Int64, None);
255    }
256
257    #[test]
258    fn test_run_end_encoded_round_trip_strings() {
259        // Test round-trip correctness for RunEndEncodedArray with strings
260
261        let array: RunArray<Int32Type> = vec!["b", "b", "a"].into_iter().collect();
262
263        assert_roundtrip(&array, DataType::Int32, DataType::Utf8, None);
264    }
265
266    #[test]
267    fn test_run_end_encoded_round_trip_strings_with_nulls() {
268        // Test round-trip correctness for RunEndEncodedArray with nulls
269
270        let array: RunArray<Int32Type> = vec![Some("b"), Some("b"), None, Some("a")]
271            .into_iter()
272            .collect();
273
274        assert_roundtrip(&array, DataType::Int32, DataType::Utf8, None);
275    }
276
277    #[test]
278    fn test_run_end_encoded_ascending_descending_round_trip() {
279        // Test round-trip correctness for ascending vs descending sort options
280
281        let values_asc =
282            arrow_array::StringArray::from(vec![Some("apple"), Some("banana"), Some("cherry")]);
283        let run_ends_asc = vec![2, 4, 6];
284        let run_array_asc: RunArray<Int32Type> = RunArray::try_new(
285            &arrow_array::PrimitiveArray::from(run_ends_asc),
286            &values_asc,
287        )
288        .unwrap();
289
290        // Test ascending order
291        assert_roundtrip(
292            &run_array_asc,
293            DataType::Int32,
294            DataType::Utf8,
295            Some(SortOptions {
296                descending: false,
297                nulls_first: true,
298            }),
299        );
300
301        // Test descending order
302        assert_roundtrip(
303            &run_array_asc,
304            DataType::Int32,
305            DataType::Utf8,
306            Some(SortOptions {
307                descending: true,
308                nulls_first: true,
309            }),
310        );
311    }
312
313    #[test]
314    fn test_run_end_encoded_sort_configurations_basic() {
315        // Test that different sort configurations work and can round-trip successfully
316
317        let test_array: RunArray<Int32Type> = vec!["test"].into_iter().collect();
318
319        // Test ascending order
320        assert_roundtrip(
321            &test_array,
322            DataType::Int32,
323            DataType::Utf8,
324            Some(SortOptions {
325                descending: false,
326                nulls_first: true,
327            }),
328        );
329
330        // Test descending order
331        assert_roundtrip(
332            &test_array,
333            DataType::Int32,
334            DataType::Utf8,
335            Some(SortOptions {
336                descending: true,
337                nulls_first: true,
338            }),
339        );
340    }
341
342    #[test]
343    fn test_run_end_encoded_nulls_first_last_configurations() {
344        // Test that nulls_first vs nulls_last configurations work
345
346        let simple_array: RunArray<Int32Type> = vec!["simple"].into_iter().collect();
347
348        let converter_nulls_first = RowConverter::new(vec![SortField::new_with_options(
349            DataType::RunEndEncoded(
350                Arc::new(Field::new(
351                    Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
352                    DataType::Int32,
353                    false,
354                )),
355                Arc::new(Field::new(
356                    Field::REE_VALUES_FIELD_DEFAULT_NAME,
357                    DataType::Utf8,
358                    true,
359                )),
360            ),
361            SortOptions {
362                descending: false,
363                nulls_first: true,
364            },
365        )])
366        .unwrap();
367
368        let converter_nulls_last = RowConverter::new(vec![SortField::new_with_options(
369            DataType::RunEndEncoded(
370                Arc::new(Field::new(
371                    Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
372                    DataType::Int32,
373                    false,
374                )),
375                Arc::new(Field::new(
376                    Field::REE_VALUES_FIELD_DEFAULT_NAME,
377                    DataType::Utf8,
378                    true,
379                )),
380            ),
381            SortOptions {
382                descending: false,
383                nulls_first: false,
384            },
385        )])
386        .unwrap();
387
388        // Test that both configurations can handle simple arrays
389        let rows_nulls_first = converter_nulls_first
390            .convert_columns(&[Arc::new(simple_array.clone())])
391            .unwrap();
392        let arrays_nulls_first = converter_nulls_first
393            .convert_rows(&rows_nulls_first)
394            .unwrap();
395        let result_nulls_first = arrays_nulls_first[0]
396            .as_any()
397            .downcast_ref::<RunArray<Int32Type>>()
398            .unwrap();
399
400        let rows_nulls_last = converter_nulls_last
401            .convert_columns(&[Arc::new(simple_array.clone())])
402            .unwrap();
403        let arrays_nulls_last = converter_nulls_last.convert_rows(&rows_nulls_last).unwrap();
404        let result_nulls_last = arrays_nulls_last[0]
405            .as_any()
406            .downcast_ref::<RunArray<Int32Type>>()
407            .unwrap();
408
409        // Both should successfully convert the simple array
410        assert_eq!(simple_array.len(), result_nulls_first.len());
411        assert_eq!(simple_array.len(), result_nulls_last.len());
412    }
413
414    #[test]
415    fn test_run_end_encoded_row_consumption() {
416        // This test verifies that ALL rows are properly consumed during decoding,
417        // not just the unique values. We test this by ensuring multi-column conversion
418        // works correctly - if rows aren't consumed properly, the second column would fail.
419
420        // Create a REE array with multiple runs
421        let array: RunArray<Int32Type> = vec!["a", "a", "b", "b", "b", "c"].into_iter().collect();
422        let string_array = StringArray::from(vec!["x", "y", "z", "w", "u", "v"]);
423
424        let multi_converter = RowConverter::new(vec![
425            SortField::new(DataType::RunEndEncoded(
426                Arc::new(Field::new(
427                    Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
428                    DataType::Int32,
429                    false,
430                )),
431                Arc::new(Field::new(
432                    Field::REE_VALUES_FIELD_DEFAULT_NAME,
433                    DataType::Utf8,
434                    true,
435                )),
436            )),
437            SortField::new(DataType::Utf8),
438        ])
439        .unwrap();
440
441        let multi_rows = multi_converter
442            .convert_columns(&[Arc::new(array.clone()), Arc::new(string_array.clone())])
443            .unwrap();
444
445        // Convert back - this will test that all rows are consumed properly
446        let arrays = multi_converter.convert_rows(&multi_rows).unwrap();
447
448        // Verify both columns round-trip correctly
449        let result_ree = arrays[0]
450            .as_any()
451            .downcast_ref::<RunArray<Int32Type>>()
452            .unwrap();
453
454        let result_string = arrays[1].as_any().downcast_ref::<StringArray>().unwrap();
455
456        // This should pass - both arrays should be identical to originals
457        assert_eq!(result_ree.values().as_ref(), array.values().as_ref());
458        assert_eq!(result_ree.run_ends().values(), array.run_ends().values());
459        assert_eq!(*result_string, string_array);
460    }
461
462    #[test]
463    fn test_run_end_encoded_sorting_behavior() {
464        // Test that the binary row encoding actually produces the correct sort order
465
466        // Create REE arrays with different values to test sorting
467        let array1: RunArray<Int32Type> = vec!["apple", "apple"].into_iter().collect();
468        let array2: RunArray<Int32Type> = vec!["banana", "banana"].into_iter().collect();
469        let array3: RunArray<Int32Type> = vec!["cherry", "cherry"].into_iter().collect();
470
471        // Test ascending sort
472        let converter_asc = RowConverter::new(vec![SortField::new(DataType::RunEndEncoded(
473            Arc::new(Field::new(
474                Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
475                DataType::Int32,
476                false,
477            )),
478            Arc::new(Field::new(
479                Field::REE_VALUES_FIELD_DEFAULT_NAME,
480                DataType::Utf8,
481                true,
482            )),
483        ))])
484        .unwrap();
485
486        let rows1_asc = converter_asc
487            .convert_columns(&[Arc::new(array1.clone())])
488            .unwrap();
489        let rows2_asc = converter_asc
490            .convert_columns(&[Arc::new(array2.clone())])
491            .unwrap();
492        let rows3_asc = converter_asc
493            .convert_columns(&[Arc::new(array3.clone())])
494            .unwrap();
495
496        // For ascending: apple < banana < cherry
497        // So row bytes should sort: rows1 < rows2 < rows3
498        assert!(
499            rows1_asc.row(0) < rows2_asc.row(0),
500            "apple should come before banana in ascending order"
501        );
502        assert!(
503            rows2_asc.row(0) < rows3_asc.row(0),
504            "banana should come before cherry in ascending order"
505        );
506        assert!(
507            rows1_asc.row(0) < rows3_asc.row(0),
508            "apple should come before cherry in ascending order"
509        );
510
511        // Test descending sort
512        let converter_desc = RowConverter::new(vec![SortField::new_with_options(
513            DataType::RunEndEncoded(
514                Arc::new(Field::new(
515                    Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
516                    DataType::Int32,
517                    false,
518                )),
519                Arc::new(Field::new(
520                    Field::REE_VALUES_FIELD_DEFAULT_NAME,
521                    DataType::Utf8,
522                    true,
523                )),
524            ),
525            arrow_schema::SortOptions {
526                descending: true,
527                nulls_first: true,
528            },
529        )])
530        .unwrap();
531
532        let rows1_desc = converter_desc
533            .convert_columns(&[Arc::new(array1.clone())])
534            .unwrap();
535        let rows2_desc = converter_desc
536            .convert_columns(&[Arc::new(array2.clone())])
537            .unwrap();
538        let rows3_desc = converter_desc
539            .convert_columns(&[Arc::new(array3.clone())])
540            .unwrap();
541
542        // For descending: cherry > banana > apple
543        // So row bytes should sort: rows3 < rows2 < rows1 (because byte comparison is ascending)
544        assert!(
545            rows3_desc.row(0) < rows2_desc.row(0),
546            "cherry should come before banana in descending order (byte-wise)"
547        );
548        assert!(
549            rows2_desc.row(0) < rows1_desc.row(0),
550            "banana should come before apple in descending order (byte-wise)"
551        );
552        assert!(
553            rows3_desc.row(0) < rows1_desc.row(0),
554            "cherry should come before apple in descending order (byte-wise)"
555        );
556    }
557
558    #[test]
559    fn test_run_end_encoded_null_sorting() {
560        // Test null handling in sort order
561
562        let array_with_nulls: RunArray<Int32Type> = vec![None, None].into_iter().collect();
563        let array_with_values: RunArray<Int32Type> = vec!["apple", "apple"].into_iter().collect();
564
565        // Test nulls_first = true
566        let converter_nulls_first = RowConverter::new(vec![SortField::new_with_options(
567            DataType::RunEndEncoded(
568                Arc::new(Field::new(
569                    Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
570                    DataType::Int32,
571                    false,
572                )),
573                Arc::new(Field::new(
574                    Field::REE_VALUES_FIELD_DEFAULT_NAME,
575                    DataType::Utf8,
576                    true,
577                )),
578            ),
579            arrow_schema::SortOptions {
580                descending: false,
581                nulls_first: true,
582            },
583        )])
584        .unwrap();
585
586        let rows_nulls = converter_nulls_first
587            .convert_columns(&[Arc::new(array_with_nulls.clone())])
588            .unwrap();
589        let rows_values = converter_nulls_first
590            .convert_columns(&[Arc::new(array_with_values.clone())])
591            .unwrap();
592
593        // nulls should come before values when nulls_first = true
594        assert!(
595            rows_nulls.row(0) < rows_values.row(0),
596            "nulls should come before values when nulls_first=true"
597        );
598
599        // Test nulls_first = false
600        let converter_nulls_last = RowConverter::new(vec![SortField::new_with_options(
601            DataType::RunEndEncoded(
602                Arc::new(Field::new(
603                    Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
604                    DataType::Int32,
605                    false,
606                )),
607                Arc::new(Field::new(
608                    Field::REE_VALUES_FIELD_DEFAULT_NAME,
609                    DataType::Utf8,
610                    true,
611                )),
612            ),
613            arrow_schema::SortOptions {
614                descending: false,
615                nulls_first: false,
616            },
617        )])
618        .unwrap();
619
620        let rows_nulls_last = converter_nulls_last
621            .convert_columns(&[Arc::new(array_with_nulls.clone())])
622            .unwrap();
623        let rows_values_last = converter_nulls_last
624            .convert_columns(&[Arc::new(array_with_values.clone())])
625            .unwrap();
626
627        // values should come before nulls when nulls_first = false
628        assert!(
629            rows_values_last.row(0) < rows_nulls_last.row(0),
630            "values should come before nulls when nulls_first=false"
631        );
632    }
633
634    #[test]
635    fn test_run_end_encoded_mixed_sorting() {
636        // Test sorting with mixed values and nulls to ensure complex scenarios work
637
638        let array1: RunArray<Int32Type> = vec![Some("apple"), None].into_iter().collect();
639        let array2: RunArray<Int32Type> = vec![None, Some("banana")].into_iter().collect();
640        let array3: RunArray<Int32Type> =
641            vec![Some("cherry"), Some("cherry")].into_iter().collect();
642
643        let converter = RowConverter::new(vec![SortField::new_with_options(
644            DataType::RunEndEncoded(
645                Arc::new(Field::new(
646                    Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
647                    DataType::Int32,
648                    false,
649                )),
650                Arc::new(Field::new(
651                    Field::REE_VALUES_FIELD_DEFAULT_NAME,
652                    DataType::Utf8,
653                    true,
654                )),
655            ),
656            arrow_schema::SortOptions {
657                descending: false,
658                nulls_first: true,
659            },
660        )])
661        .unwrap();
662
663        let rows1 = converter.convert_columns(&[Arc::new(array1)]).unwrap();
664        let rows2 = converter.convert_columns(&[Arc::new(array2)]).unwrap();
665        let rows3 = converter.convert_columns(&[Arc::new(array3)]).unwrap();
666
667        // With nulls_first=true, ascending:
668        // Row 0: array1[0]="apple", array2[0]=null, array3[0]="cherry" -> null < apple < cherry
669        // Row 1: array1[1]=null, array2[1]="banana", array3[1]="cherry" -> null < banana < cherry
670
671        // Compare first rows: null < apple < cherry
672        assert!(rows2.row(0) < rows1.row(0), "null should come before apple");
673        assert!(
674            rows1.row(0) < rows3.row(0),
675            "apple should come before cherry"
676        );
677
678        // Compare second rows: null < banana < cherry
679        assert!(
680            rows1.row(1) < rows2.row(1),
681            "null should come before banana"
682        );
683        assert!(
684            rows2.row(1) < rows3.row(1),
685            "banana should come before cherry"
686        );
687    }
688
689    #[test]
690    fn test_run_end_encoded_empty() {
691        // Test converting / decoding an empty RunEndEncodedArray
692        let values: Vec<&str> = vec![];
693        let array: RunArray<Int32Type> = values.into_iter().collect();
694
695        let converter = RowConverter::new(vec![SortField::new(DataType::RunEndEncoded(
696            Arc::new(Field::new(
697                Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
698                DataType::Int32,
699                false,
700            )),
701            Arc::new(Field::new(
702                Field::REE_VALUES_FIELD_DEFAULT_NAME,
703                DataType::Utf8,
704                true,
705            )),
706        ))])
707        .unwrap();
708
709        let rows = converter.convert_columns(&[Arc::new(array)]).unwrap();
710        assert_eq!(rows.num_rows(), 0);
711
712        // Likewise converting empty rows should yield an empty RunEndEncodedArray
713        let arrays = converter.convert_rows(&rows).unwrap();
714        assert_eq!(arrays.len(), 1);
715        // Verify both columns round-trip correctly
716        let result_ree = arrays[0].as_run::<Int32Type>();
717        assert_eq!(result_ree.len(), 0);
718    }
719
720    #[test]
721    fn test_run_end_encoded_round_trip_sliced() {
722        let values = Int64Array::from(vec![100, 200, 100, 300]);
723        let run_ends = vec![2, 3, 5, 6];
724        let array: RunArray<Int16Type> =
725            RunArray::try_new(&PrimitiveArray::from(run_ends), &values).unwrap();
726        let array = array.slice(2, 3);
727
728        assert_roundtrip(&array, DataType::Int16, DataType::Int64, None);
729    }
730}