Skip to main content

parquet/encodings/encoding/
mod.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18//! Contains all supported encoders for Parquet.
19
20use std::{cmp, marker::PhantomData};
21
22use crate::basic::*;
23use crate::data_type::private::ParquetValueType;
24use crate::data_type::*;
25use crate::encodings::rle::RleEncoder;
26use crate::errors::{ParquetError, Result};
27use crate::schema::types::ColumnDescPtr;
28use crate::util::bit_util::{BitWriter, num_required_bits};
29use crate::util::prefix::common_prefix_length;
30
31use alp_encoder::AlpEncoder;
32use byte_stream_split_encoder::{ByteStreamSplitEncoder, VariableWidthByteStreamSplitEncoder};
33use bytes::Bytes;
34pub use dict_encoder::DictEncoder;
35
36mod alp_encoder;
37mod byte_stream_split_encoder;
38mod dict_encoder;
39
40// ----------------------------------------------------------------------
41// Encoders
42
43/// An Parquet encoder for the data type `T`.
44///
45/// Currently this allocates internal buffers for the encoded values. After done putting
46/// values, caller should call `flush_buffer()` to get an immutable buffer pointer.
47pub trait Encoder<T: DataType>: Send {
48    /// Encodes data from `values`.
49    fn put(&mut self, values: &[T::T]) -> Result<()>;
50
51    /// Encodes data from `values`, which contains spaces for null values, that is
52    /// identified by `valid_bits`.
53    ///
54    /// Returns the number of non-null values encoded.
55    #[cfg(test)]
56    fn put_spaced(&mut self, values: &[T::T], valid_bits: &[u8]) -> Result<usize> {
57        let num_values = values.len();
58        let mut buffer = Vec::with_capacity(num_values);
59        // TODO: this is pretty inefficient. Revisit in future.
60        for (i, item) in values.iter().enumerate().take(num_values) {
61            if crate::util::bit_util::get_bit(valid_bits, i) {
62                buffer.push(item.clone());
63            }
64        }
65        self.put(&buffer[..])?;
66        Ok(buffer.len())
67    }
68
69    /// Returns the encoding type of this encoder.
70    fn encoding(&self) -> Encoding;
71
72    /// Returns an estimate of the encoded data, in bytes.
73    /// Method call must be O(1).
74    fn estimated_data_encoded_size(&self) -> usize;
75
76    /// Returns an estimate of the memory use of this encoder, in bytes
77    fn estimated_memory_size(&self) -> usize;
78
79    /// Flushes the underlying byte buffer that's being processed by this encoder, and
80    /// return the immutable copy of it. This will also reset the internal state.
81    fn flush_buffer(&mut self) -> Result<Bytes>;
82}
83
84/// Gets a encoder for the particular data type `T` and encoding `encoding`. Memory usage
85/// for the encoder instance is tracked by `mem_tracker`.
86pub fn get_encoder<T: DataType>(
87    encoding: Encoding,
88    descr: &ColumnDescPtr,
89) -> Result<Box<dyn Encoder<T>>> {
90    <T::T as private::GetEncoder>::get_encoder(descr, encoding)
91}
92
93pub(crate) mod private {
94    use super::*;
95
96    /// A trait that allows getting an [`Encoder`] implementation for a [`DataType`]
97    /// with the corresponding [`ParquetValueType`]. This is necessary to support
98    /// [`Encoder`] implementations that may not be applicable for all [`DataType`]
99    /// and by extension all [`ParquetValueType`], such as ALP, which encodes only
100    /// floating-point columns.
101    ///
102    /// [`ParquetValueType`]: crate::data_type::private::ParquetValueType
103    pub trait GetEncoder {
104        fn get_encoder<T: DataType<T = Self>>(
105            descr: &ColumnDescPtr,
106            encoding: Encoding,
107        ) -> Result<Box<dyn Encoder<T>>> {
108            get_encoder_default(descr, encoding)
109        }
110    }
111
112    fn get_encoder_default<T: DataType>(
113        descr: &ColumnDescPtr,
114        encoding: Encoding,
115    ) -> Result<Box<dyn Encoder<T>>> {
116        let encoder: Box<dyn Encoder<T>> = match encoding {
117            Encoding::PLAIN => Box::new(PlainEncoder::new()),
118            Encoding::RLE_DICTIONARY | Encoding::PLAIN_DICTIONARY => {
119                return Err(general_err!(
120                    "Cannot initialize this encoding through this function"
121                ));
122            }
123            Encoding::RLE => Box::new(RleValueEncoder::new()),
124            Encoding::DELTA_BINARY_PACKED => Box::new(DeltaBitPackEncoder::new()),
125            Encoding::DELTA_LENGTH_BYTE_ARRAY => Box::new(DeltaLengthByteArrayEncoder::new()),
126            Encoding::DELTA_BYTE_ARRAY => Box::new(DeltaByteArrayEncoder::new()),
127            Encoding::BYTE_STREAM_SPLIT => match T::get_physical_type() {
128                Type::FIXED_LEN_BYTE_ARRAY => Box::new(VariableWidthByteStreamSplitEncoder::new(
129                    descr.type_length(),
130                )),
131                _ => Box::new(ByteStreamSplitEncoder::new()),
132            },
133            Encoding::ALP => {
134                return Err(general_err!(
135                    "Encoding {} only supports FLOAT and DOUBLE, got {}",
136                    encoding,
137                    T::get_physical_type()
138                ));
139            }
140            #[expect(deprecated, reason = "BIT_PACKED is the encoding we reject here")]
141            e @ Encoding::BIT_PACKED => return Err(nyi_err!("Encoding {} is not supported", e)),
142        };
143        Ok(encoder)
144    }
145
146    impl GetEncoder for bool {}
147    impl GetEncoder for i32 {}
148    impl GetEncoder for i64 {}
149    impl GetEncoder for Int96 {}
150    impl GetEncoder for ByteArray {}
151    impl GetEncoder for FixedLenByteArray {}
152
153    impl GetEncoder for f32 {
154        fn get_encoder<T: DataType<T = Self>>(
155            descr: &ColumnDescPtr,
156            encoding: Encoding,
157        ) -> Result<Box<dyn Encoder<T>>> {
158            match encoding {
159                Encoding::ALP => Ok(Box::new(AlpEncoder::new())),
160                _ => get_encoder_default(descr, encoding),
161            }
162        }
163    }
164
165    impl GetEncoder for f64 {
166        fn get_encoder<T: DataType<T = Self>>(
167            descr: &ColumnDescPtr,
168            encoding: Encoding,
169        ) -> Result<Box<dyn Encoder<T>>> {
170            match encoding {
171                Encoding::ALP => Ok(Box::new(AlpEncoder::new())),
172                _ => get_encoder_default(descr, encoding),
173            }
174        }
175    }
176}
177
178// ----------------------------------------------------------------------
179// Plain encoding
180
181/// Plain encoding that supports all types.
182/// Values are encoded back to back.
183/// The plain encoding is used whenever a more efficient encoding can not be used.
184/// It stores the data in the following format:
185/// - BOOLEAN - 1 bit per value, 0 is false; 1 is true.
186/// - INT32 - 4 bytes per value, stored as little-endian.
187/// - INT64 - 8 bytes per value, stored as little-endian.
188/// - FLOAT - 4 bytes per value, stored as IEEE little-endian.
189/// - DOUBLE - 8 bytes per value, stored as IEEE little-endian.
190/// - BYTE_ARRAY - 4 byte length stored as little endian, followed by bytes.
191/// - FIXED_LEN_BYTE_ARRAY - just the bytes are stored.
192pub struct PlainEncoder<T: DataType> {
193    buffer: Vec<u8>,
194    bit_writer: BitWriter,
195    _phantom: PhantomData<T>,
196}
197
198impl<T: DataType> Default for PlainEncoder<T> {
199    fn default() -> Self {
200        Self::new()
201    }
202}
203
204impl<T: DataType> PlainEncoder<T> {
205    /// Creates new plain encoder.
206    pub fn new() -> Self {
207        Self {
208            buffer: vec![],
209            bit_writer: BitWriter::new(256),
210            _phantom: PhantomData,
211        }
212    }
213}
214
215impl<T: DataType> Encoder<T> for PlainEncoder<T> {
216    // Performance Note:
217    // As far as can be seen these functions are rarely called and as such we can hint to the
218    // compiler that they dont need to be folded into hot locations in the final output.
219    #[cold]
220    fn encoding(&self) -> Encoding {
221        Encoding::PLAIN
222    }
223
224    fn estimated_data_encoded_size(&self) -> usize {
225        self.buffer.len() + self.bit_writer.bytes_written()
226    }
227
228    #[inline]
229    fn flush_buffer(&mut self) -> Result<Bytes> {
230        self.buffer
231            .extend_from_slice(self.bit_writer.flush_buffer());
232        self.bit_writer.clear();
233        Ok(std::mem::take(&mut self.buffer).into())
234    }
235
236    #[inline]
237    fn put(&mut self, values: &[T::T]) -> Result<()> {
238        T::T::encode(values, &mut self.buffer, &mut self.bit_writer)?;
239        Ok(())
240    }
241
242    /// Return the estimated memory size of this encoder.
243    fn estimated_memory_size(&self) -> usize {
244        self.buffer.capacity() * std::mem::size_of::<u8>() + self.bit_writer.estimated_memory_size()
245    }
246}
247
248// ----------------------------------------------------------------------
249// RLE encoding
250
251const DEFAULT_RLE_BUFFER_LEN: usize = 1024;
252
253/// RLE/Bit-Packing hybrid encoding for values.
254/// Currently is used only for data pages v2 and supports boolean types.
255pub struct RleValueEncoder<T: DataType> {
256    // Buffer with raw values that we collect,
257    // when flushing buffer they are encoded using RLE encoder
258    encoder: Option<RleEncoder>,
259    _phantom: PhantomData<T>,
260}
261
262impl<T: DataType> Default for RleValueEncoder<T> {
263    fn default() -> Self {
264        Self::new()
265    }
266}
267
268impl<T: DataType> RleValueEncoder<T> {
269    /// Creates new rle value encoder.
270    pub fn new() -> Self {
271        Self {
272            encoder: None,
273            _phantom: PhantomData,
274        }
275    }
276}
277
278impl<T: DataType> Encoder<T> for RleValueEncoder<T> {
279    #[inline]
280    fn put(&mut self, values: &[T::T]) -> Result<()> {
281        ensure_phys_ty!(Type::BOOLEAN, "RleValueEncoder only supports BoolType");
282
283        let rle_encoder = self.encoder.get_or_insert_with(|| {
284            let mut buffer = Vec::with_capacity(DEFAULT_RLE_BUFFER_LEN);
285            // Reserve space for length
286            buffer.extend_from_slice(&[0; 4]);
287            RleEncoder::new_from_buf(1, buffer)
288        });
289
290        let mut buf = [0_u64; 64];
291        for chunk in values.chunks(buf.len()) {
292            let buf = &mut buf[..chunk.len()];
293            for (b, value) in buf.iter_mut().zip(chunk) {
294                *b = value.as_u64()?;
295            }
296            rle_encoder.put_batch(buf);
297        }
298        Ok(())
299    }
300
301    // Performance Note:
302    // As far as can be seen these functions are rarely called and as such we can hint to the
303    // compiler that they dont need to be folded into hot locations in the final output.
304    #[cold]
305    fn encoding(&self) -> Encoding {
306        Encoding::RLE
307    }
308
309    #[inline]
310    fn estimated_data_encoded_size(&self) -> usize {
311        match self.encoder {
312            Some(ref enc) => enc.len(),
313            None => 0,
314        }
315    }
316
317    #[inline]
318    fn flush_buffer(&mut self) -> Result<Bytes> {
319        ensure_phys_ty!(Type::BOOLEAN, "RleValueEncoder only supports BoolType");
320        let rle_encoder = self
321            .encoder
322            .take()
323            .expect("RLE value encoder is not initialized");
324
325        // Flush all encoder buffers and raw values
326        let mut buf = rle_encoder.consume();
327        assert!(buf.len() >= 4, "should have had padding inserted");
328
329        // Note that buf does not have any offset, all data is encoded bytes
330        let len = (buf.len() - 4) as i32;
331        buf[..4].copy_from_slice(&len.to_le_bytes());
332
333        Ok(buf.into())
334    }
335
336    /// return the estimated memory size of this encoder.
337    fn estimated_memory_size(&self) -> usize {
338        self.encoder
339            .as_ref()
340            .map_or(0, |enc| enc.estimated_memory_size())
341    }
342}
343
344// ----------------------------------------------------------------------
345// DELTA_BINARY_PACKED encoding
346
347const MAX_PAGE_HEADER_WRITER_SIZE: usize = 32;
348const DEFAULT_BIT_WRITER_SIZE: usize = 1024 * 1024;
349const DEFAULT_NUM_MINI_BLOCKS: usize = 4;
350
351/// Delta bit packed encoder.
352/// Consists of a header followed by blocks of delta encoded values binary packed.
353///
354/// Delta-binary-packing:
355/// ```shell
356///   [page-header] [block 1], [block 2], ... [block N]
357/// ```
358///
359/// Each page header consists of:
360/// ```shell
361///   [block size] [number of miniblocks in a block] [total value count] [first value]
362/// ```
363///
364/// Each block consists of:
365/// ```shell
366///   [min delta] [list of bitwidths of miniblocks] [miniblocks]
367/// ```
368///
369/// Current implementation writes values in `put` method, multiple calls to `put` to
370/// existing block or start new block if block size is exceeded. Calling `flush_buffer`
371/// writes out all data and resets internal state, including page header.
372///
373/// Supports only INT32 and INT64.
374pub struct DeltaBitPackEncoder<T: DataType> {
375    page_header_writer: BitWriter,
376    bit_writer: BitWriter,
377    total_values: usize,
378    first_value: i64,
379    current_value: i64,
380    block_size: usize,
381    mini_block_size: usize,
382    num_mini_blocks: usize,
383    values_in_block: usize,
384    deltas: Vec<i64>,
385    _phantom: PhantomData<T>,
386}
387
388impl<T: DataType> Default for DeltaBitPackEncoder<T> {
389    fn default() -> Self {
390        Self::new()
391    }
392}
393
394impl<T: DataType> DeltaBitPackEncoder<T> {
395    /// Creates new delta bit packed encoder.
396    pub fn new() -> Self {
397        Self::assert_supported_type();
398
399        // Size miniblocks so that they can be efficiently decoded
400        let mini_block_size = match T::T::PHYSICAL_TYPE {
401            Type::INT32 => 32,
402            Type::INT64 => 64,
403            _ => unreachable!(),
404        };
405
406        let num_mini_blocks = DEFAULT_NUM_MINI_BLOCKS;
407        let block_size = mini_block_size * num_mini_blocks;
408        assert_eq!(block_size % 128, 0);
409
410        DeltaBitPackEncoder {
411            page_header_writer: BitWriter::new(MAX_PAGE_HEADER_WRITER_SIZE),
412            bit_writer: BitWriter::new(DEFAULT_BIT_WRITER_SIZE),
413            total_values: 0,
414            first_value: 0,
415            current_value: 0, // current value to keep adding deltas
416            block_size,       // can write fewer values than block size for last block
417            mini_block_size,
418            num_mini_blocks,
419            values_in_block: 0, // will be at most block_size
420            deltas: vec![0; block_size],
421            _phantom: PhantomData,
422        }
423    }
424
425    /// Writes page header for blocks, this method is invoked when we are done encoding
426    /// values. It is also okay to encode when no values have been provided
427    fn write_page_header(&mut self) {
428        // We ignore the result of each 'put' operation, because
429        // MAX_PAGE_HEADER_WRITER_SIZE is chosen to fit all header values and
430        // guarantees that writes will not fail.
431
432        // Write the size of each block
433        self.page_header_writer.put_vlq_int(self.block_size as u64);
434        // Write the number of mini blocks
435        self.page_header_writer
436            .put_vlq_int(self.num_mini_blocks as u64);
437        // Write the number of all values (including non-encoded first value)
438        self.page_header_writer
439            .put_vlq_int(self.total_values as u64);
440        // Write first value
441        self.page_header_writer.put_zigzag_vlq_int(self.first_value);
442    }
443
444    // Write current delta buffer (<= 'block size' values) into bit writer
445    #[inline(never)]
446    fn flush_block_values(&mut self) -> Result<()> {
447        if self.values_in_block == 0 {
448            return Ok(());
449        }
450
451        let mut min_delta = i64::MAX;
452        for i in 0..self.values_in_block {
453            min_delta = cmp::min(min_delta, self.deltas[i]);
454        }
455
456        // Write min delta
457        self.bit_writer.put_zigzag_vlq_int(min_delta);
458
459        // Slice to store bit width for each mini block
460        let offset = self.bit_writer.skip(self.num_mini_blocks);
461
462        for i in 0..self.num_mini_blocks {
463            // Find how many values we need to encode - either block size or whatever
464            // values left
465            let n = cmp::min(self.mini_block_size, self.values_in_block);
466            if n == 0 {
467                // Decoders should be agnostic to the padding value, we therefore use 0xFF
468                // when running tests. However, not all implementations may handle this correctly
469                // so pad with 0 when not running tests
470                let pad_value = cfg!(test).then(|| 0xFF).unwrap_or(0);
471                for j in i..self.num_mini_blocks {
472                    self.bit_writer.write_at(offset + j, pad_value);
473                }
474                break;
475            }
476
477            // Compute the max delta in current mini block
478            let mut max_delta = i64::MIN;
479            for j in 0..n {
480                max_delta = cmp::max(max_delta, self.deltas[i * self.mini_block_size + j]);
481            }
482
483            // Compute bit width to store (max_delta - min_delta)
484            let bit_width = num_required_bits(self.subtract_u64(max_delta, min_delta)) as usize;
485            self.bit_writer.write_at(offset + i, bit_width as u8);
486
487            // Encode values in current mini block using min_delta and bit_width. This
488            // mini block's deltas are not read again, so they can be rewritten in place
489            // with the values to pack
490            let start = i * self.mini_block_size;
491            for j in start..start + n {
492                self.deltas[j] = self.subtract_u64(self.deltas[j], min_delta) as i64;
493            }
494            self.bit_writer
495                .put_batch(&self.deltas[start..start + n], bit_width);
496
497            // Pad the last block (n < mini_block_size)
498            for _ in n..self.mini_block_size {
499                self.bit_writer.put_value(0, bit_width);
500            }
501
502            self.values_in_block -= n;
503        }
504
505        assert_eq!(
506            self.values_in_block, 0,
507            "Expected 0 values in block, found {}",
508            self.values_in_block
509        );
510        Ok(())
511    }
512}
513
514// Implementation is shared between Int32Type and Int64Type,
515// see `DeltaBitPackEncoderConversion` below for specifics.
516impl<T: DataType> Encoder<T> for DeltaBitPackEncoder<T> {
517    fn put(&mut self, values: &[T::T]) -> Result<()> {
518        if values.is_empty() {
519            return Ok(());
520        }
521
522        // Define values to encode, initialize state
523        let mut idx = if self.total_values == 0 {
524            self.first_value = self.as_i64(values, 0);
525            self.current_value = self.first_value;
526            1
527        } else {
528            0
529        };
530        // Add all values (including first value)
531        self.total_values += values.len();
532
533        // Write block
534        while idx < values.len() {
535            let value = self.as_i64(values, idx);
536            self.deltas[self.values_in_block] = self.subtract(value, self.current_value);
537            self.current_value = value;
538            idx += 1;
539            self.values_in_block += 1;
540            if self.values_in_block == self.block_size {
541                self.flush_block_values()?;
542            }
543        }
544        Ok(())
545    }
546
547    // Performance Note:
548    // As far as can be seen these functions are rarely called and as such we can hint to the
549    // compiler that they dont need to be folded into hot locations in the final output.
550    #[cold]
551    fn encoding(&self) -> Encoding {
552        Encoding::DELTA_BINARY_PACKED
553    }
554
555    fn estimated_data_encoded_size(&self) -> usize {
556        self.bit_writer.bytes_written()
557    }
558
559    fn flush_buffer(&mut self) -> Result<Bytes> {
560        // Write remaining values
561        self.flush_block_values()?;
562        // Write page header with total values
563        self.write_page_header();
564
565        let mut buffer = Vec::new();
566        buffer.extend_from_slice(self.page_header_writer.flush_buffer());
567        buffer.extend_from_slice(self.bit_writer.flush_buffer());
568
569        // Reset state
570        self.page_header_writer.clear();
571        self.bit_writer.clear();
572        self.total_values = 0;
573        self.first_value = 0;
574        self.current_value = 0;
575        self.values_in_block = 0;
576
577        Ok(buffer.into())
578    }
579
580    /// return the estimated memory size of this encoder.
581    fn estimated_memory_size(&self) -> usize {
582        self.page_header_writer.estimated_memory_size()
583            + self.bit_writer.estimated_memory_size()
584            + self.deltas.capacity() * std::mem::size_of::<i64>()
585            + std::mem::size_of::<Self>()
586    }
587}
588
589/// Helper trait to define specific conversions and subtractions when computing deltas
590trait DeltaBitPackEncoderConversion<T: DataType> {
591    // Method should panic if type is not supported, otherwise no-op
592    fn assert_supported_type();
593
594    fn as_i64(&self, values: &[T::T], index: usize) -> i64;
595
596    fn subtract(&self, left: i64, right: i64) -> i64;
597
598    fn subtract_u64(&self, left: i64, right: i64) -> u64;
599}
600
601const DELTA_BIT_PACK_TYPE_ERROR: &str =
602    "DeltaBitPackDecoder only supports Int32Type, UInt32Type, Int64Type, and UInt64Type";
603
604impl<T: DataType> DeltaBitPackEncoderConversion<T> for DeltaBitPackEncoder<T> {
605    #[inline]
606    fn assert_supported_type() {
607        ensure_phys_ty!(Type::INT32 | Type::INT64, "{}", DELTA_BIT_PACK_TYPE_ERROR);
608    }
609
610    #[inline]
611    fn as_i64(&self, values: &[T::T], index: usize) -> i64 {
612        values[index].as_i64().expect(DELTA_BIT_PACK_TYPE_ERROR)
613    }
614
615    #[inline]
616    fn subtract(&self, left: i64, right: i64) -> i64 {
617        // It is okay for values to overflow, wrapping_sub wrapping around at the boundary
618        match T::get_physical_type() {
619            Type::INT32 => (left as i32).wrapping_sub(right as i32) as i64,
620            Type::INT64 => left.wrapping_sub(right),
621            _ => panic!("{}", DELTA_BIT_PACK_TYPE_ERROR),
622        }
623    }
624
625    #[inline]
626    fn subtract_u64(&self, left: i64, right: i64) -> u64 {
627        match T::get_physical_type() {
628            // Conversion of i32 -> u32 -> u64 is to avoid non-zero left most bytes in int repr
629            Type::INT32 => (left as i32).wrapping_sub(right as i32) as u32 as u64,
630            Type::INT64 => left.wrapping_sub(right) as u64,
631            _ => panic!("{}", DELTA_BIT_PACK_TYPE_ERROR),
632        }
633    }
634}
635
636// ----------------------------------------------------------------------
637// DELTA_LENGTH_BYTE_ARRAY encoding
638
639/// Encoding for byte arrays to separate the length values and the data.
640/// The lengths are encoded using DELTA_BINARY_PACKED encoding, data is
641/// stored as raw bytes.
642pub struct DeltaLengthByteArrayEncoder<T: DataType> {
643    // length encoder
644    len_encoder: DeltaBitPackEncoder<Int32Type>,
645    // byte array data
646    data: Vec<ByteArray>,
647    // data size in bytes of encoded values
648    encoded_size: usize,
649    _phantom: PhantomData<T>,
650}
651
652impl<T: DataType> Default for DeltaLengthByteArrayEncoder<T> {
653    fn default() -> Self {
654        Self::new()
655    }
656}
657
658impl<T: DataType> DeltaLengthByteArrayEncoder<T> {
659    /// Creates new delta length byte array encoder.
660    pub fn new() -> Self {
661        Self {
662            len_encoder: DeltaBitPackEncoder::new(),
663            data: vec![],
664            encoded_size: 0,
665            _phantom: PhantomData,
666        }
667    }
668}
669
670impl<T: DataType> Encoder<T> for DeltaLengthByteArrayEncoder<T> {
671    fn put(&mut self, values: &[T::T]) -> Result<()> {
672        ensure_phys_ty!(
673            Type::BYTE_ARRAY | Type::FIXED_LEN_BYTE_ARRAY,
674            "DeltaLengthByteArrayEncoder only supports ByteArrayType"
675        );
676
677        let val_it = || {
678            values
679                .iter()
680                .map(|x| x.as_any().downcast_ref::<ByteArray>().unwrap())
681        };
682
683        let lengths: Vec<i32> = val_it().map(|byte_array| byte_array.len() as i32).collect();
684        self.len_encoder.put(&lengths)?;
685        for byte_array in val_it() {
686            self.encoded_size += byte_array.len();
687            self.data.push(byte_array.clone());
688        }
689
690        Ok(())
691    }
692
693    // Performance Note:
694    // As far as can be seen these functions are rarely called and as such we can hint to the
695    // compiler that they dont need to be folded into hot locations in the final output.
696    #[cold]
697    fn encoding(&self) -> Encoding {
698        Encoding::DELTA_LENGTH_BYTE_ARRAY
699    }
700
701    fn estimated_data_encoded_size(&self) -> usize {
702        self.len_encoder.estimated_data_encoded_size() + self.encoded_size
703    }
704
705    fn flush_buffer(&mut self) -> Result<Bytes> {
706        ensure_phys_ty!(
707            Type::BYTE_ARRAY | Type::FIXED_LEN_BYTE_ARRAY,
708            "DeltaLengthByteArrayEncoder only supports ByteArrayType"
709        );
710
711        let mut total_bytes = vec![];
712        let lengths = self.len_encoder.flush_buffer()?;
713        total_bytes.extend_from_slice(&lengths);
714        self.data.iter().for_each(|byte_array| {
715            total_bytes.extend_from_slice(byte_array.data());
716        });
717        self.data.clear();
718        self.encoded_size = 0;
719
720        Ok(total_bytes.into())
721    }
722
723    /// return the estimated memory size of this encoder.
724    fn estimated_memory_size(&self) -> usize {
725        self.len_encoder.estimated_memory_size() + self.data.len() + std::mem::size_of::<Self>()
726    }
727}
728
729// ----------------------------------------------------------------------
730// DELTA_BYTE_ARRAY encoding
731
732/// Encoding for byte arrays, prefix lengths are encoded using DELTA_BINARY_PACKED
733/// encoding, followed by suffixes with DELTA_LENGTH_BYTE_ARRAY encoding.
734pub struct DeltaByteArrayEncoder<T: DataType> {
735    prefix_len_encoder: DeltaBitPackEncoder<Int32Type>,
736    suffix_writer: DeltaLengthByteArrayEncoder<ByteArrayType>,
737    previous: Vec<u8>,
738    _phantom: PhantomData<T>,
739}
740
741impl<T: DataType> Default for DeltaByteArrayEncoder<T> {
742    fn default() -> Self {
743        Self::new()
744    }
745}
746
747impl<T: DataType> DeltaByteArrayEncoder<T> {
748    /// Creates new delta byte array encoder.
749    pub fn new() -> Self {
750        Self {
751            prefix_len_encoder: DeltaBitPackEncoder::new(),
752            suffix_writer: DeltaLengthByteArrayEncoder::new(),
753            previous: vec![],
754            _phantom: PhantomData,
755        }
756    }
757}
758
759impl<T: DataType> Encoder<T> for DeltaByteArrayEncoder<T> {
760    fn put(&mut self, values: &[T::T]) -> Result<()> {
761        let mut prefix_lengths: Vec<i32> = vec![];
762        let mut suffixes: Vec<ByteArray> = vec![];
763
764        let values = values
765            .iter()
766            .map(|x| x.as_any())
767            .map(|x| match T::get_physical_type() {
768                Type::BYTE_ARRAY => x.downcast_ref::<ByteArray>().unwrap(),
769                Type::FIXED_LEN_BYTE_ARRAY => x.downcast_ref::<FixedLenByteArray>().unwrap(),
770                _ => panic!(
771                    "DeltaByteArrayEncoder only supports ByteArrayType and FixedLenByteArrayType"
772                ),
773            });
774
775        for byte_array in values {
776            let current = byte_array.data();
777            // Number of leading bytes shared with the previous value
778            let match_len = common_prefix_length(&self.previous, current);
779            prefix_lengths.push(match_len as i32);
780            suffixes.push(byte_array.slice(match_len, byte_array.len() - match_len));
781            // Update previous for the next prefix
782            self.previous.clear();
783            self.previous.extend_from_slice(current);
784        }
785        self.prefix_len_encoder.put(&prefix_lengths)?;
786        self.suffix_writer.put(&suffixes)?;
787
788        Ok(())
789    }
790
791    // Performance Note:
792    // As far as can be seen these functions are rarely called and as such we can hint to the
793    // compiler that they dont need to be folded into hot locations in the final output.
794    #[cold]
795    fn encoding(&self) -> Encoding {
796        Encoding::DELTA_BYTE_ARRAY
797    }
798
799    fn estimated_data_encoded_size(&self) -> usize {
800        self.prefix_len_encoder.estimated_data_encoded_size()
801            + self.suffix_writer.estimated_data_encoded_size()
802    }
803
804    fn flush_buffer(&mut self) -> Result<Bytes> {
805        match T::get_physical_type() {
806            Type::BYTE_ARRAY | Type::FIXED_LEN_BYTE_ARRAY => {
807                // TODO: investigate if we can merge lengths and suffixes
808                // without copying data into new vector.
809                let mut total_bytes = vec![];
810                // Insert lengths ...
811                let lengths = self.prefix_len_encoder.flush_buffer()?;
812                total_bytes.extend_from_slice(&lengths);
813                // ... followed by suffixes
814                let suffixes = self.suffix_writer.flush_buffer()?;
815                total_bytes.extend_from_slice(&suffixes);
816
817                self.previous.clear();
818                Ok(total_bytes.into())
819            }
820            _ => panic!(
821                "DeltaByteArrayEncoder only supports ByteArrayType and FixedLenByteArrayType"
822            ),
823        }
824    }
825
826    /// return the estimated memory size of this encoder.
827    fn estimated_memory_size(&self) -> usize {
828        self.prefix_len_encoder.estimated_memory_size()
829            + self.suffix_writer.estimated_memory_size()
830            + (self.previous.capacity() * std::mem::size_of::<u8>())
831    }
832}
833
834#[cfg(test)]
835mod tests {
836    use super::*;
837
838    use std::sync::Arc;
839
840    use crate::encodings::decoding::{Decoder, DictDecoder, PlainDecoder, get_decoder};
841    use crate::schema::types::{ColumnDescPtr, ColumnDescriptor, ColumnPath, Type as SchemaType};
842    use crate::util::bit_util;
843    use crate::util::test_common::rand_gen::{RandGen, random_bytes};
844
845    const TEST_SET_SIZE: usize = 1024;
846
847    #[test]
848    fn test_get_encoders() {
849        // supported encodings
850        create_and_check_encoder::<Int32Type>(0, Encoding::PLAIN, None);
851        create_and_check_encoder::<Int32Type>(0, Encoding::DELTA_BINARY_PACKED, None);
852        create_and_check_encoder::<Int32Type>(0, Encoding::DELTA_LENGTH_BYTE_ARRAY, None);
853        create_and_check_encoder::<Int32Type>(0, Encoding::DELTA_BYTE_ARRAY, None);
854        create_and_check_encoder::<BoolType>(0, Encoding::RLE, None);
855
856        // error when initializing
857        create_and_check_encoder::<Int32Type>(
858            0,
859            Encoding::RLE_DICTIONARY,
860            Some(general_err!(
861                "Cannot initialize this encoding through this function"
862            )),
863        );
864        create_and_check_encoder::<Int32Type>(
865            0,
866            Encoding::PLAIN_DICTIONARY,
867            Some(general_err!(
868                "Cannot initialize this encoding through this function"
869            )),
870        );
871        create_and_check_encoder::<Int32Type>(
872            0,
873            Encoding::ALP,
874            Some(general_err!(
875                "Encoding ALP only supports FLOAT and DOUBLE, got INT32"
876            )),
877        );
878
879        // unsupported
880        #[expect(deprecated)]
881        create_and_check_encoder::<Int32Type>(
882            0,
883            Encoding::BIT_PACKED,
884            Some(nyi_err!("Encoding BIT_PACKED is not supported")),
885        );
886    }
887
888    #[test]
889    fn test_bool() {
890        BoolType::test(Encoding::PLAIN, TEST_SET_SIZE, -1);
891        BoolType::test(Encoding::PLAIN_DICTIONARY, TEST_SET_SIZE, -1);
892        BoolType::test(Encoding::RLE, TEST_SET_SIZE, -1);
893    }
894
895    #[test]
896    #[cfg_attr(miri, ignore)] // Takes too long
897    fn test_i32() {
898        Int32Type::test(Encoding::PLAIN, TEST_SET_SIZE, -1);
899        Int32Type::test(Encoding::PLAIN_DICTIONARY, TEST_SET_SIZE, -1);
900        Int32Type::test(Encoding::DELTA_BINARY_PACKED, TEST_SET_SIZE, -1);
901        Int32Type::test(Encoding::BYTE_STREAM_SPLIT, TEST_SET_SIZE, -1);
902    }
903
904    #[test]
905    #[cfg_attr(miri, ignore)] // Takes too long
906    fn test_i64() {
907        Int64Type::test(Encoding::PLAIN, TEST_SET_SIZE, -1);
908        Int64Type::test(Encoding::PLAIN_DICTIONARY, TEST_SET_SIZE, -1);
909        Int64Type::test(Encoding::DELTA_BINARY_PACKED, TEST_SET_SIZE, -1);
910        Int64Type::test(Encoding::BYTE_STREAM_SPLIT, TEST_SET_SIZE, -1);
911    }
912
913    #[test]
914    #[cfg_attr(miri, ignore)] // Takes too long
915    fn test_i96() {
916        Int96Type::test(Encoding::PLAIN, TEST_SET_SIZE, -1);
917        Int96Type::test(Encoding::PLAIN_DICTIONARY, TEST_SET_SIZE, -1);
918    }
919
920    #[test]
921    fn test_float() {
922        FloatType::test(Encoding::PLAIN, TEST_SET_SIZE, -1);
923        FloatType::test(Encoding::PLAIN_DICTIONARY, TEST_SET_SIZE, -1);
924        FloatType::test(Encoding::BYTE_STREAM_SPLIT, TEST_SET_SIZE, -1);
925    }
926
927    #[test]
928    #[cfg_attr(miri, ignore)] // Takes too long
929    fn test_double() {
930        DoubleType::test(Encoding::PLAIN, TEST_SET_SIZE, -1);
931        DoubleType::test(Encoding::PLAIN_DICTIONARY, TEST_SET_SIZE, -1);
932        DoubleType::test(Encoding::BYTE_STREAM_SPLIT, TEST_SET_SIZE, -1);
933    }
934
935    #[test]
936    #[cfg_attr(miri, ignore)] // Takes too long
937    fn test_byte_array() {
938        ByteArrayType::test(Encoding::PLAIN, TEST_SET_SIZE, -1);
939        ByteArrayType::test(Encoding::PLAIN_DICTIONARY, TEST_SET_SIZE, -1);
940        ByteArrayType::test(Encoding::DELTA_LENGTH_BYTE_ARRAY, TEST_SET_SIZE, -1);
941        ByteArrayType::test(Encoding::DELTA_BYTE_ARRAY, TEST_SET_SIZE, -1);
942    }
943
944    #[test]
945    #[cfg_attr(miri, ignore)] // Takes too long
946    fn test_fixed_len_byte_array() {
947        FixedLenByteArrayType::test(Encoding::PLAIN, TEST_SET_SIZE, 100);
948        FixedLenByteArrayType::test(Encoding::PLAIN_DICTIONARY, TEST_SET_SIZE, 100);
949        FixedLenByteArrayType::test(Encoding::DELTA_BYTE_ARRAY, TEST_SET_SIZE, 100);
950        FixedLenByteArrayType::test(Encoding::BYTE_STREAM_SPLIT, TEST_SET_SIZE, 100);
951    }
952
953    #[test]
954    fn test_dict_encoded_size() {
955        fn run_test<T: DataType>(type_length: i32, values: &[T::T], expected_size: usize) {
956            let mut encoder = create_test_dict_encoder::<T>(type_length);
957            assert_eq!(encoder.dict_encoded_size(), 0);
958            encoder.put(values).unwrap();
959            assert_eq!(encoder.dict_encoded_size(), expected_size);
960            // We do not reset encoded size of the dictionary keys after flush_buffer
961            encoder.flush_buffer().unwrap();
962            assert_eq!(encoder.dict_encoded_size(), expected_size);
963        }
964
965        // Only 2 variations of values 1 byte each
966        run_test::<BoolType>(-1, &[true, false, true, false, true], 2);
967        run_test::<Int32Type>(-1, &[1i32, 2i32, 3i32, 4i32, 5i32], 20);
968        run_test::<Int64Type>(-1, &[1i64, 2i64, 3i64, 4i64, 5i64], 40);
969        run_test::<FloatType>(-1, &[1f32, 2f32, 3f32, 4f32, 5f32], 20);
970        run_test::<DoubleType>(-1, &[1f64, 2f64, 3f64, 4f64, 5f64], 40);
971        // Int96: len + reference
972        run_test::<Int96Type>(
973            -1,
974            &[Int96::from(vec![1, 2, 3]), Int96::from(vec![2, 3, 4])],
975            24,
976        );
977        run_test::<ByteArrayType>(-1, &[ByteArray::from("abcd"), ByteArray::from("efj")], 15);
978        run_test::<FixedLenByteArrayType>(
979            2,
980            &[ByteArray::from("ab").into(), ByteArray::from("bc").into()],
981            4,
982        );
983    }
984
985    #[test]
986    fn test_estimated_data_encoded_size() {
987        fn run_test<T: DataType>(
988            encoding: Encoding,
989            type_length: i32,
990            values: &[T::T],
991            initial_size: usize,
992            max_size: usize,
993            flush_size: usize,
994        ) {
995            let mut encoder = match encoding {
996                Encoding::PLAIN_DICTIONARY | Encoding::RLE_DICTIONARY => {
997                    Box::new(create_test_dict_encoder::<T>(type_length))
998                }
999                _ => create_test_encoder::<T>(type_length, encoding),
1000            };
1001            assert_eq!(encoder.estimated_data_encoded_size(), initial_size);
1002
1003            encoder.put(values).unwrap();
1004            assert_eq!(encoder.estimated_data_encoded_size(), max_size);
1005
1006            encoder.flush_buffer().unwrap();
1007            assert_eq!(encoder.estimated_data_encoded_size(), flush_size);
1008        }
1009
1010        // PLAIN
1011        run_test::<Int32Type>(Encoding::PLAIN, -1, &[123; 1024], 0, 4096, 0);
1012
1013        // DICTIONARY
1014        // NOTE: The final size is almost the same because the dictionary entries are
1015        // preserved after encoded values have been written.
1016        run_test::<Int32Type>(Encoding::RLE_DICTIONARY, -1, &[123, 1024], 0, 2, 0);
1017
1018        // DELTA_BINARY_PACKED
1019        run_test::<Int32Type>(Encoding::DELTA_BINARY_PACKED, -1, &[123; 1024], 0, 35, 0);
1020
1021        // RLE
1022        let mut values = vec![];
1023        values.extend_from_slice(&[true; 16]);
1024        values.extend_from_slice(&[false; 16]);
1025        run_test::<BoolType>(Encoding::RLE, -1, &values, 0, 6, 0);
1026
1027        // DELTA_LENGTH_BYTE_ARRAY
1028        run_test::<ByteArrayType>(
1029            Encoding::DELTA_LENGTH_BYTE_ARRAY,
1030            -1,
1031            &[ByteArray::from("ab"), ByteArray::from("abc")],
1032            0,
1033            5, // only value bytes, length encoder is not flushed yet
1034            0,
1035        );
1036
1037        // DELTA_BYTE_ARRAY
1038        run_test::<ByteArrayType>(
1039            Encoding::DELTA_BYTE_ARRAY,
1040            -1,
1041            &[ByteArray::from("ab"), ByteArray::from("abc")],
1042            0,
1043            3, // only suffix bytes, length encoder is not flushed yet
1044            0,
1045        );
1046
1047        // BYTE_STREAM_SPLIT
1048        run_test::<FloatType>(Encoding::BYTE_STREAM_SPLIT, -1, &[0.1, 0.2], 0, 8, 0);
1049    }
1050
1051    #[test]
1052    fn test_byte_stream_split_example_f32() {
1053        // Test data from https://github.com/apache/parquet-format/blob/2a481fe1aad64ff770e21734533bb7ef5a057dac/Encodings.md#byte-stream-split-byte_stream_split--9
1054        let mut encoder = create_test_encoder::<FloatType>(0, Encoding::BYTE_STREAM_SPLIT);
1055        let mut decoder = create_test_decoder::<FloatType>(0, Encoding::BYTE_STREAM_SPLIT);
1056
1057        let input = vec![
1058            f32::from_le_bytes([0xAA, 0xBB, 0xCC, 0xDD]),
1059            f32::from_le_bytes([0x00, 0x11, 0x22, 0x33]),
1060            f32::from_le_bytes([0xA3, 0xB4, 0xC5, 0xD6]),
1061        ];
1062
1063        encoder.put(&input).unwrap();
1064        let encoded = encoder.flush_buffer().unwrap();
1065
1066        assert_eq!(
1067            encoded,
1068            Bytes::from(vec![
1069                0xAA_u8, 0x00, 0xA3, 0xBB, 0x11, 0xB4, 0xCC, 0x22, 0xC5, 0xDD, 0x33, 0xD6
1070            ])
1071        );
1072
1073        let mut decoded = vec![0.0; input.len()];
1074        decoder.set_data(encoded, input.len()).unwrap();
1075        decoder.get(&mut decoded).unwrap();
1076
1077        assert_eq!(decoded, input);
1078    }
1079
1080    // See: https://github.com/sunchao/parquet-rs/issues/47
1081    #[test]
1082    fn test_issue_47() {
1083        let mut encoder = create_test_encoder::<ByteArrayType>(0, Encoding::DELTA_BYTE_ARRAY);
1084        let mut decoder = create_test_decoder::<ByteArrayType>(0, Encoding::DELTA_BYTE_ARRAY);
1085
1086        let input = vec![
1087            ByteArray::from("aa"),
1088            ByteArray::from("aaa"),
1089            ByteArray::from("aa"),
1090            ByteArray::from("aaa"),
1091        ];
1092
1093        let mut output = vec![ByteArray::default(); input.len()];
1094
1095        let mut result = put_and_get(&mut encoder, &mut decoder, &input[..2], &mut output[..2]);
1096        assert!(
1097            result.is_ok(),
1098            "first put_and_get() failed with: {}",
1099            result.unwrap_err()
1100        );
1101        result = put_and_get(&mut encoder, &mut decoder, &input[2..], &mut output[2..]);
1102        assert!(
1103            result.is_ok(),
1104            "second put_and_get() failed with: {}",
1105            result.unwrap_err()
1106        );
1107        assert_eq!(output, input);
1108    }
1109
1110    trait EncodingTester<T: DataType> {
1111        fn test(enc: Encoding, total: usize, type_length: i32) {
1112            let result = match enc {
1113                Encoding::PLAIN_DICTIONARY | Encoding::RLE_DICTIONARY => {
1114                    Self::test_dict_internal(total, type_length)
1115                }
1116                enc => Self::test_internal(enc, total, type_length),
1117            };
1118
1119            assert!(
1120                result.is_ok(),
1121                "Expected result to be OK but got err:\n {}",
1122                result.unwrap_err()
1123            );
1124        }
1125
1126        fn test_internal(enc: Encoding, total: usize, type_length: i32) -> Result<()>;
1127
1128        fn test_dict_internal(total: usize, type_length: i32) -> Result<()>;
1129    }
1130
1131    impl<T: DataType + RandGen<T>> EncodingTester<T> for T {
1132        fn test_internal(enc: Encoding, total: usize, type_length: i32) -> Result<()> {
1133            let mut encoder = create_test_encoder::<T>(type_length, enc);
1134            let mut decoder = create_test_decoder::<T>(type_length, enc);
1135            let mut values = <T as RandGen<T>>::gen_vec(type_length, total);
1136            let mut result_data = vec![T::T::default(); total];
1137
1138            // Test put/get spaced.
1139            let num_bytes = bit_util::ceil(total as i64, 8);
1140            let valid_bits = random_bytes(num_bytes as usize);
1141            let values_written = encoder.put_spaced(&values[..], &valid_bits[..])?;
1142            let data = encoder.flush_buffer()?;
1143            decoder.set_data(data, values_written)?;
1144            let _ = decoder.get_spaced(
1145                &mut result_data[..],
1146                values.len() - values_written,
1147                &valid_bits[..],
1148            )?;
1149
1150            // Check equality
1151            for i in 0..total {
1152                if bit_util::get_bit(&valid_bits[..], i) {
1153                    assert_eq!(result_data[i], values[i]);
1154                } else {
1155                    assert_eq!(result_data[i], T::T::default());
1156                }
1157            }
1158
1159            let mut actual_total = put_and_get(
1160                &mut encoder,
1161                &mut decoder,
1162                &values[..],
1163                &mut result_data[..],
1164            )?;
1165            assert_eq!(actual_total, total);
1166            assert_eq!(result_data, values);
1167
1168            // Encode more data after flush and test with decoder
1169
1170            values = <T as RandGen<T>>::gen_vec(type_length, total);
1171            actual_total = put_and_get(
1172                &mut encoder,
1173                &mut decoder,
1174                &values[..],
1175                &mut result_data[..],
1176            )?;
1177            assert_eq!(actual_total, total);
1178            assert_eq!(result_data, values);
1179
1180            Ok(())
1181        }
1182
1183        fn test_dict_internal(total: usize, type_length: i32) -> Result<()> {
1184            let mut encoder = create_test_dict_encoder::<T>(type_length);
1185            let mut values = <T as RandGen<T>>::gen_vec(type_length, total);
1186            encoder.put(&values[..])?;
1187
1188            let mut data = encoder.flush_buffer()?;
1189            let mut decoder = create_test_dict_decoder::<T>();
1190            let mut dict_decoder = PlainDecoder::<T>::new(type_length);
1191            dict_decoder.set_data(encoder.write_dict()?, encoder.num_entries())?;
1192            decoder.set_dict(Box::new(dict_decoder))?;
1193            let mut result_data = vec![T::T::default(); total];
1194            decoder.set_data(data, total)?;
1195            let mut actual_total = decoder.get(&mut result_data)?;
1196
1197            assert_eq!(actual_total, total);
1198            assert_eq!(result_data, values);
1199
1200            // Encode more data after flush and test with decoder
1201
1202            values = <T as RandGen<T>>::gen_vec(type_length, total);
1203            encoder.put(&values[..])?;
1204            data = encoder.flush_buffer()?;
1205
1206            let mut dict_decoder = PlainDecoder::<T>::new(type_length);
1207            dict_decoder.set_data(encoder.write_dict()?, encoder.num_entries())?;
1208            decoder.set_dict(Box::new(dict_decoder))?;
1209            decoder.set_data(data, total)?;
1210            actual_total = decoder.get(&mut result_data)?;
1211
1212            assert_eq!(actual_total, total);
1213            assert_eq!(result_data, values);
1214
1215            Ok(())
1216        }
1217    }
1218
1219    fn put_and_get<T: DataType>(
1220        encoder: &mut Box<dyn Encoder<T>>,
1221        decoder: &mut Box<dyn Decoder<T>>,
1222        input: &[T::T],
1223        output: &mut [T::T],
1224    ) -> Result<usize> {
1225        encoder.put(input)?;
1226        let data = encoder.flush_buffer()?;
1227        decoder.set_data(data, input.len())?;
1228        decoder.get(output)
1229    }
1230
1231    fn create_and_check_encoder<T: DataType>(
1232        type_length: i32,
1233        encoding: Encoding,
1234        err: Option<ParquetError>,
1235    ) {
1236        let desc = create_test_col_desc_ptr(type_length, T::get_physical_type());
1237        let encoder = get_encoder::<T>(encoding, &desc);
1238        match err {
1239            Some(parquet_error) => {
1240                assert_eq!(
1241                    encoder.err().unwrap().to_string(),
1242                    parquet_error.to_string()
1243                )
1244            }
1245            None => assert_eq!(encoder.unwrap().encoding(), encoding),
1246        }
1247    }
1248
1249    // Creates test column descriptor.
1250    fn create_test_col_desc_ptr(type_len: i32, t: Type) -> ColumnDescPtr {
1251        let ty = SchemaType::primitive_type_builder("t", t)
1252            .with_length(type_len)
1253            .build()
1254            .unwrap();
1255        Arc::new(ColumnDescriptor::new(
1256            Arc::new(ty),
1257            0,
1258            0,
1259            ColumnPath::new(vec![]),
1260        ))
1261    }
1262
1263    fn create_test_encoder<T: DataType>(type_len: i32, enc: Encoding) -> Box<dyn Encoder<T>> {
1264        let desc = create_test_col_desc_ptr(type_len, T::get_physical_type());
1265        get_encoder(enc, &desc).unwrap()
1266    }
1267
1268    fn create_test_decoder<T: DataType>(type_len: i32, enc: Encoding) -> Box<dyn Decoder<T>> {
1269        let desc = create_test_col_desc_ptr(type_len, T::get_physical_type());
1270        get_decoder(desc, enc).unwrap()
1271    }
1272
1273    fn create_test_dict_encoder<T: DataType>(type_len: i32) -> DictEncoder<T> {
1274        let desc = create_test_col_desc_ptr(type_len, T::get_physical_type());
1275        DictEncoder::<T>::new(desc)
1276    }
1277
1278    fn create_test_dict_decoder<T: DataType>() -> DictDecoder<T> {
1279        DictDecoder::<T>::new()
1280    }
1281}