1use 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 #[slot(0)]
55 pub validity_child: Option<ArrayRef>,
56}
57
58#[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 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 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 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 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
239impl PrimitiveData {
241 pub(super) fn make_slots(validity: &Validity, len: usize) -> ArraySlots {
243 smallvec![validity_to_child(validity, len)]
244 }
245
246 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 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 #[inline]
283 pub fn try_new<T: NativePType>(buffer: Buffer<T>, validity: Validity) -> VortexResult<Self> {
284 Self::validate(&buffer, &validity)?;
285
286 Ok(unsafe { Self::new_unchecked(buffer, validity) })
288 }
289
290 #[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 #[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 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 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 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 unsafe fn from_primitive_parts_unchecked(parts: ArrayParts<Primitive>) -> Self {
406 unsafe { Array::from_parts_unchecked(parts) }
407 }
408
409 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 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 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 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 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 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 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 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 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 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 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 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}