Skip to main content

vortex_array/arrays/primitive/array/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Display;
5use std::fmt::Formatter;
6
7use smallvec::smallvec;
8use vortex_buffer::Alignment;
9use vortex_buffer::Buffer;
10use vortex_buffer::BufferMut;
11use vortex_buffer::ByteBuffer;
12use vortex_buffer::ByteBufferMut;
13use vortex_error::VortexExpect;
14use vortex_error::VortexResult;
15use vortex_error::vortex_err;
16use vortex_error::vortex_panic;
17
18use crate::ArraySlots;
19use crate::ExecutionCtx;
20use crate::array::Array;
21use crate::array::ArrayParts;
22use crate::array::TypedArrayRef;
23use crate::arrays::BoolArray;
24use crate::arrays::Primitive;
25use crate::arrays::PrimitiveArray;
26use crate::dtype::DType;
27use crate::dtype::NativePType;
28use crate::dtype::Nullability;
29use crate::dtype::PType;
30use crate::match_each_native_ptype;
31use crate::validity::Validity;
32
33mod cast;
34mod conversion;
35mod patch;
36mod top_value;
37
38pub use patch::chunk_range;
39pub use patch::patch_chunk;
40
41use crate::ArrayRef;
42use crate::aggregate_fn::NumericalAggregateOpts;
43use crate::aggregate_fn::fns::min_max::min_max;
44use crate::array::child_to_validity;
45use crate::array::validity_to_child;
46use crate::array_slots;
47use crate::arrays::bool::BoolArrayExt;
48use crate::buffer::BufferHandle;
49use crate::builtins::ArrayBuiltins;
50
51#[array_slots(Primitive)]
52pub struct PrimitiveSlots {
53    /// The validity bitmap indicating which elements are non-null.
54    #[slot(0)]
55    pub validity_child: Option<ArrayRef>,
56}
57
58/// A primitive array that stores [native types][crate::dtype::NativePType] in a contiguous buffer
59/// of memory, along with an optional validity child.
60///
61/// This mirrors the Apache Arrow Primitive layout and can be converted into and out of one
62/// without allocations or copies.
63///
64/// The underlying buffer must be natively aligned to the primitive type they are representing.
65///
66/// Values are stored in their native representation with proper alignment.
67/// Null values still occupy space in the buffer but are marked invalid in the validity mask.
68///
69/// # Examples
70///
71/// ```
72/// # fn main() -> vortex_error::VortexResult<()> {
73/// use vortex_array::arrays::PrimitiveArray;
74/// use vortex_array::{VortexSessionExecute};
75/// use vortex_session::VortexSession;
76///
77/// // Create from iterator using FromIterator impl
78/// let array: PrimitiveArray = [1i32, 2, 3, 4, 5].into_iter().collect();
79///
80/// // Slice the array
81/// let sliced = array.slice(1..3)?;
82///
83/// // Access individual values
84/// let mut ctx = VortexSession::empty().create_execution_ctx();
85/// let value = sliced.execute_scalar(0, &mut ctx).unwrap();
86/// assert_eq!(value, 2i32.into());
87///
88/// # Ok(())
89/// # }
90/// ```
91#[derive(Clone, Debug)]
92pub struct PrimitiveData {
93    pub(super) ptype: PType,
94    pub(super) buffer: BufferHandle,
95}
96
97impl Display for PrimitiveData {
98    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
99        write!(f, "ptype: {}", self.ptype)
100    }
101}
102
103pub struct PrimitiveDataParts {
104    pub ptype: PType,
105    pub buffer: BufferHandle,
106    pub validity: Validity,
107}
108
109pub trait PrimitiveArrayExt: TypedArrayRef<Primitive> {
110    fn ptype(&self) -> PType {
111        match self.dtype() {
112            DType::Primitive(ptype, _) => *ptype,
113            _ => unreachable!("PrimitiveArrayExt requires a primitive dtype"),
114        }
115    }
116
117    fn nullability(&self) -> Nullability {
118        match self.dtype() {
119            DType::Primitive(_, nullability) => *nullability,
120            _ => unreachable!("PrimitiveArrayExt requires a primitive dtype"),
121        }
122    }
123
124    fn validity(&self) -> Validity {
125        child_to_validity(self.validity_child(), self.nullability())
126    }
127
128    fn buffer_handle(&self) -> &BufferHandle {
129        &self.buffer
130    }
131
132    fn reinterpret_cast(&self, ptype: PType) -> PrimitiveArray {
133        if self.ptype() == ptype {
134            return self.to_owned();
135        }
136
137        assert_eq!(
138            self.ptype().byte_width(),
139            ptype.byte_width(),
140            "can't reinterpret cast between integers of two different widths"
141        );
142
143        PrimitiveArray::from_buffer_handle(
144            self.buffer_handle().clone(),
145            ptype,
146            PrimitiveArrayExt::validity(self),
147        )
148    }
149
150    /// Narrow the array to the smallest possible integer type that can represent all values.
151    fn narrow(&self, ctx: &mut ExecutionCtx) -> VortexResult<PrimitiveArray> {
152        if !self.ptype().is_int() {
153            return Ok(self.to_owned());
154        }
155
156        let Some(min_max) = min_max(self.as_ref(), ctx, NumericalAggregateOpts::default())? else {
157            return Ok(PrimitiveArray::new(
158                Buffer::<u8>::zeroed(self.len()),
159                PrimitiveArrayExt::validity(self),
160            ));
161        };
162
163        // If we can't cast to i64, then leave the array as its original type.
164        // It's too big to downcast anyway.
165        let Ok(min) = min_max
166            .min
167            .cast(&PType::I64.into())
168            .and_then(|s| i64::try_from(&s))
169        else {
170            return Ok(self.to_owned());
171        };
172        let Ok(max) = min_max
173            .max
174            .cast(&PType::I64.into())
175            .and_then(|s| i64::try_from(&s))
176        else {
177            return Ok(self.to_owned());
178        };
179
180        let nullability = self.dtype().nullability();
181
182        if min < 0 || max < 0 {
183            // Signed
184            if min >= i8::MIN as i64 && max <= i8::MAX as i64 {
185                let result = self
186                    .as_ref()
187                    .cast(DType::Primitive(PType::I8, nullability))?
188                    .execute::<PrimitiveArray>(ctx)?;
189                return Ok(result);
190            }
191
192            if min >= i16::MIN as i64 && max <= i16::MAX as i64 {
193                let result = self
194                    .as_ref()
195                    .cast(DType::Primitive(PType::I16, nullability))?
196                    .execute::<PrimitiveArray>(ctx)?;
197                return Ok(result);
198            }
199
200            if min >= i32::MIN as i64 && max <= i32::MAX as i64 {
201                let result = self
202                    .as_ref()
203                    .cast(DType::Primitive(PType::I32, nullability))?
204                    .execute::<PrimitiveArray>(ctx)?;
205                return Ok(result);
206            }
207        } else {
208            // Unsigned
209            if max <= u8::MAX as i64 {
210                let result = self
211                    .as_ref()
212                    .cast(DType::Primitive(PType::U8, nullability))?
213                    .execute::<PrimitiveArray>(ctx)?;
214                return Ok(result);
215            }
216
217            if max <= u16::MAX as i64 {
218                let result = self
219                    .as_ref()
220                    .cast(DType::Primitive(PType::U16, nullability))?
221                    .execute::<PrimitiveArray>(ctx)?;
222                return Ok(result);
223            }
224
225            if max <= u32::MAX as i64 {
226                let result = self
227                    .as_ref()
228                    .cast(DType::Primitive(PType::U32, nullability))?
229                    .execute::<PrimitiveArray>(ctx)?;
230                return Ok(result);
231            }
232        }
233
234        Ok(self.to_owned())
235    }
236}
237impl<T: TypedArrayRef<Primitive>> PrimitiveArrayExt for T {}
238
239// TODO(connor): There are a lot of places where we could be using `new_unchecked` in the codebase.
240impl PrimitiveData {
241    /// Build the slots vector for this array.
242    pub(super) fn make_slots(validity: &Validity, len: usize) -> ArraySlots {
243        smallvec![validity_to_child(validity, len)]
244    }
245
246    /// Create a new array from a buffer handle.
247    ///
248    /// # Safety
249    ///
250    /// Should ensure that the provided BufferHandle points at sufficiently large region of aligned
251    /// memory to hold the `ptype` values.
252    pub unsafe fn new_unchecked_from_handle(
253        handle: BufferHandle,
254        ptype: PType,
255        _validity: Validity,
256    ) -> Self {
257        Self {
258            ptype,
259            buffer: handle,
260        }
261    }
262
263    /// Creates a new `PrimitiveArray`.
264    ///
265    /// # Panics
266    ///
267    /// Panics if the provided components do not satisfy the invariants documented
268    /// in `PrimitiveArray::new_unchecked`.
269    pub fn new<T: NativePType>(buffer: impl Into<Buffer<T>>, validity: Validity) -> Self {
270        let buffer = buffer.into();
271        Self::try_new(buffer, validity).vortex_expect("PrimitiveArray construction failed")
272    }
273
274    /// Constructs a new `PrimitiveArray`.
275    ///
276    /// See `PrimitiveArray::new_unchecked` for more information.
277    ///
278    /// # Errors
279    ///
280    /// Returns an error if the provided components do not satisfy the invariants documented in
281    /// `PrimitiveArray::new_unchecked`.
282    #[inline]
283    pub fn try_new<T: NativePType>(buffer: Buffer<T>, validity: Validity) -> VortexResult<Self> {
284        Self::validate(&buffer, &validity)?;
285
286        // SAFETY: validate ensures all invariants are met.
287        Ok(unsafe { Self::new_unchecked(buffer, validity) })
288    }
289
290    /// Creates a new `PrimitiveArray` without validation from these components:
291    ///
292    /// * `buffer` is a typed buffer containing the primitive values.
293    /// * `validity` holds the null values.
294    ///
295    /// # Safety
296    ///
297    /// The caller must ensure all of the following invariants are satisfied:
298    ///
299    /// ## Validity Requirements
300    ///
301    /// - If `validity` is [`Validity::Array`], its length must exactly equal `buffer.len()`.
302    #[inline]
303    pub unsafe fn new_unchecked<T: NativePType>(buffer: Buffer<T>, _validity: Validity) -> Self {
304        #[cfg(debug_assertions)]
305        Self::validate(&buffer, &_validity)
306            .vortex_expect("[Debug Assertion]: Invalid `PrimitiveArray` parameters");
307
308        Self {
309            ptype: T::PTYPE,
310            buffer: BufferHandle::new_host(buffer.into_byte_buffer()),
311        }
312    }
313
314    /// Validates the components that would be used to create a `PrimitiveArray`.
315    ///
316    /// This function checks all the invariants required by `PrimitiveArray::new_unchecked`.
317    #[inline]
318    pub fn validate<T: NativePType>(buffer: &Buffer<T>, validity: &Validity) -> VortexResult<()> {
319        if let Some(len) = validity.maybe_len()
320            && buffer.len() != len
321        {
322            return Err(vortex_err!(
323                "Buffer and validity length mismatch: buffer={}, validity={}",
324                buffer.len(),
325                len
326            ));
327        }
328        Ok(())
329    }
330
331    pub fn empty<T: NativePType>(nullability: Nullability) -> Self {
332        Self::new(Buffer::<T>::empty(), nullability.into())
333    }
334}
335
336impl Array<Primitive> {
337    pub fn empty<T: NativePType>(nullability: Nullability) -> Self {
338        let dtype = DType::Primitive(T::PTYPE, nullability);
339        let len = 0;
340        let data = PrimitiveData::empty::<T>(nullability);
341        let slots = PrimitiveData::make_slots(&Validity::from(nullability), len);
342        unsafe {
343            Self::from_primitive_parts_unchecked(ArrayParts::new(
344                Primitive, dtype, len, data, slots,
345            ))
346        }
347    }
348
349    /// Creates a new `PrimitiveArray`.
350    ///
351    /// # Panics
352    ///
353    /// Panics if the provided components do not satisfy the invariants.
354    pub fn new<T: NativePType>(buffer: impl Into<Buffer<T>>, validity: Validity) -> Self {
355        let buffer = buffer.into();
356        let dtype = DType::Primitive(T::PTYPE, validity.nullability());
357        let len = buffer.len();
358        let slots = PrimitiveData::make_slots(&validity, len);
359        let data = PrimitiveData::new(buffer, validity);
360        unsafe {
361            Self::from_primitive_parts_unchecked(ArrayParts::new(
362                Primitive, dtype, len, data, slots,
363            ))
364        }
365    }
366
367    /// Constructs a new `PrimitiveArray`.
368    pub fn try_new<T: NativePType>(buffer: Buffer<T>, validity: Validity) -> VortexResult<Self> {
369        let dtype = DType::Primitive(T::PTYPE, validity.nullability());
370        let len = buffer.len();
371        let slots = PrimitiveData::make_slots(&validity, len);
372        let data = PrimitiveData::try_new(buffer, validity)?;
373        Ok(unsafe {
374            Self::from_primitive_parts_unchecked(ArrayParts::new(
375                Primitive, dtype, len, data, slots,
376            ))
377        })
378    }
379
380    /// Creates a new `PrimitiveArray` without validation.
381    ///
382    /// # Safety
383    ///
384    /// See [`PrimitiveData::new_unchecked`].
385    pub unsafe fn new_unchecked<T: NativePType>(buffer: Buffer<T>, validity: Validity) -> Self {
386        let dtype = DType::Primitive(T::PTYPE, validity.nullability());
387        let len = buffer.len();
388        let slots = PrimitiveData::make_slots(&validity, len);
389        let data = unsafe { PrimitiveData::new_unchecked(buffer, validity) };
390        unsafe {
391            Self::from_primitive_parts_unchecked(ArrayParts::new(
392                Primitive, dtype, len, data, slots,
393            ))
394        }
395    }
396
397    /// Creates the array from parts without validation.
398    ///
399    /// The generic constructors call this function. It is not generic, so crates that call those
400    /// constructors do not each compile the `Primitive` array vtable.
401    ///
402    /// # Safety
403    ///
404    /// The parts must be logically consistent.
405    unsafe fn from_primitive_parts_unchecked(parts: ArrayParts<Primitive>) -> Self {
406        unsafe { Array::from_parts_unchecked(parts) }
407    }
408
409    /// Create a new array from a buffer handle.
410    ///
411    /// # Safety
412    ///
413    /// See [`PrimitiveData::new_unchecked_from_handle`].
414    pub unsafe fn new_unchecked_from_handle(
415        handle: BufferHandle,
416        ptype: PType,
417        validity: Validity,
418    ) -> Self {
419        let dtype = DType::Primitive(ptype, validity.nullability());
420        let len = handle.len() / ptype.byte_width();
421        let slots = PrimitiveData::make_slots(&validity, len);
422        let data = unsafe { PrimitiveData::new_unchecked_from_handle(handle, ptype, validity) };
423        unsafe { Array::from_parts_unchecked(ArrayParts::new(Primitive, dtype, len, data, slots)) }
424    }
425
426    /// Creates a new `PrimitiveArray` from a [`BufferHandle`].
427    pub fn from_buffer_handle(handle: BufferHandle, ptype: PType, validity: Validity) -> Self {
428        let dtype = DType::Primitive(ptype, validity.nullability());
429        let len = handle.len() / ptype.byte_width();
430        let slots = PrimitiveData::make_slots(&validity, len);
431        let data = PrimitiveData::from_buffer_handle(handle, ptype, validity);
432        Array::try_from_parts(ArrayParts::new(Primitive, dtype, len, data, slots))
433            .vortex_expect("PrimitiveData is always valid")
434    }
435
436    /// Creates a new `PrimitiveArray` from a [`ByteBuffer`].
437    pub fn from_byte_buffer(buffer: ByteBuffer, ptype: PType, validity: Validity) -> Self {
438        let dtype = DType::Primitive(ptype, validity.nullability());
439        let len = buffer.len() / ptype.byte_width();
440        let slots = PrimitiveData::make_slots(&validity, len);
441        let data = PrimitiveData::from_byte_buffer(buffer, ptype, validity);
442        unsafe { Array::from_parts_unchecked(ArrayParts::new(Primitive, dtype, len, data, slots)) }
443    }
444
445    /// Create a PrimitiveArray from a byte buffer containing only the valid elements.
446    pub fn from_values_byte_buffer(
447        valid_elems_buffer: ByteBuffer,
448        ptype: PType,
449        validity: Validity,
450        n_rows: usize,
451        ctx: &mut ExecutionCtx,
452    ) -> Self {
453        let dtype = DType::Primitive(ptype, validity.nullability());
454        let len = n_rows;
455        let slots = PrimitiveData::make_slots(&validity, len);
456        let data = PrimitiveData::from_values_byte_buffer(
457            valid_elems_buffer,
458            ptype,
459            validity,
460            n_rows,
461            ctx,
462        );
463        unsafe { Array::from_parts_unchecked(ArrayParts::new(Primitive, dtype, len, data, slots)) }
464    }
465
466    /// Validates the components that would be used to create a `PrimitiveArray`.
467    pub fn validate<T: NativePType>(buffer: &Buffer<T>, validity: &Validity) -> VortexResult<()> {
468        PrimitiveData::validate(buffer, validity)
469    }
470
471    pub fn into_data_parts(self) -> PrimitiveDataParts {
472        let validity = PrimitiveArrayExt::validity(&self);
473        let ptype = PrimitiveArrayExt::ptype(&self);
474        let data = self.into_data();
475        PrimitiveDataParts {
476            ptype,
477            buffer: data.buffer,
478            validity,
479        }
480    }
481}
482
483impl PrimitiveData {
484    pub fn len(&self) -> usize {
485        self.buffer.len() / self.ptype.byte_width()
486    }
487
488    /// Returns `true` if the array is empty.
489    pub fn is_empty(&self) -> bool {
490        self.buffer.is_empty()
491    }
492
493    pub fn ptype(&self) -> PType {
494        self.ptype
495    }
496
497    /// Get access to the buffer handle backing the array.
498    pub fn buffer_handle(&self) -> &BufferHandle {
499        &self.buffer
500    }
501
502    pub fn from_buffer_handle(handle: BufferHandle, ptype: PType, _validity: Validity) -> Self {
503        Self {
504            ptype,
505            buffer: handle,
506        }
507    }
508
509    pub fn from_byte_buffer(buffer: ByteBuffer, ptype: PType, validity: Validity) -> Self {
510        match_each_native_ptype!(ptype, |T| {
511            Self::new::<T>(Buffer::from_byte_buffer(buffer), validity)
512        })
513    }
514
515    /// Create a PrimitiveArray from a byte buffer containing only the valid elements.
516    pub fn from_values_byte_buffer(
517        valid_elems_buffer: ByteBuffer,
518        ptype: PType,
519        validity: Validity,
520        n_rows: usize,
521        ctx: &mut ExecutionCtx,
522    ) -> Self {
523        let byte_width = ptype.byte_width();
524        let alignment = Alignment::new(byte_width);
525        let buffer = match &validity {
526            Validity::AllValid | Validity::NonNullable => valid_elems_buffer.aligned(alignment),
527            Validity::AllInvalid => ByteBuffer::zeroed_aligned(n_rows * byte_width, alignment),
528            Validity::Array(is_valid) => {
529                let bool_array = is_valid
530                    .clone()
531                    .execute::<BoolArray>(ctx)
532                    .vortex_expect("must be a bool array");
533                let bool_buffer = bool_array.bit_buffer_view();
534                let mut bytes = ByteBufferMut::zeroed_aligned(n_rows * byte_width, alignment);
535                for (i, valid_i) in bool_buffer.set_indices().enumerate() {
536                    bytes[valid_i * byte_width..(valid_i + 1) * byte_width]
537                        .copy_from_slice(&valid_elems_buffer[i * byte_width..(i + 1) * byte_width])
538                }
539                bytes.freeze()
540            }
541        };
542
543        Self::from_byte_buffer(buffer, ptype, validity)
544    }
545
546    /// Get a buffer in host memory holding all the values.
547    ///
548    /// NOTE: some values may be nonsense if the validity buffer indicates that the value is null.
549    pub fn to_buffer<T: NativePType>(&self) -> Buffer<T> {
550        if T::PTYPE != self.ptype() {
551            vortex_panic!(
552                "Attempted to get buffer of type {} from array of type {}",
553                T::PTYPE,
554                self.ptype()
555            )
556        }
557        Buffer::from_byte_buffer(self.buffer_handle().to_host_sync())
558    }
559
560    /// Consume the array and get a host Buffer containing the data values.
561    pub fn into_buffer<T: NativePType>(self) -> Buffer<T> {
562        if T::PTYPE != self.ptype() {
563            vortex_panic!(
564                "Attempted to get buffer of type {} from array of type {}",
565                T::PTYPE,
566                self.ptype()
567            )
568        }
569        Buffer::from_byte_buffer(self.buffer.into_host_sync())
570    }
571
572    /// Extract a mutable buffer from the PrimitiveData. Attempts to do this with zero-copy
573    /// if the buffer is uniquely owned, otherwise will make a copy.
574    pub fn into_buffer_mut<T: NativePType>(self) -> BufferMut<T> {
575        self.try_into_buffer_mut()
576            .unwrap_or_else(|buffer| BufferMut::<T>::copy_from(&buffer))
577    }
578
579    /// Try to extract a mutable buffer from the PrimitiveData with zero copy.
580    ///
581    /// # Panic
582    /// If the buffer is not of type T this will panic
583    pub fn try_into_buffer_mut<T: NativePType>(self) -> Result<BufferMut<T>, Buffer<T>> {
584        if T::PTYPE != self.ptype() {
585            vortex_panic!(
586                "Attempted to get buffer_mut of type {} from array of type {}",
587                T::PTYPE,
588                self.ptype()
589            )
590        }
591        let buffer = Buffer::<T>::from_byte_buffer(self.buffer.into_host_sync());
592        buffer.try_into_mut()
593    }
594}