Skip to main content

arrow_row/
fixed.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use crate::array::PrimitiveArray;
6use crate::null_sentinel;
7use arrow_array::{ArrowPrimitiveType, BooleanArray, FixedSizeBinaryArray};
8use arrow_buffer::{
9    BooleanBuffer, IntervalDayTime, IntervalMonthDayNano, MutableBuffer, NullBuffer, bit_util, i256,
10};
11use arrow_schema::{ArrowError, DataType, SortOptions};
12use half::f16;
13
14pub trait FromSlice {
15    fn from_slice(slice: &[u8], invert: bool) -> Self;
16}
17
18impl<const N: usize> FromSlice for [u8; N] {
19    #[inline]
20    fn from_slice(slice: &[u8], invert: bool) -> Self {
21        let mut t: Self = slice.try_into().unwrap();
22        if invert {
23            t.iter_mut().for_each(|o| *o = !*o);
24        }
25        t
26    }
27}
28
29/// Encodes a value of a particular fixed width type into bytes according to the rules
30/// described on [`super::RowConverter`]
31pub trait FixedLengthEncoding: Copy {
32    const ENCODED_LEN: usize = 1 + std::mem::size_of::<Self::Encoded>();
33
34    type Encoded: Sized + Copy + FromSlice + AsRef<[u8]> + AsMut<[u8]>;
35
36    fn encode(self) -> Self::Encoded;
37
38    fn decode(encoded: Self::Encoded) -> Self;
39}
40
41impl FixedLengthEncoding for bool {
42    type Encoded = [u8; 1];
43
44    fn encode(self) -> [u8; 1] {
45        [self as u8]
46    }
47
48    fn decode(encoded: Self::Encoded) -> Self {
49        encoded[0] != 0
50    }
51}
52
53macro_rules! encode_signed {
54    ($n:expr, $t:ty) => {
55        impl FixedLengthEncoding for $t {
56            type Encoded = [u8; $n];
57
58            fn encode(self) -> [u8; $n] {
59                let mut b = self.to_be_bytes();
60                // Toggle top "sign" bit to ensure consistent sort order
61                b[0] ^= 0x80;
62                b
63            }
64
65            fn decode(mut encoded: Self::Encoded) -> Self {
66                // Toggle top "sign" bit
67                encoded[0] ^= 0x80;
68                Self::from_be_bytes(encoded)
69            }
70        }
71    };
72}
73
74encode_signed!(1, i8);
75encode_signed!(2, i16);
76encode_signed!(4, i32);
77encode_signed!(8, i64);
78encode_signed!(16, i128);
79encode_signed!(32, i256);
80
81macro_rules! encode_unsigned {
82    ($n:expr, $t:ty) => {
83        impl FixedLengthEncoding for $t {
84            type Encoded = [u8; $n];
85
86            fn encode(self) -> [u8; $n] {
87                self.to_be_bytes()
88            }
89
90            fn decode(encoded: Self::Encoded) -> Self {
91                Self::from_be_bytes(encoded)
92            }
93        }
94    };
95}
96
97encode_unsigned!(1, u8);
98encode_unsigned!(2, u16);
99encode_unsigned!(4, u32);
100encode_unsigned!(8, u64);
101
102impl FixedLengthEncoding for f16 {
103    type Encoded = [u8; 2];
104
105    fn encode(self) -> [u8; 2] {
106        // https://github.com/rust-lang/rust/blob/9c20b2a8cc7588decb6de25ac6a7912dcef24d65/library/core/src/num/f32.rs#L1176-L1260
107        let s = self.to_bits() as i16;
108        let val = s ^ (((s >> 15) as u16) >> 1) as i16;
109        val.encode()
110    }
111
112    fn decode(encoded: Self::Encoded) -> Self {
113        let bits = i16::decode(encoded);
114        let val = bits ^ (((bits >> 15) as u16) >> 1) as i16;
115        Self::from_bits(val as u16)
116    }
117}
118
119impl FixedLengthEncoding for f32 {
120    type Encoded = [u8; 4];
121
122    fn encode(self) -> [u8; 4] {
123        // https://github.com/rust-lang/rust/blob/9c20b2a8cc7588decb6de25ac6a7912dcef24d65/library/core/src/num/f32.rs#L1176-L1260
124        let s = self.to_bits() as i32;
125        let val = s ^ (((s >> 31) as u32) >> 1) as i32;
126        val.encode()
127    }
128
129    fn decode(encoded: Self::Encoded) -> Self {
130        let bits = i32::decode(encoded);
131        let val = bits ^ (((bits >> 31) as u32) >> 1) as i32;
132        Self::from_bits(val as u32)
133    }
134}
135
136impl FixedLengthEncoding for f64 {
137    type Encoded = [u8; 8];
138
139    fn encode(self) -> [u8; 8] {
140        // https://github.com/rust-lang/rust/blob/9c20b2a8cc7588decb6de25ac6a7912dcef24d65/library/core/src/num/f32.rs#L1176-L1260
141        let s = self.to_bits() as i64;
142        let val = s ^ (((s >> 63) as u64) >> 1) as i64;
143        val.encode()
144    }
145
146    fn decode(encoded: Self::Encoded) -> Self {
147        let bits = i64::decode(encoded);
148        let val = bits ^ (((bits >> 63) as u64) >> 1) as i64;
149        Self::from_bits(val as u64)
150    }
151}
152
153impl FixedLengthEncoding for IntervalDayTime {
154    type Encoded = [u8; 8];
155
156    fn encode(self) -> Self::Encoded {
157        let mut out = [0_u8; 8];
158        out[..4].copy_from_slice(&self.days.encode());
159        out[4..].copy_from_slice(&self.milliseconds.encode());
160        out
161    }
162
163    fn decode(encoded: Self::Encoded) -> Self {
164        Self {
165            days: i32::decode(encoded[..4].try_into().unwrap()),
166            milliseconds: i32::decode(encoded[4..].try_into().unwrap()),
167        }
168    }
169}
170
171impl FixedLengthEncoding for IntervalMonthDayNano {
172    type Encoded = [u8; 16];
173
174    fn encode(self) -> Self::Encoded {
175        let mut out = [0_u8; 16];
176        out[..4].copy_from_slice(&self.months.encode());
177        out[4..8].copy_from_slice(&self.days.encode());
178        out[8..].copy_from_slice(&self.nanoseconds.encode());
179        out
180    }
181
182    fn decode(encoded: Self::Encoded) -> Self {
183        Self {
184            months: i32::decode(encoded[..4].try_into().unwrap()),
185            days: i32::decode(encoded[4..8].try_into().unwrap()),
186            nanoseconds: i64::decode(encoded[8..].try_into().unwrap()),
187        }
188    }
189}
190
191/// Returns the total encoded length (including null byte) for a value of type `T::Native`
192pub const fn encoded_len<T>(_col: &PrimitiveArray<T>) -> usize
193where
194    T: ArrowPrimitiveType,
195    T::Native: FixedLengthEncoding,
196{
197    T::Native::ENCODED_LEN
198}
199
200/// Fixed width types are encoded as
201///
202/// - 1 byte `0` if null or `1` if valid
203/// - bytes of [`FixedLengthEncoding`]
204pub fn encode<T: FixedLengthEncoding>(
205    data: &mut [u8],
206    offsets: &mut [usize],
207    values: &[T],
208    nulls: &NullBuffer,
209    opts: SortOptions,
210) {
211    let null_sentinel = null_sentinel(opts);
212    for (value_idx, is_valid) in nulls.iter().enumerate() {
213        let offset = &mut offsets[value_idx + 1];
214        let end_offset = *offset + T::ENCODED_LEN;
215        if is_valid {
216            let to_write = &mut data[*offset..end_offset];
217            to_write[0] = 1;
218            let mut encoded = values[value_idx].encode();
219            if opts.descending {
220                // Flip bits to reverse order
221                encoded.as_mut().iter_mut().for_each(|v| *v = !*v)
222            }
223            to_write[1..].copy_from_slice(encoded.as_ref())
224        } else {
225            data[*offset] = null_sentinel;
226        }
227        *offset = end_offset;
228    }
229}
230
231/// Encoding for non-nullable primitive arrays.
232/// Iterates directly over the `values`, and skips NULLs-checking.
233pub fn encode_not_null<T: FixedLengthEncoding>(
234    data: &mut [u8],
235    offsets: &mut [usize],
236    values: &[T],
237    opts: SortOptions,
238) {
239    for (value_idx, val) in values.iter().enumerate() {
240        let offset = &mut offsets[value_idx + 1];
241        let end_offset = *offset + T::ENCODED_LEN;
242
243        let to_write = &mut data[*offset..end_offset];
244        to_write[0] = 1;
245        let mut encoded = val.encode();
246        if opts.descending {
247            // Flip bits to reverse order
248            encoded.as_mut().iter_mut().for_each(|v| *v = !*v)
249        }
250        to_write[1..].copy_from_slice(encoded.as_ref());
251
252        *offset = end_offset;
253    }
254}
255
256/// Boolean values are encoded as
257///
258/// - 1 byte `0` if null or `1` if valid
259/// - bytes of [`FixedLengthEncoding`]
260pub fn encode_boolean(
261    data: &mut [u8],
262    offsets: &mut [usize],
263    values: &BooleanBuffer,
264    nulls: &NullBuffer,
265    opts: SortOptions,
266) {
267    let null_sentinel = null_sentinel(opts);
268    for (idx, is_valid) in nulls.iter().enumerate() {
269        let offset = &mut offsets[idx + 1];
270        let end_offset = *offset + bool::ENCODED_LEN;
271        if is_valid {
272            let to_write = &mut data[*offset..end_offset];
273            to_write[0] = 1;
274            let mut encoded = values.value(idx).encode();
275            if opts.descending {
276                // Flip bits to reverse order
277                encoded.as_mut().iter_mut().for_each(|v| *v = !*v)
278            }
279            to_write[1..].copy_from_slice(encoded.as_ref())
280        } else {
281            data[*offset] = null_sentinel;
282        }
283        *offset = end_offset;
284    }
285}
286
287/// Encoding for non-nullable boolean arrays.
288/// Iterates directly over `values`, and skips NULLs-checking.
289pub fn encode_boolean_not_null(
290    data: &mut [u8],
291    offsets: &mut [usize],
292    values: &BooleanBuffer,
293    opts: SortOptions,
294) {
295    for (value_idx, val) in values.iter().enumerate() {
296        let offset = &mut offsets[value_idx + 1];
297        let end_offset = *offset + bool::ENCODED_LEN;
298
299        let to_write = &mut data[*offset..end_offset];
300        to_write[0] = 1;
301        let mut encoded = val.encode();
302        if opts.descending {
303            // Flip bits to reverse order
304            encoded.as_mut().iter_mut().for_each(|v| *v = !*v)
305        }
306        to_write[1..].copy_from_slice(encoded.as_ref());
307
308        *offset = end_offset;
309    }
310}
311
312pub fn encode_fixed_size_binary(
313    data: &mut [u8],
314    offsets: &mut [usize],
315    array: &FixedSizeBinaryArray,
316    opts: SortOptions,
317) {
318    let len = array.value_length() as usize;
319    let null_sentinel = null_sentinel(opts);
320    for (offset, maybe_val) in offsets.iter_mut().skip(1).zip(array.iter()) {
321        let end_offset = *offset + len + 1;
322        if let Some(val) = maybe_val {
323            let to_write = &mut data[*offset..end_offset];
324            to_write[0] = 1;
325            to_write[1..].copy_from_slice(&val[..len]);
326            if opts.descending {
327                // Flip bits to reverse order
328                to_write[1..1 + len].iter_mut().for_each(|v| *v = !*v)
329            }
330        } else {
331            data[*offset] = null_sentinel;
332        }
333        *offset = end_offset;
334    }
335}
336
337/// Splits `len` bytes from `src`
338#[inline]
339fn split_off<'a>(src: &mut &'a [u8], len: usize) -> &'a [u8] {
340    let v = &src[..len];
341    *src = &src[len..];
342    v
343}
344
345/// Decodes a `BooleanArray` from rows
346pub(crate) fn try_decode_bool(
347    rows: &mut [&[u8]],
348    options: SortOptions,
349) -> Result<BooleanArray, ArrowError> {
350    let true_val = match options.descending {
351        true => !1,
352        false => 1,
353    };
354
355    let len = rows.len();
356
357    let capacity = bit_util::ceil(len, 64) * 8;
358    let mut nulls = MutableBuffer::try_with_capacity(capacity)
359        .map_err(|e| ArrowError::MemoryError(e.to_string()))?;
360    let mut values = MutableBuffer::try_with_capacity(capacity)
361        .map_err(|e| ArrowError::MemoryError(e.to_string()))?;
362
363    let chunks = len / 64;
364    let remainder = len % 64;
365    for chunk in 0..chunks {
366        let mut null_packed = 0;
367        let mut values_packed = 0;
368
369        for bit_idx in 0..64 {
370            let i = split_off(&mut rows[bit_idx + chunk * 64], 2);
371            let (null, value) = (i[0] == 1, i[1] == true_val);
372            null_packed |= (null as u64) << bit_idx;
373            values_packed |= (value as u64) << bit_idx;
374        }
375
376        nulls.push(null_packed);
377        values.push(values_packed);
378    }
379
380    if remainder != 0 {
381        let mut null_packed = 0;
382        let mut values_packed = 0;
383
384        for bit_idx in 0..remainder {
385            let i = split_off(&mut rows[bit_idx + chunks * 64], 2);
386            let (null, value) = (i[0] == 1, i[1] == true_val);
387            null_packed |= (null as u64) << bit_idx;
388            values_packed |= (value as u64) << bit_idx;
389        }
390
391        nulls.push(null_packed);
392        values.push(values_packed);
393    }
394
395    let nulls = NullBuffer::new(BooleanBuffer::new(nulls.into(), 0, len));
396    let nulls = (nulls.null_count() > 0).then_some(nulls);
397
398    Ok(BooleanArray::new(
399        BooleanBuffer::new(values.into(), 0, len),
400        nulls,
401    ))
402}
403
404/// Decodes a single byte from each row, interpreting `0x01` as a valid value
405/// and all other values as a null. Optionally returns `None` if there are no
406/// null values.
407pub(crate) fn try_decode_nulls(rows: &[&[u8]]) -> Result<Option<NullBuffer>, ArrowError> {
408    let nulls = MutableBuffer::try_collect_bool(rows.len(), |idx| rows[idx][0] == 1)
409        .map_err(|e| ArrowError::MemoryError(e.to_string()))?;
410    let nulls = BooleanBuffer::new(nulls.into(), 0, rows.len());
411    let nulls = NullBuffer::new(nulls);
412    Ok((nulls.null_count() > 0).then_some(nulls))
413}
414
415/// Decodes a `PrimitiveArray` from rows
416pub(crate) fn try_decode_primitive<T: ArrowPrimitiveType>(
417    rows: &mut [&[u8]],
418    data_type: DataType,
419    options: SortOptions,
420) -> Result<PrimitiveArray<T>, ArrowError>
421where
422    T::Native: FixedLengthEncoding,
423{
424    assert!(PrimitiveArray::<T>::is_compatible(&data_type));
425
426    let nulls = try_decode_nulls(rows)?;
427    let values = rows
428        .iter_mut()
429        .map(|row| {
430            let i = split_off(row, T::Native::ENCODED_LEN);
431            let value = <T::Native as FixedLengthEncoding>::Encoded::from_slice(
432                &i[1..],
433                options.descending,
434            );
435            T::Native::decode(value)
436        })
437        .collect::<Vec<_>>();
438
439    Ok(PrimitiveArray::new(values.into(), nulls).with_data_type(data_type))
440}
441
442/// Decodes a `FixedLengthBinary` from rows
443///
444/// # Panics:
445/// Panics if `size` is negative
446pub(crate) fn try_decode_fixed_size_binary(
447    rows: &mut [&[u8]],
448    size: i32,
449    options: SortOptions,
450) -> Result<FixedSizeBinaryArray, ArrowError> {
451    if size < 0 {
452        panic!("cannot decode FixedSizeBinary({size})");
453    }
454    let num_rows = rows.len();
455    let capacity = (size as usize)
456        .checked_mul(num_rows)
457        .ok_or_else(|| ArrowError::MemoryError("decoded values size overflow".into()))?;
458    let mut values = MutableBuffer::try_with_capacity(capacity)
459        .map_err(|e| ArrowError::MemoryError(e.to_string()))?;
460    let nulls = try_decode_nulls(rows)?;
461
462    let encoded_len = size as usize + 1;
463
464    for row in rows {
465        let i = split_off(row, encoded_len);
466        values.extend_from_slice(&i[1..]);
467    }
468
469    if options.descending {
470        for v in values.as_slice_mut() {
471            *v = !*v;
472        }
473    }
474
475    // Need to set the length since when size is 0 and no nulls the length could not be determined by FixedSizeBinaryArray
476    FixedSizeBinaryArray::try_new_with_len(size, values.into(), nulls, num_rows)
477}