Skip to main content

liquid_cache_storage/liquid_array/
byte_array.rs

1use ahash::HashMap;
2use arrow::array::BinaryViewArray;
3use arrow::array::{
4    Array, ArrayAccessor, ArrayIter, ArrayRef, BinaryArray, BooleanArray, BooleanBufferBuilder,
5    BufferBuilder, DictionaryArray, GenericByteArray, StringArray, StringViewArray, UInt16Array,
6    cast::AsArray, types::UInt16Type,
7};
8use arrow::buffer::{BooleanBuffer, Buffer, NullBuffer, OffsetBuffer, ScalarBuffer};
9use arrow::compute::{cast, kernels};
10use arrow::datatypes::{BinaryType, ByteArrayType, Utf8Type};
11use arrow_schema::DataType;
12use bytes::Bytes;
13use datafusion::logical_expr::{ColumnarValue, Operator};
14use datafusion::physical_expr_common::datum::apply_cmp;
15use datafusion::physical_plan::PhysicalExpr;
16use datafusion::physical_plan::expressions::{BinaryExpr, LikeExpr, Literal};
17use datafusion::scalar::ScalarValue;
18use fsst::{Compressor, Decompressor};
19use std::any::Any;
20use std::mem::MaybeUninit;
21use std::sync::Arc;
22
23use super::{LiquidArray, LiquidArrayRef, LiquidDataType};
24use crate::liquid_array::ipc::LiquidIPCHeader;
25use crate::liquid_array::{raw::BitPackedArray, raw::FsstArray};
26use crate::utils::CheckedDictionaryArray;
27
28impl LiquidArray for LiquidByteArray {
29    fn as_any(&self) -> &dyn Any {
30        self
31    }
32
33    fn get_array_memory_size(&self) -> usize {
34        self.keys.get_array_memory_size() + self.values.get_array_memory_size()
35    }
36
37    fn len(&self) -> usize {
38        self.keys.len()
39    }
40
41    #[inline]
42    fn to_arrow_array(&self) -> ArrayRef {
43        let dict = self.to_arrow_array();
44        Arc::new(dict)
45    }
46
47    fn to_best_arrow_array(&self) -> ArrayRef {
48        // the best arrow string is DictionaryArray<UInt16Type>
49        let dict = self.to_dict_arrow();
50        Arc::new(dict)
51    }
52
53    fn filter(&self, selection: &BooleanBuffer) -> LiquidArrayRef {
54        let filtered = filter_inner(self, selection);
55        Arc::new(filtered)
56    }
57
58    fn try_eval_predicate(
59        &self,
60        expr: &Arc<dyn PhysicalExpr>,
61        filter: &BooleanBuffer,
62    ) -> Option<BooleanArray> {
63        let filtered = filter_inner(self, filter);
64        try_eval_predicate_inner(expr, &filtered)
65    }
66
67    fn to_bytes(&self) -> Vec<u8> {
68        self.to_bytes_inner()
69    }
70
71    fn original_arrow_data_type(&self) -> DataType {
72        self.original_arrow_type.to_arrow_type()
73    }
74
75    fn data_type(&self) -> LiquidDataType {
76        LiquidDataType::ByteArray
77    }
78}
79
80// Header for LiquidByteArray serialization
81#[repr(C)]
82struct ByteArrayHeader {
83    key_size: u32,
84    value_size: u32,
85}
86
87impl ByteArrayHeader {
88    const fn size() -> usize {
89        const _: () = assert!(std::mem::size_of::<ByteArrayHeader>() == ByteArrayHeader::size());
90        8
91    }
92
93    fn to_bytes(&self) -> [u8; Self::size()] {
94        let mut bytes = [0; Self::size()];
95        bytes[0..4].copy_from_slice(&self.key_size.to_le_bytes());
96        bytes[4..8].copy_from_slice(&self.value_size.to_le_bytes());
97        bytes
98    }
99
100    fn from_bytes(bytes: &[u8]) -> Self {
101        if bytes.len() < Self::size() {
102            panic!(
103                "value too small for ByteArrayHeader, expected at least {} bytes, got {}",
104                Self::size(),
105                bytes.len()
106            );
107        }
108        let key_size = u32::from_le_bytes(bytes[0..4].try_into().unwrap());
109        let value_size = u32::from_le_bytes(bytes[4..8].try_into().unwrap());
110        Self {
111            key_size,
112            value_size,
113        }
114    }
115}
116
117impl LiquidByteArray {
118    /*
119    Serialized LiquidByteArray Memory Layout:
120    +--------------------------------------------------+
121    | LiquidIPCHeader (16 bytes)                       |
122    +--------------------------------------------------+
123    | ByteArrayHeader (8 bytes)                        |  // Contains key_size and value_size
124    +--------------------------------------------------+
125    | BitPackedArray Data (keys)                       |
126    +--------------------------------------------------+
127    | [BitPackedArray Header & Bit-Packed Key Values]  |  // Written by keys.to_bytes()
128    +--------------------------------------------------+
129    | Padding (to 8-byte alignment)                    |  // Padding to ensure 8-byte alignment
130    +--------------------------------------------------+
131    | FsstArray Data (values)                          |
132    +--------------------------------------------------+
133    | [FsstArray Data]                                 |  // Written by values.to_bytes()
134    +--------------------------------------------------+
135    */
136    pub(crate) fn to_bytes_inner(&self) -> Vec<u8> {
137        // Create a buffer for the final output data, starting with the header
138        let header_size = LiquidIPCHeader::size() + ByteArrayHeader::size();
139        let mut result = Vec::with_capacity(header_size + 1024); // Pre-allocate a reasonable size
140
141        result.resize(header_size, 0);
142
143        // Serialize the BitPackedArray (keys)
144        let keys_start = result.len();
145        self.keys.to_bytes(&mut result);
146        let keys_size = result.len() - keys_start;
147
148        // Add padding to ensure FsstArray starts at an 8-byte aligned position
149        while !result.len().is_multiple_of(8) {
150            result.push(0);
151        }
152
153        // Serialize the FsstArray (values)
154        let values_start = result.len();
155        self.values.to_bytes(&mut result);
156        let values_size = result.len() - values_start;
157
158        // Go back and fill in the header
159        let ipc_header = LiquidIPCHeader::new(
160            LiquidDataType::ByteArray as u16,
161            self.original_arrow_type as u16,
162        );
163        let header = &mut result[0..header_size];
164        header[0..LiquidIPCHeader::size()].copy_from_slice(&ipc_header.to_bytes());
165
166        let byte_array_header = ByteArrayHeader {
167            key_size: keys_size as u32,
168            value_size: values_size as u32,
169        };
170        header[LiquidIPCHeader::size()..header_size].copy_from_slice(&byte_array_header.to_bytes());
171
172        result
173    }
174
175    /// Deserialize a LiquidByteArray from bytes, using zero-copy where possible.
176    pub fn from_bytes(bytes: Bytes, compressor: Arc<Compressor>) -> Self {
177        let header_size = LiquidIPCHeader::size() + ByteArrayHeader::size();
178        let header = LiquidIPCHeader::from_bytes(&bytes);
179
180        let byte_array_header =
181            ByteArrayHeader::from_bytes(&bytes[LiquidIPCHeader::size()..header_size]);
182
183        let original_arrow_type = ArrowByteType::from(header.physical_type_id);
184
185        let keys_size = byte_array_header.key_size as usize;
186        let values_size = byte_array_header.value_size as usize;
187
188        // Calculate offsets
189        let keys_start = header_size;
190        let keys_end = keys_start + keys_size;
191
192        if keys_end > bytes.len() {
193            panic!("Keys data extends beyond input buffer");
194        }
195
196        // Ensure values data starts at 8-byte aligned position
197        let values_start = (keys_end + 7) & !7; // Round up to next 8-byte boundary
198        let values_end = values_start + values_size;
199
200        if values_end > bytes.len() {
201            panic!("Values data extends beyond input buffer");
202        }
203
204        // Extract and deserialize components
205        let keys_data = bytes.slice(keys_start..keys_end);
206        let keys = BitPackedArray::<UInt16Type>::from_bytes(keys_data);
207
208        let values_data = bytes.slice(values_start..values_end);
209        let values = FsstArray::from_bytes(values_data, compressor);
210
211        Self {
212            keys,
213            values,
214            original_arrow_type,
215        }
216    }
217}
218
219fn filter_inner(array: &LiquidByteArray, filter: &BooleanBuffer) -> LiquidByteArray {
220    let values = array.values.clone();
221    let keys = array.keys.clone();
222    let primitive_keys = keys.to_primitive();
223    let filter = BooleanArray::new(filter.clone(), None);
224    let filtered_keys = arrow::compute::filter(&primitive_keys, &filter)
225        .unwrap()
226        .as_primitive::<UInt16Type>()
227        .clone();
228    let bit_packed_array = match keys.bit_width() {
229        Some(bit_width) => BitPackedArray::from_primitive(filtered_keys, bit_width),
230        None => BitPackedArray::new_null_array(filtered_keys.len()),
231    };
232    LiquidByteArray {
233        keys: bit_packed_array,
234        values,
235        original_arrow_type: array.original_arrow_type,
236    }
237}
238
239fn try_eval_predicate_inner(
240    expr: &Arc<dyn PhysicalExpr>,
241    array: &LiquidByteArray,
242) -> Option<BooleanArray> {
243    if let Some(binary_expr) = expr.as_any().downcast_ref::<BinaryExpr>() {
244        if let Some(literal) = binary_expr.right().as_any().downcast_ref::<Literal>() {
245            let op = binary_expr.op();
246            if let Some(needle) = get_string_needle(literal.value()) {
247                if op == &Operator::Eq {
248                    let result = array.compare_equals(needle);
249                    return Some(result);
250                } else if op == &Operator::NotEq {
251                    let result = array.compare_not_equals(needle);
252                    return Some(result);
253                }
254            }
255
256            let dict_array = array.to_dict_arrow();
257            let lhs = ColumnarValue::Array(Arc::new(dict_array));
258            let rhs = ColumnarValue::Scalar(literal.value().clone());
259
260            let result = match op {
261                Operator::NotEq => apply_cmp(&lhs, &rhs, kernels::cmp::neq),
262                Operator::Eq => apply_cmp(&lhs, &rhs, kernels::cmp::eq),
263                Operator::Lt => apply_cmp(&lhs, &rhs, kernels::cmp::lt),
264                Operator::LtEq => apply_cmp(&lhs, &rhs, kernels::cmp::lt_eq),
265                Operator::Gt => apply_cmp(&lhs, &rhs, kernels::cmp::gt),
266                Operator::GtEq => apply_cmp(&lhs, &rhs, kernels::cmp::gt_eq),
267                Operator::LikeMatch => apply_cmp(&lhs, &rhs, arrow::compute::like),
268                Operator::ILikeMatch => apply_cmp(&lhs, &rhs, arrow::compute::ilike),
269                Operator::NotLikeMatch => apply_cmp(&lhs, &rhs, arrow::compute::nlike),
270                Operator::NotILikeMatch => apply_cmp(&lhs, &rhs, arrow::compute::nilike),
271                _ => return None,
272            };
273            if let Ok(result) = result {
274                let filtered = result.into_array(array.len()).unwrap().as_boolean().clone();
275                return Some(filtered);
276            }
277        }
278    } else if let Some(like_expr) = expr.as_any().downcast_ref::<LikeExpr>()
279        && like_expr
280            .pattern()
281            .as_any()
282            .downcast_ref::<Literal>()
283            .is_some()
284        && let Some(literal) = like_expr.pattern().as_any().downcast_ref::<Literal>()
285    {
286        let arrow_dict = array.to_dict_arrow();
287
288        let lhs = ColumnarValue::Array(Arc::new(arrow_dict));
289        let rhs = ColumnarValue::Scalar(literal.value().clone());
290
291        let result = match (like_expr.negated(), like_expr.case_insensitive()) {
292            (false, false) => apply_cmp(&lhs, &rhs, arrow::compute::like),
293            (true, false) => apply_cmp(&lhs, &rhs, arrow::compute::nlike),
294            (false, true) => apply_cmp(&lhs, &rhs, arrow::compute::ilike),
295            (true, true) => apply_cmp(&lhs, &rhs, arrow::compute::nilike),
296        };
297        if let Ok(result) = result {
298            let filtered = result.into_array(array.len()).unwrap().as_boolean().clone();
299            return Some(filtered);
300        }
301    }
302    None
303}
304
305/// Extract a string needle from a scalar value for string comparison operations.
306///
307/// This function handles various string scalar value types including Utf8, Utf8View,
308/// LargeUtf8, and Dictionary types. Returns `None` for non-string types or null values.
309pub fn get_string_needle(value: &ScalarValue) -> Option<&str> {
310    if let ScalarValue::Utf8(Some(v)) = value {
311        Some(v)
312    } else if let ScalarValue::Utf8View(Some(v)) = value {
313        Some(v)
314    } else if let ScalarValue::LargeUtf8(Some(v)) = value {
315        Some(v)
316    } else if let ScalarValue::Dictionary(_, value) = value {
317        get_string_needle(value.as_ref())
318    } else {
319        None
320    }
321}
322
323#[derive(Debug, Clone, Copy, PartialEq)]
324#[repr(u16)]
325pub(crate) enum ArrowByteType {
326    Utf8 = 0,
327    Utf8View = 1,
328    Dict16Binary = 2, // DictionaryArray<UInt16Type>
329    Dict16Utf8 = 3,   // DictionaryArray<UInt16Type>
330    Binary = 4,
331    BinaryView = 5,
332}
333
334impl From<u16> for ArrowByteType {
335    fn from(value: u16) -> Self {
336        match value {
337            0 => ArrowByteType::Utf8,
338            1 => ArrowByteType::Utf8View,
339            2 => ArrowByteType::Dict16Binary,
340            3 => ArrowByteType::Dict16Utf8,
341            4 => ArrowByteType::Binary,
342            5 => ArrowByteType::BinaryView,
343            _ => panic!("Invalid arrow byte type: {value}"),
344        }
345    }
346}
347
348impl ArrowByteType {
349    pub fn to_arrow_type(self) -> DataType {
350        match self {
351            ArrowByteType::Utf8 => DataType::Utf8,
352            ArrowByteType::Utf8View => DataType::Utf8View,
353            ArrowByteType::Dict16Binary => {
354                DataType::Dictionary(Box::new(DataType::UInt16), Box::new(DataType::Binary))
355            }
356            ArrowByteType::Dict16Utf8 => {
357                DataType::Dictionary(Box::new(DataType::UInt16), Box::new(DataType::Utf8))
358            }
359            ArrowByteType::Binary => DataType::Binary,
360            ArrowByteType::BinaryView => DataType::BinaryView,
361        }
362    }
363
364    fn is_string(&self) -> bool {
365        matches!(
366            self,
367            ArrowByteType::Utf8 | ArrowByteType::Utf8View | ArrowByteType::Dict16Utf8
368        )
369    }
370
371    pub fn from_arrow_type(ty: &DataType) -> Self {
372        match ty {
373            DataType::Utf8 => ArrowByteType::Utf8,
374            DataType::Utf8View => ArrowByteType::Utf8View,
375            DataType::Binary => ArrowByteType::Binary,
376            DataType::BinaryView => ArrowByteType::BinaryView,
377            DataType::Dictionary(_, _) => {
378                if ty
379                    == &DataType::Dictionary(Box::new(DataType::UInt16), Box::new(DataType::Binary))
380                {
381                    ArrowByteType::Dict16Binary
382                } else if ty
383                    == &DataType::Dictionary(Box::new(DataType::UInt16), Box::new(DataType::Utf8))
384                {
385                    ArrowByteType::Dict16Utf8
386                } else {
387                    panic!("Unsupported arrow type: {ty:?}")
388                }
389            }
390            _ => panic!("Unsupported arrow type: {ty:?}"),
391        }
392    }
393}
394
395/// An array that stores strings in a dictionary format, with a bit-packed array for the keys and a FSST array for the values.
396#[derive(Debug, Clone)]
397pub struct LiquidByteArray {
398    keys: BitPackedArray<UInt16Type>,
399    /// TODO: we need to specify that the values in the FsstArray must be unique, this enables us some optimizations.
400    values: FsstArray,
401    /// Used to convert back to the original arrow type.
402    original_arrow_type: ArrowByteType,
403}
404
405impl LiquidByteArray {
406    /// Create a LiquidByteArray from an Arrow [StringViewArray].
407    pub fn from_string_view_array(array: &StringViewArray, compressor: Arc<Compressor>) -> Self {
408        let dict = CheckedDictionaryArray::from_string_view_array(array);
409        Self::from_dict_array_inner(dict, compressor, ArrowByteType::Utf8View)
410    }
411
412    /// Create a LiquidByteArray from an Arrow [BinaryViewArray].
413    pub fn from_binary_view_array(array: &BinaryViewArray, compressor: Arc<Compressor>) -> Self {
414        let dict = CheckedDictionaryArray::from_binary_view_array(array);
415        Self::from_dict_array_inner(dict, compressor, ArrowByteType::BinaryView)
416    }
417
418    /// Train a compressor from an iterator of byte arrays.
419    pub fn train_compressor_bytes<'a, T: ArrayAccessor<Item = &'a [u8]>>(
420        array: ArrayIter<T>,
421    ) -> Arc<Compressor> {
422        let strings = array.filter_map(|s| s.as_ref().map(|s| *s));
423        Arc::new(FsstArray::train_compressor(strings))
424    }
425
426    /// Train a compressor from an iterator of strings.
427    pub fn train_compressor<'a, T: ArrayAccessor<Item = &'a str>>(
428        array: ArrayIter<T>,
429    ) -> Arc<Compressor> {
430        let strings = array.filter_map(|s| s.as_ref().map(|s| s.as_bytes()));
431        Arc::new(FsstArray::train_compressor(strings))
432    }
433
434    /// Create a LiquidByteArray from an Arrow [StringArray].
435    pub fn from_string_array(array: &StringArray, compressor: Arc<Compressor>) -> Self {
436        Self::from_byte_array(array, compressor)
437    }
438
439    /// Create a LiquidByteArray from an Arrow ByteArray.
440    pub fn from_byte_array<T: ByteArrayType>(
441        array: &GenericByteArray<T>,
442        compressor: Arc<Compressor>,
443    ) -> Self {
444        let dict = CheckedDictionaryArray::from_byte_array::<T>(array);
445        Self::from_dict_array_inner(
446            dict,
447            compressor,
448            ArrowByteType::from_arrow_type(&T::DATA_TYPE),
449        )
450    }
451
452    /// Train a compressor from an Arrow StringViewArray.
453    pub fn train_from_string_view(array: &StringViewArray) -> (Arc<Compressor>, Self) {
454        let dict = CheckedDictionaryArray::from_string_view_array(array);
455        let compressor = Self::train_compressor(dict.as_ref().values().as_string::<i32>().iter());
456        (
457            compressor.clone(),
458            Self::from_dict_array_inner(dict, compressor, ArrowByteType::Utf8View),
459        )
460    }
461
462    /// Train a compressor from an Arrow BinaryViewArray.
463    pub fn train_from_binary_view(array: &BinaryViewArray) -> (Arc<Compressor>, Self) {
464        let dict = CheckedDictionaryArray::from_binary_view_array(array);
465        let compressor =
466            Self::train_compressor_bytes(dict.as_ref().values().as_binary::<i32>().iter());
467        (
468            compressor.clone(),
469            Self::from_dict_array_inner(dict, compressor, ArrowByteType::BinaryView),
470        )
471    }
472
473    /// Train a compressor from an Arrow ByteArray.
474    pub fn train_from_arrow<T: ByteArrayType>(
475        array: &GenericByteArray<T>,
476    ) -> (Arc<Compressor>, Self) {
477        let dict = CheckedDictionaryArray::from_byte_array::<T>(array);
478        let value_type = dict.as_ref().values().data_type();
479
480        let compressor = if value_type == &DataType::Utf8 {
481            Self::train_compressor(dict.as_ref().values().as_string::<i32>().iter())
482        } else {
483            Self::train_compressor_bytes(dict.as_ref().values().as_binary::<i32>().iter())
484        };
485        (
486            compressor.clone(),
487            Self::from_dict_array_inner(
488                dict,
489                compressor,
490                ArrowByteType::from_arrow_type(&T::DATA_TYPE),
491            ),
492        )
493    }
494
495    /// Train a compressor from an Arrow DictionaryArray.
496    pub fn train_from_arrow_dict(array: &DictionaryArray<UInt16Type>) -> (Arc<Compressor>, Self) {
497        if array.values().data_type() == &DataType::Utf8 {
498            let values = array.values().as_string::<i32>();
499
500            let compressor = Self::train_compressor(values.iter());
501            (
502                compressor.clone(),
503                Self::from_dict_array_inner(
504                    CheckedDictionaryArray::new_checked(array),
505                    compressor,
506                    ArrowByteType::Dict16Utf8,
507                ),
508            )
509        } else if array.values().data_type() == &DataType::Binary {
510            let values = array.values().as_binary::<i32>();
511            let compressor = Self::train_compressor_bytes(values.iter());
512            (
513                compressor.clone(),
514                Self::from_dict_array_inner(
515                    CheckedDictionaryArray::new_checked(array),
516                    compressor,
517                    ArrowByteType::Dict16Binary,
518                ),
519            )
520        } else {
521            panic!("Unsupported dictionary type: {:?}", array.data_type())
522        }
523    }
524
525    /// Create a LiquidByteArray from an Arrow DictionaryArray.
526    fn from_dict_array_inner(
527        array: CheckedDictionaryArray,
528        compressor: Arc<Compressor>,
529        arrow_type: ArrowByteType,
530    ) -> Self {
531        let bit_width_for_key = array.bit_width_for_key();
532        let (keys, values) = array.into_inner().into_parts();
533
534        let bit_packed_array = BitPackedArray::from_primitive(keys, bit_width_for_key);
535
536        let fsst_values = if let Some(values) = values.as_string_opt::<i32>() {
537            FsstArray::from_byte_array_with_compressor(values, compressor)
538        } else if let Some(values) = values.as_binary_opt::<i32>() {
539            FsstArray::from_byte_array_with_compressor(values, compressor)
540        } else {
541            panic!("Unsupported dictionary type")
542        };
543        LiquidByteArray {
544            keys: bit_packed_array,
545            values: fsst_values,
546            original_arrow_type: arrow_type,
547        }
548    }
549
550    /// Only used when the dictionary is read from a trusted parquet reader,
551    /// which reads a trusted parquet file, written by a trusted writer.
552    ///
553    /// # Safety
554    /// The caller must ensure that the values in the dictionary are unique.
555    pub unsafe fn from_unique_dict_array(
556        array: &DictionaryArray<UInt16Type>,
557        compressor: Arc<Compressor>,
558    ) -> Self {
559        let arrow_type = ArrowByteType::from_arrow_type(array.values().data_type());
560        Self::from_dict_array_inner(
561            unsafe { CheckedDictionaryArray::new_unchecked_i_know_what_i_am_doing(array) },
562            compressor,
563            arrow_type,
564        )
565    }
566
567    /// Create a LiquidByteArray from an Arrow DictionaryArray.
568    pub fn from_dict_array(
569        array: &DictionaryArray<UInt16Type>,
570        compressor: Arc<Compressor>,
571    ) -> Self {
572        if array.downcast_dict::<StringArray>().is_some() {
573            let dict = CheckedDictionaryArray::new_checked(array);
574            Self::from_dict_array_inner(dict, compressor, ArrowByteType::Dict16Utf8)
575        } else if array.downcast_dict::<BinaryArray>().is_some() {
576            let dict = CheckedDictionaryArray::new_checked(array);
577            Self::from_dict_array_inner(dict, compressor, ArrowByteType::Dict16Binary)
578        } else {
579            panic!("Unsupported dictionary type: {:?}", array.data_type())
580        }
581    }
582
583    /// Get the decompressor of the LiquidStringArray.
584    pub fn decompressor(&self) -> Decompressor<'_> {
585        self.values.decompressor()
586    }
587
588    /// Convert the LiquidStringArray to arrow's DictionaryArray.
589    pub fn to_dict_arrow(&self) -> DictionaryArray<UInt16Type> {
590        if self.keys.len() < 2048 || self.keys.len() < self.values.len() {
591            // a heuristic to selective decompress.
592            self.to_dict_arrow_decompress_keyed()
593        } else {
594            self.to_dict_arrow_decompress_all()
595        }
596    }
597
598    fn to_dict_arrow_decompress_all(&self) -> DictionaryArray<UInt16Type> {
599        let primitive_key = self.keys.to_primitive();
600        if self.original_arrow_type.is_string() {
601            let values = self.values.to_arrow_byte_array::<Utf8Type>();
602            unsafe { DictionaryArray::<UInt16Type>::new_unchecked(primitive_key, Arc::new(values)) }
603        } else {
604            let values = self.values.to_arrow_byte_array::<BinaryType>();
605            unsafe { DictionaryArray::<UInt16Type>::new_unchecked(primitive_key, Arc::new(values)) }
606        }
607    }
608
609    fn to_dict_arrow_decompress_keyed(&self) -> DictionaryArray<UInt16Type> {
610        let primitive_key = self.keys.to_primitive();
611        let mut hit_mask = BooleanBufferBuilder::new(self.values.len());
612        hit_mask.advance(self.values.len());
613        for v in primitive_key.iter().flatten() {
614            hit_mask.set_bit(v as usize, true);
615        }
616        let hit_mask = hit_mask.finish();
617        let selected_cnt = hit_mask.count_set_bits();
618
619        let mut key_map =
620            HashMap::with_capacity_and_hasher(selected_cnt, ahash::RandomState::new());
621        let mut offset = 0;
622        for (i, select) in hit_mask.iter().enumerate() {
623            if select {
624                key_map.insert(i, offset);
625                offset += 1;
626            }
627        }
628        let new_keys = UInt16Array::from_iter(
629            primitive_key
630                .iter()
631                .map(|v| v.map(|v| key_map[&(v as usize)])),
632        );
633
634        let decompressor = self.values.decompressor();
635        let mut value_buffer: Vec<u8> = Vec::with_capacity(self.values.uncompressed_bytes() + 8);
636        let mut offsets_builder = BufferBuilder::<i32>::new(selected_cnt + 1);
637        offsets_builder.append(0);
638
639        assert_eq!(hit_mask.len(), self.values.len());
640        for (_select, v) in hit_mask
641            .iter()
642            .zip(self.values.compressed().iter())
643            .filter(|(select, _v)| *select)
644        {
645            let v = v.expect("values array can't be null");
646            let slice = unsafe {
647                std::slice::from_raw_parts_mut(
648                    value_buffer.as_mut_ptr().add(value_buffer.len()) as *mut MaybeUninit<u8>,
649                    value_buffer.capacity(),
650                )
651            };
652            let len = decompressor.decompress_into(v, slice);
653            let new_len = value_buffer.len() + len;
654            debug_assert!(new_len <= value_buffer.capacity());
655            unsafe {
656                value_buffer.set_len(new_len);
657            }
658            offsets_builder.append(value_buffer.len() as i32);
659        }
660        value_buffer.shrink_to_fit();
661        let value_buffer = Buffer::from(value_buffer);
662        let offsets_buffer: ScalarBuffer<i32> = ScalarBuffer::from(offsets_builder.finish());
663        let values = if self.original_arrow_type.is_string() {
664            unsafe {
665                Arc::new(GenericByteArray::<Utf8Type>::new_unchecked(
666                    OffsetBuffer::new_unchecked(offsets_buffer),
667                    value_buffer,
668                    None,
669                )) as ArrayRef
670            }
671        } else {
672            unsafe {
673                Arc::new(GenericByteArray::<BinaryType>::new_unchecked(
674                    OffsetBuffer::new_unchecked(offsets_buffer),
675                    value_buffer,
676                    None,
677                ))
678            }
679        };
680        unsafe { DictionaryArray::<UInt16Type>::new_unchecked(new_keys, values) }
681    }
682
683    /// Convert the LiquidStringArray to a DictionaryArray with a selection.
684    pub fn to_dict_arrow_with_selection(
685        &self,
686        selection: &BooleanArray,
687    ) -> DictionaryArray<UInt16Type> {
688        let primitive_key = self.keys.to_primitive().clone();
689        let filtered_keys = arrow::compute::filter(&primitive_key, selection)
690            .unwrap()
691            .as_primitive::<UInt16Type>()
692            .clone();
693        let values: StringArray = StringArray::from(&self.values);
694        unsafe { DictionaryArray::<UInt16Type>::new_unchecked(filtered_keys, Arc::new(values)) }
695    }
696
697    /// Convert the LiquidStringArray to a StringArray.
698    pub fn to_arrow_array(&self) -> ArrayRef {
699        let dict = self.to_dict_arrow();
700        cast(&dict, &self.original_arrow_type.to_arrow_type()).unwrap()
701    }
702
703    /// Compare the values of the LiquidStringArray with a given string and return a BooleanArray of the result.
704    pub fn compare_not_equals(&self, needle: &str) -> BooleanArray {
705        let result = self.compare_equals(needle);
706        let (values, nulls) = result.into_parts();
707        let values = !&values;
708        BooleanArray::new(values, nulls)
709    }
710
711    /// Get the nulls of the LiquidStringArray.
712    pub fn nulls(&self) -> Option<&NullBuffer> {
713        self.keys.nulls()
714    }
715
716    /// Compare the values of the LiquidStringArray with a given string.
717    /// Leverage the distinct values to speed up the comparison.
718    /// TODO: We can further optimize this by vectorizing the comparison.
719    pub fn compare_equals(&self, needle: &str) -> BooleanArray {
720        let compressor = self.values.compressor();
721        let compressed = compressor.compress(needle.as_bytes());
722
723        let values = self.values.compressed();
724        let keys = self.keys.to_primitive();
725
726        let idx = values.iter().position(|v| v == Some(compressed.as_ref()));
727
728        if let Some(idx) = idx {
729            let to_compare = UInt16Array::new_scalar(idx as u16);
730            arrow::compute::kernels::cmp::eq(&keys, &to_compare).unwrap()
731        } else {
732            let buffer = BooleanBuffer::new_unset(keys.len());
733            BooleanArray::new(buffer, self.nulls().cloned())
734        }
735    }
736}
737
738#[cfg(test)]
739mod tests {
740    use crate::liquid_array::LiquidPrimitiveArray;
741
742    use super::*;
743    use arrow::{
744        array::{Array, Int32Array},
745        datatypes::Int32Type,
746    };
747    use bytes::Bytes;
748    use datafusion::physical_plan::expressions::Column;
749    use std::num::NonZero;
750
751    fn test_roundtrip(input: StringArray) {
752        let compressor = LiquidByteArray::train_compressor(input.iter());
753        let liquid_array = LiquidByteArray::from_string_array(&input, compressor.clone());
754        let output = liquid_array.to_arrow_array();
755        assert_eq!(&input, output.as_string::<i32>());
756
757        let bytes = liquid_array.to_bytes_inner();
758        let bytes = Bytes::from(bytes);
759        let deserialized = LiquidByteArray::from_bytes(bytes, compressor);
760        let output = deserialized.to_arrow_array();
761        assert_eq!(&input, output.as_string::<i32>());
762    }
763
764    #[test]
765    fn test_simple_roundtrip() {
766        let input = StringArray::from(vec!["hello", "world", "hello", "rust"]);
767        test_roundtrip(input);
768    }
769
770    #[test]
771    fn test_original_arrow_data_type_returns_utf8() {
772        let input = StringArray::from(vec!["alpha", "beta"]);
773        let compressor = LiquidByteArray::train_compressor(input.iter());
774        let array = LiquidByteArray::from_string_array(&input, compressor);
775        assert_eq!(array.original_arrow_data_type(), DataType::Utf8);
776    }
777
778    #[test]
779    fn test_to_arrow_array_preserve_arrow_type() {
780        let input = StringArray::from(vec!["hello", "world", "hello", "rust"]);
781        let compressor = LiquidByteArray::train_compressor(input.iter());
782        let etc = LiquidByteArray::from_string_array(&input, compressor);
783        let output = etc.to_arrow_array();
784        assert_eq!(&input, output.as_string::<i32>());
785
786        let input = cast(&input, &DataType::Utf8View)
787            .unwrap()
788            .as_string_view()
789            .clone();
790        let compressor = LiquidByteArray::train_compressor(input.iter());
791        let etc = LiquidByteArray::from_string_view_array(&input, compressor);
792        let output = etc.to_arrow_array();
793        assert_eq!(&input, output.as_string_view());
794
795        let input = cast(
796            &input,
797            &DataType::Dictionary(Box::new(DataType::UInt16), Box::new(DataType::Utf8)),
798        )
799        .unwrap()
800        .as_dictionary()
801        .clone();
802        let compressor =
803            LiquidByteArray::train_compressor(input.values().as_string::<i32>().iter());
804        let etc = LiquidByteArray::from_dict_array(&input, compressor);
805        let output = etc.to_arrow_array();
806        assert_eq!(&input, output.as_dictionary());
807    }
808
809    // moved to shared tests in tests.rs: roundtrip with duplicates and long strings
810
811    #[test]
812    fn test_dictionary_roundtrip() {
813        let input = StringArray::from(vec!["hello", "world", "hello", "rust"]);
814        let compressor = LiquidByteArray::train_compressor(input.iter());
815        let etc = LiquidByteArray::from_string_array(&input, compressor);
816        let dict = etc.to_dict_arrow();
817
818        // Check dictionary values are unique
819        let dict_values = dict.values();
820        let unique_values: std::collections::HashSet<&str> = dict_values
821            .as_string::<i32>()
822            .into_iter()
823            .flatten()
824            .collect();
825
826        assert_eq!(unique_values.len(), 3); // "hello", "world", "rust"
827
828        // Convert back to string array and verify
829        let output = etc.to_arrow_array();
830        let string_array = output.as_string::<i32>();
831        assert_eq!(input.len(), string_array.len());
832        for i in 0..input.len() {
833            assert_eq!(input.value(i), string_array.value(i));
834        }
835    }
836
837    #[test]
838    fn test_compare_equals_comprehensive() {
839        struct TestCase<'a> {
840            input: Vec<Option<&'a str>>,
841            needle: &'a str,
842            expected: Vec<Option<bool>>,
843        }
844
845        let test_cases = vec![
846            TestCase {
847                input: vec![Some("hello"), Some("world"), Some("hello"), Some("rust")],
848                needle: "hello",
849                expected: vec![Some(true), Some(false), Some(true), Some(false)],
850            },
851            TestCase {
852                input: vec![Some("hello"), Some("world"), Some("hello"), Some("rust")],
853                needle: "nonexistent",
854                expected: vec![Some(false), Some(false), Some(false), Some(false)],
855            },
856            TestCase {
857                input: vec![Some("hello"), None, Some("hello"), None, Some("world")],
858                needle: "hello",
859                expected: vec![Some(true), None, Some(true), None, Some(false)],
860            },
861            TestCase {
862                input: vec![Some(""), Some("hello"), Some(""), Some("world")],
863                needle: "",
864                expected: vec![Some(true), Some(false), Some(true), Some(false)],
865            },
866            TestCase {
867                input: vec![Some("same"), Some("same"), Some("same"), Some("same")],
868                needle: "same",
869                expected: vec![Some(true), Some(true), Some(true), Some(true)],
870            },
871            TestCase {
872                input: vec![
873                    Some("apple"),
874                    None,
875                    Some("banana"),
876                    Some("apple"),
877                    None,
878                    Some("cherry"),
879                ],
880                needle: "apple",
881                expected: vec![Some(true), None, Some(false), Some(true), None, Some(false)],
882            },
883            TestCase {
884                input: vec![Some("Hello"), Some("hello"), Some("HELLO"), Some("HeLLo")],
885                needle: "hello",
886                expected: vec![Some(false), Some(true), Some(false), Some(false)],
887            },
888            TestCase {
889                input: vec![
890                    Some("こんにちは"), // "Hello" in Japanese
891                    Some("世界"),       // "World" in Japanese
892                    Some("こんにちは"),
893                    Some("rust"),
894                ],
895                needle: "こんにちは",
896                expected: vec![Some(true), Some(false), Some(true), Some(false)],
897            },
898            TestCase {
899                input: vec![Some("123"), Some("456"), Some("123"), Some("789")],
900                needle: "123",
901                expected: vec![Some(true), Some(false), Some(true), Some(false)],
902            },
903            TestCase {
904                input: vec![Some("@home"), Some("#rust"), Some("@home"), Some("$money")],
905                needle: "@home",
906                expected: vec![Some(true), Some(false), Some(true), Some(false)],
907            },
908            TestCase {
909                input: vec![None, None, None, None, Some("world")],
910                needle: "hello",
911                expected: vec![None, None, None, None, Some(false)],
912            },
913            // This cannot pass because the nulls are not handled correctly in `BitPackedArray::from_primitive`
914            // TestCase {
915            //     input: vec![None, None, None, None],
916            //     needle: "hello",
917            //     expected: vec![None, None, None, None],
918            // },
919        ];
920
921        for case in test_cases {
922            let input_array: StringArray = StringArray::from(case.input.clone());
923
924            let compressor = LiquidByteArray::train_compressor(input_array.iter());
925            let etc = LiquidByteArray::from_string_array(&input_array, compressor);
926
927            let result: BooleanArray = etc.compare_equals(case.needle);
928
929            let expected_array: BooleanArray = BooleanArray::from(case.expected.clone());
930
931            assert_eq!(result, expected_array,);
932        }
933    }
934
935    // moved to shared tests in tests.rs: to_dict_arrow_preserves_value_type_shared
936
937    #[test]
938    fn test_decompress_keyed_all_same_value() {
939        // Tests when all keys reference the same compressed value
940        let input_values = vec!["repeat"; 8];
941        let input_array = StringArray::from(input_values);
942
943        // Create liquid array with all keys pointing to index 0
944        let compressor = LiquidByteArray::train_compressor(input_array.iter());
945        let mut etc = LiquidByteArray::from_string_array(&input_array, compressor);
946        etc.keys = BitPackedArray::from_primitive(
947            UInt16Array::from(vec![0; 1000]),
948            NonZero::new(1).unwrap(),
949        );
950
951        let dict = etc.to_dict_arrow_decompress_keyed();
952
953        // Verify only one unique value exists
954        assert_eq!(dict.values().len(), 1);
955        assert_eq!(dict.values().as_string::<i32>().value(0), "repeat");
956
957        // Verify all keys are remapped to 0
958        let keys = dict.keys();
959        assert!(keys.iter().all(|v| v == Some(0)));
960    }
961
962    #[test]
963    fn test_decompress_keyed_sparse_references() {
964        // Tests when only a subset of values are referenced
965        let values = vec!["a", "b", "c", "d", "e"];
966        let input_keys = UInt16Array::from(vec![0, 2, 4, 2, 0]); // References a, c, e, c, a
967        let input_array = StringArray::from(values.clone());
968
969        let compressor = LiquidByteArray::train_compressor(input_array.iter());
970        let etc = LiquidByteArray {
971            keys: BitPackedArray::from_primitive(input_keys.clone(), NonZero::new(3).unwrap()),
972            values: FsstArray::from_byte_array_with_compressor(&input_array, compressor),
973            original_arrow_type: ArrowByteType::Dict16Utf8,
974        };
975
976        let dict = etc.to_dict_arrow_decompress_keyed();
977
978        // Should only decompress a, c, e (indexes 0,2,4 from original)
979        assert_eq!(dict.values().len(), 3);
980        let dict_values = dict.values().as_string::<i32>();
981        assert_eq!(dict_values.value(0), "a");
982        assert_eq!(dict_values.value(1), "c");
983        assert_eq!(dict_values.value(2), "e");
984
985        // Verify key remapping: original 0→0, 2→1, 4→2
986        let expected_keys = UInt16Array::from(vec![0, 1, 2, 1, 0]);
987        assert_eq!(dict.keys(), &expected_keys);
988    }
989
990    #[test]
991    fn test_decompress_keyed_with_nulls_and_unreferenced() {
992        // Tests null handling and unreferenced values
993        let values = vec!["a", "b", "c", "d"];
994        let input_keys = UInt16Array::from(vec![Some(0), None, Some(3), Some(0), None, Some(2)]);
995        let input_array = StringArray::from(values.clone());
996
997        let compressor = LiquidByteArray::train_compressor(input_array.iter());
998        let etc = LiquidByteArray {
999            keys: BitPackedArray::from_primitive(input_keys.clone(), NonZero::new(2).unwrap()),
1000            values: FsstArray::from_byte_array_with_compressor(&input_array, compressor),
1001            original_arrow_type: ArrowByteType::Dict16Utf8,
1002        };
1003
1004        let dict = etc.to_dict_arrow_decompress_keyed();
1005
1006        // Verify values
1007        assert_eq!(dict.values().len(), 3);
1008        let dict_values = dict.values().as_string::<i32>();
1009        assert_eq!(dict_values.value(0), "a");
1010        assert_eq!(dict_values.value(1), "c");
1011        assert_eq!(dict_values.value(2), "d");
1012
1013        // Verify keys and nulls
1014        let expected_keys = UInt16Array::from(vec![Some(0), None, Some(2), Some(0), None, Some(1)]);
1015        assert_eq!(dict.keys(), &expected_keys);
1016        assert_eq!(dict.nulls(), input_keys.nulls());
1017    }
1018
1019    #[test]
1020    fn test_roundtrip_edge_cases() {
1021        use arrow::array::StringBuilder;
1022
1023        // Create a string array with various edge cases
1024        let mut builder = StringBuilder::new();
1025
1026        // Empty string
1027        builder.append_value("");
1028
1029        // Section of nulls
1030        for _ in 0..10 {
1031            builder.append_null();
1032        }
1033
1034        // Very long string
1035        let long_string = "a".repeat(10_000);
1036        builder.append_value(&long_string);
1037
1038        // Unicode and special characters
1039        builder.append_value("こんにちは世界"); // Hello world in Japanese
1040        builder.append_value("🚀🔥🌈⭐"); // Emoji characters
1041        builder.append_value("Special chars: !@#$%^&*(){}[]|\\/.,<>?`~");
1042
1043        // Single character strings
1044        for c in "abcdefghijklmnopqrstuvwxyz".chars() {
1045            builder.append_value(c.to_string());
1046        }
1047
1048        // Highly repetitive string to test compression effectiveness
1049        builder.append_value("ABABABABABABABABABABABABABABAB");
1050
1051        // Test the roundtrip
1052        let string_array = builder.finish();
1053        test_roundtrip(string_array);
1054    }
1055
1056    #[test]
1057    fn test_filter_all_nulls() {
1058        let original: Vec<Option<&str>> = vec![None, None, None];
1059        let array = StringArray::from(original.clone());
1060        let compressor = LiquidByteArray::train_compressor(array.iter());
1061        let liquid_array = LiquidByteArray::from_string_array(&array, compressor);
1062        let result_array = liquid_array.filter(&BooleanBuffer::from(vec![true, false, true]));
1063        let result_array = result_array.to_arrow_array();
1064
1065        assert_eq!(result_array.len(), 2);
1066        assert_eq!(result_array.null_count(), 2);
1067    }
1068
1069    #[test]
1070    fn test_get_string_needle() {
1071        // Test Utf8 scalar value
1072        let utf8_value = ScalarValue::Utf8(Some("test_string".to_string()));
1073        assert_eq!(get_string_needle(&utf8_value), Some("test_string"));
1074
1075        // Test Utf8View scalar value
1076        let utf8_view_value = ScalarValue::Utf8View(Some("test_view".to_string()));
1077        assert_eq!(get_string_needle(&utf8_view_value), Some("test_view"));
1078
1079        // Test LargeUtf8 scalar value
1080        let large_utf8_value = ScalarValue::LargeUtf8(Some("test_large".to_string()));
1081        assert_eq!(get_string_needle(&large_utf8_value), Some("test_large"));
1082
1083        // Test Dictionary scalar value
1084        let dict_inner = ScalarValue::Utf8(Some("test_dict".to_string()));
1085        let dict_value = ScalarValue::Dictionary(
1086            Box::new(arrow_schema::DataType::Int32),
1087            Box::new(dict_inner),
1088        );
1089        assert_eq!(get_string_needle(&dict_value), Some("test_dict"));
1090
1091        // Test None values
1092        let utf8_none = ScalarValue::Utf8(None);
1093        assert_eq!(get_string_needle(&utf8_none), None);
1094
1095        // Test non-string scalar value
1096        let int_value = ScalarValue::Int32(Some(42));
1097        assert_eq!(get_string_needle(&int_value), None);
1098    }
1099
1100    #[test]
1101    fn test_try_eval_predicate_inner_string_equality() {
1102        use datafusion::logical_expr::Operator;
1103        use datafusion::physical_expr::expressions::BinaryExpr;
1104        use datafusion::physical_plan::expressions::{Column, Literal};
1105        use datafusion::scalar::ScalarValue;
1106
1107        // Test the optimized string equality path
1108        let string_data = vec!["apple", "banana", "cherry", "apple", "grape"];
1109        let arrow_array = StringViewArray::from(string_data);
1110        let (_compressor, liquid_array) = LiquidByteArray::train_from_string_view(&arrow_array);
1111
1112        // Create predicate: column = "apple"
1113        let expr: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
1114            Arc::new(Column::new("test_col", 0)),
1115            Operator::Eq,
1116            Arc::new(Literal::new(ScalarValue::Utf8(Some("apple".to_string())))),
1117        ));
1118
1119        let result = try_eval_predicate_inner(&expr, &liquid_array).unwrap();
1120        let boolean_array = result;
1121        assert_eq!(boolean_array.len(), 5);
1122
1123        // Should match indices 0 and 3 (both "apple")
1124        assert!(boolean_array.value(0)); // "apple"
1125        assert!(!boolean_array.value(1)); // "banana"
1126        assert!(!boolean_array.value(2)); // "cherry"
1127        assert!(boolean_array.value(3)); // "apple"
1128        assert!(!boolean_array.value(4)); // "grape"
1129    }
1130
1131    #[test]
1132    fn test_try_eval_predicate_inner_numeric_not_supported() {
1133        // Test that numeric comparisons are not supported and return None
1134        let numeric_data = vec![10, 20, 30, 15, 25];
1135        let arrow_array = Int32Array::from(numeric_data);
1136        let liquid_array = LiquidPrimitiveArray::<Int32Type>::from_arrow_array(arrow_array);
1137        let liquid_ref: LiquidArrayRef = Arc::new(liquid_array);
1138
1139        // Create predicate: column > 20
1140        let expr: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
1141            Arc::new(Column::new("test_col", 0)),
1142            Operator::Gt,
1143            Arc::new(Literal::new(ScalarValue::Int32(Some(20)))),
1144        ));
1145
1146        let filter = BooleanBuffer::from(vec![true; liquid_ref.len()]);
1147        let result = liquid_ref.try_eval_predicate(&expr, &filter);
1148        // Numeric comparisons are not supported, should return None
1149        assert!(result.is_none());
1150
1151        // Test other numeric operators that are also not supported
1152        let eq_expr: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
1153            Arc::new(Column::new("test_col", 0)),
1154            Operator::Eq,
1155            Arc::new(Literal::new(ScalarValue::Int32(Some(20)))),
1156        ));
1157
1158        let result = liquid_ref.try_eval_predicate(&eq_expr, &filter);
1159        assert!(result.is_none());
1160    }
1161
1162    #[test]
1163    fn test_try_eval_predicate_inner_unsupported_expression() {
1164        // Test unsupported expression types that should return None
1165        let numeric_data = vec![10, 20, 30, 15, 25];
1166        let arrow_array = Int32Array::from(numeric_data);
1167        let liquid_array = LiquidPrimitiveArray::<Int32Type>::from_arrow_array(arrow_array);
1168        let liquid_ref: LiquidArrayRef = Arc::new(liquid_array);
1169
1170        // Create unsupported predicate: column + 5 (not column op literal)
1171        let add_expr: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
1172            Arc::new(Column::new("test_col", 0)),
1173            Operator::Plus,
1174            Arc::new(Literal::new(ScalarValue::Int32(Some(5)))),
1175        ));
1176
1177        let filter = BooleanBuffer::from(vec![true; liquid_ref.len()]);
1178        let result = liquid_ref.try_eval_predicate(&add_expr, &filter);
1179        assert!(result.is_none());
1180
1181        // Test another unsupported case: literal op column (wrong order)
1182        let wrong_order_expr: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
1183            Arc::new(Literal::new(ScalarValue::Int32(Some(20)))),
1184            Operator::Eq,
1185            Arc::new(Column::new("test_col", 0)),
1186        ));
1187
1188        let result = liquid_ref.try_eval_predicate(&wrong_order_expr, &filter);
1189        assert!(result.is_none());
1190
1191        // Test column-column comparison (not column-literal)
1192        let col_col_expr: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
1193            Arc::new(Column::new("col1", 0)),
1194            Operator::Eq,
1195            Arc::new(Column::new("col2", 1)),
1196        ));
1197
1198        let result = liquid_ref.try_eval_predicate(&col_col_expr, &filter);
1199        assert!(result.is_none());
1200    }
1201
1202    #[test]
1203    fn test_train_from_binary_view() {
1204        // Create binary data with some repeated patterns for compression
1205        let binary_data: Vec<&[u8]> = vec![
1206            b"hello",
1207            b"world",
1208            b"hello",              // duplicate
1209            b"test\x00\x01\x02",   // with null bytes
1210            b"world",              // duplicate
1211            b"binary\xff\xfe\xfd", // with high bytes
1212        ];
1213
1214        let input = BinaryViewArray::from_iter_values(binary_data.iter().copied());
1215
1216        // Test train_from_binary_view
1217        let (compressor, liquid_array1) = LiquidByteArray::train_from_binary_view(&input);
1218
1219        // Verify the liquid array has correct properties
1220        assert_eq!(liquid_array1.len(), input.len());
1221        assert_eq!(liquid_array1.original_arrow_type, ArrowByteType::BinaryView);
1222
1223        // Test roundtrip conversion with train_from_binary_view
1224        let output1 = liquid_array1.to_arrow_array();
1225        let output_binary_view1 = output1.as_binary_view();
1226
1227        // Verify all values match
1228        assert_eq!(input.len(), output_binary_view1.len());
1229        for i in 0..input.len() {
1230            assert_eq!(input.value(i), output_binary_view1.value(i));
1231        }
1232
1233        // Test from_binary_view_array with the same compressor
1234        let liquid_array2 = LiquidByteArray::from_binary_view_array(&input, compressor);
1235
1236        // Verify the second liquid array has correct properties
1237        assert_eq!(liquid_array2.len(), input.len());
1238        assert_eq!(liquid_array2.original_arrow_type, ArrowByteType::BinaryView);
1239
1240        // Test roundtrip conversion with from_binary_view_array
1241        let output2 = liquid_array2.to_arrow_array();
1242        let output_binary_view2 = output2.as_binary_view();
1243
1244        // Verify all values match
1245        assert_eq!(input.len(), output_binary_view2.len());
1246        for i in 0..input.len() {
1247            assert_eq!(input.value(i), output_binary_view2.value(i));
1248        }
1249
1250        // Both methods should produce equivalent results
1251        let dict1 = liquid_array1.to_dict_arrow();
1252        let dict2 = liquid_array2.to_dict_arrow();
1253        assert_eq!(dict1.keys(), dict2.keys());
1254        assert_eq!(dict1.values().len(), dict2.values().len());
1255    }
1256
1257    #[test]
1258    fn test_train_from_binary_view_with_nulls() {
1259        let binary_data: Vec<Option<&[u8]>> = vec![
1260            Some(b"data1"),
1261            None,
1262            Some(b"data2"),
1263            None,
1264            Some(b"data1"), // duplicate
1265        ];
1266
1267        let input = BinaryViewArray::from(binary_data.clone());
1268        let (compressor, liquid_array1) = LiquidByteArray::train_from_binary_view(&input);
1269
1270        // Verify roundtrip with nulls for train_from_binary_view
1271        let output1 = liquid_array1.to_arrow_array();
1272        let output_binary_view1 = output1.as_binary_view();
1273
1274        assert_eq!(input.len(), output_binary_view1.len());
1275        assert_eq!(input.null_count(), output_binary_view1.null_count());
1276
1277        for i in 0..input.len() {
1278            if input.is_null(i) {
1279                assert!(output_binary_view1.is_null(i));
1280            } else {
1281                assert_eq!(input.value(i), output_binary_view1.value(i));
1282            }
1283        }
1284
1285        // Test from_binary_view_array with nulls
1286        let liquid_array2 = LiquidByteArray::from_binary_view_array(&input, compressor);
1287
1288        // Verify roundtrip with nulls for from_binary_view_array
1289        let output2 = liquid_array2.to_arrow_array();
1290        let output_binary_view2 = output2.as_binary_view();
1291
1292        assert_eq!(input.len(), output_binary_view2.len());
1293        assert_eq!(input.null_count(), output_binary_view2.null_count());
1294
1295        for i in 0..input.len() {
1296            if input.is_null(i) {
1297                assert!(output_binary_view2.is_null(i));
1298            } else {
1299                assert_eq!(input.value(i), output_binary_view2.value(i));
1300            }
1301        }
1302    }
1303}