1use num_traits::AsPrimitive;
5use num_traits::CheckedMul;
6use num_traits::NumCast;
7use vortex_buffer::Buffer;
8use vortex_buffer::BufferMut;
9use vortex_compute::lane_kernels::IndexedSinkExt;
10use vortex_compute::lane_kernels::IndexedSourceExt;
11use vortex_compute::lane_kernels::ReinterpretSink;
12use vortex_error::VortexError;
13use vortex_error::VortexResult;
14use vortex_error::vortex_bail;
15use vortex_error::vortex_err;
16use vortex_mask::Mask;
17
18use crate::ArrayRef;
19use crate::ExecutionCtx;
20use crate::IntoArray;
21use crate::aggregate_fn;
22use crate::array::ArrayView;
23use crate::arrays::DecimalArray;
24use crate::arrays::Primitive;
25use crate::arrays::PrimitiveArray;
26use crate::arrays::primitive::PrimitiveArrayExt;
27use crate::dtype::BigCast;
28use crate::dtype::DType;
29use crate::dtype::DecimalDType;
30use crate::dtype::DecimalType;
31use crate::dtype::IntegerPType;
32use crate::dtype::NativeDecimalType;
33use crate::dtype::NativePType;
34use crate::dtype::Nullability;
35use crate::dtype::PType;
36use crate::dtype::ToI256;
37use crate::dtype::i256;
38use crate::expr::stats::Stat;
39use crate::expr::stats::StatsProvider;
40use crate::match_each_decimal_value_type;
41use crate::match_each_integer_ptype;
42use crate::match_each_native_ptype;
43use crate::match_each_signed_integer_ptype;
44use crate::scalar::DecimalValue;
45use crate::scalar_fn::fns::cast::CastKernel;
46use crate::scalar_fn::fns::cast::CastReduce;
47use crate::validity::Validity;
48
49impl CastReduce for Primitive {
50 fn cast(array: ArrayView<'_, Primitive>, dtype: &DType) -> VortexResult<Option<ArrayRef>> {
51 let DType::Primitive(new_ptype, new_nullability) = dtype else {
54 return Ok(None);
55 };
56 if *new_ptype != array.ptype() {
57 return Ok(None);
58 }
59
60 let Some(new_validity) = array
61 .validity()?
62 .trivially_cast_nullability(*new_nullability, array.len())?
63 else {
64 return Ok(None);
65 };
66
67 Ok(Some(unsafe {
69 PrimitiveArray::new_unchecked_from_handle(
70 array.buffer_handle().clone(),
71 array.ptype(),
72 new_validity,
73 )
74 .into_array()
75 }))
76 }
77}
78
79impl CastKernel for Primitive {
80 fn cast(
81 array: ArrayView<'_, Primitive>,
82 dtype: &DType,
83 ctx: &mut ExecutionCtx,
84 ) -> VortexResult<Option<ArrayRef>> {
85 if let DType::Decimal(decimal_dtype, nullability) = dtype {
86 return cast_to_decimal(array, *decimal_dtype, *nullability, ctx).map(Some);
87 }
88 let DType::Primitive(new_ptype, new_nullability) = dtype else {
89 return Ok(None);
90 };
91 let (new_ptype, new_nullability) = (*new_ptype, *new_nullability);
92 let src_ptype = array.ptype();
93
94 let new_validity = array
95 .validity()?
96 .cast_nullability(new_nullability, array.len(), ctx)?;
97
98 let same_rep = src_ptype == new_ptype
102 || (src_ptype.is_int()
103 && new_ptype.is_int()
104 && src_ptype.byte_width() == new_ptype.byte_width());
105 if same_rep {
106 if !values_fit_in(array, new_ptype, ctx, true) {
107 vortex_bail!(
108 Compute: "Cannot cast {} to {} — values exceed target range",
109 src_ptype, new_ptype,
110 );
111 }
112 return Ok(Some(reinterpret(array, new_ptype, new_validity)));
113 }
114
115 Ok(Some(match_each_native_ptype!(new_ptype, |T| {
118 match_each_native_ptype!(src_ptype, |F| {
119 cast_values::<F, T>(array, new_validity, ctx)?
120 })
121 })))
122 }
123}
124
125fn cast_to_decimal(
126 array: ArrayView<'_, Primitive>,
127 decimal_dtype: DecimalDType,
128 nullability: Nullability,
129 ctx: &mut ExecutionCtx,
130) -> VortexResult<ArrayRef> {
131 if !array.ptype().is_int() {
132 vortex_bail!(
133 Compute: "Cannot cast floating primitive {} to decimal {}",
134 array.ptype(), decimal_dtype
135 );
136 }
137
138 let source_validity = array.validity()?;
139 let validity = source_validity
140 .clone()
141 .cast_nullability(nullability, array.len(), ctx)?;
142 let values_type = DecimalType::smallest_decimal_value_type(&decimal_dtype);
143
144 if decimal_dtype.scale() == 0
145 && signed_primitive_decimal_type(array.ptype()) == Some(values_type)
146 {
147 return match_each_signed_integer_ptype!(array.ptype(), |S| {
148 cast_unscaled_same_width_signed_integer_to_decimal::<S>(
149 array,
150 decimal_dtype,
151 validity,
152 &source_validity,
153 ctx,
154 )
155 });
156 }
157
158 let valid_values = source_validity.execute_mask(array.len(), ctx)?;
159 match_each_integer_ptype!(array.ptype(), |S| {
160 match_each_decimal_value_type!(values_type, |T| {
161 cast_integer_values_to_decimal::<S, T>(array, decimal_dtype, validity, &valid_values)
162 })
163 })
164}
165
166fn cast_unscaled_same_width_signed_integer_to_decimal<S>(
167 array: ArrayView<'_, Primitive>,
168 decimal_dtype: DecimalDType,
169 validity: Validity,
170 source_validity: &Validity,
171 ctx: &mut ExecutionCtx,
172) -> VortexResult<ArrayRef>
173where
174 S: IntegerPType + NativeDecimalType + ToI256,
175{
176 let values = array.as_slice::<S>();
177 let target_dtype = DType::Decimal(decimal_dtype, Nullability::NonNullable);
178 if !cached_values_fit_in(array, &target_dtype).unwrap_or(false) {
179 let valid_values = source_validity.execute_mask(array.len(), ctx)?;
180 validate_unscaled_signed_integer_values_to_decimal(values, decimal_dtype, &valid_values)
181 .map_err(|idx| primitive_to_decimal_cast_error(values[idx], decimal_dtype))?;
182 }
183
184 Ok(unsafe {
187 DecimalArray::new_unchecked_handle(
188 array.buffer_handle().clone(),
189 S::DECIMAL_TYPE,
190 decimal_dtype,
191 validity,
192 )
193 .into_array()
194 })
195}
196
197fn validate_unscaled_signed_integer_values_to_decimal<S>(
198 values: &[S],
199 decimal_dtype: DecimalDType,
200 valid_values: &Mask,
201) -> Result<(), usize>
202where
203 S: NativeDecimalType,
204{
205 let fits = |value| decimal_value_fits_precision(value, decimal_dtype);
206 match valid_values {
207 Mask::AllTrue(_) => values
208 .iter()
209 .position(|&value| !fits(value))
210 .map_or(Ok(()), Err),
211 Mask::AllFalse(_) => Ok(()),
212 Mask::Values(mask) => {
213 let mut first_failure = None;
214 mask.bit_buffer().for_each_set_index(|idx| {
215 if first_failure.is_none() && !fits(values[idx]) {
216 first_failure = Some(idx);
217 }
218 });
219 first_failure.map_or(Ok(()), Err)
220 }
221 }
222}
223
224fn cast_integer_values_to_decimal<S, T>(
225 array: ArrayView<'_, Primitive>,
226 decimal_dtype: DecimalDType,
227 validity: Validity,
228 valid_values: &Mask,
229) -> VortexResult<ArrayRef>
230where
231 S: IntegerPType + ToI256,
232 T: NativeDecimalType + CheckedMul,
233{
234 let scale = decimal_dtype.scale();
235 let buffer = if scale == 0 {
236 cast_unscaled_integer_values_to_decimal::<S, T>(array, decimal_dtype, valid_values)?
237 } else if scale > 0 {
238 cast_scaled_up_integer_values_to_decimal::<S, T>(array, decimal_dtype, valid_values)?
239 } else {
240 cast_scaled_down_integer_values_to_decimal::<S, T>(array, decimal_dtype, valid_values)?
241 };
242
243 Ok(DecimalArray::new(buffer, decimal_dtype, validity).into_array())
244}
245
246fn cast_unscaled_integer_values_to_decimal<S, T>(
247 array: ArrayView<'_, Primitive>,
248 decimal_dtype: DecimalDType,
249 valid_values: &Mask,
250) -> VortexResult<Buffer<T>>
251where
252 S: IntegerPType + ToI256,
253 T: NativeDecimalType,
254{
255 let values = array.as_slice::<S>();
256 cast_integer_values_to_decimal_buffer(values, decimal_dtype, valid_values, |value| {
257 let value = <T as BigCast>::from(value)?;
258 decimal_value_fits_precision(value, decimal_dtype).then_some(value)
259 })
260}
261
262fn cast_scaled_up_integer_values_to_decimal<S, T>(
263 array: ArrayView<'_, Primitive>,
264 decimal_dtype: DecimalDType,
265 valid_values: &Mask,
266) -> VortexResult<Buffer<T>>
267where
268 S: IntegerPType + ToI256,
269 T: NativeDecimalType + CheckedMul,
270{
271 let values = array.as_slice::<S>();
272 let scale_factor = decimal_scale_factor::<T>(decimal_dtype.scale())?;
273 cast_integer_values_to_decimal_buffer(values, decimal_dtype, valid_values, |value| {
274 let value = <T as BigCast>::from(value)?;
275 let value = value.checked_mul(&scale_factor)?;
276 decimal_value_fits_precision(value, decimal_dtype).then_some(value)
277 })
278}
279
280fn cast_scaled_down_integer_values_to_decimal<S, T>(
281 array: ArrayView<'_, Primitive>,
282 decimal_dtype: DecimalDType,
283 valid_values: &Mask,
284) -> VortexResult<Buffer<T>>
285where
286 S: IntegerPType + ToI256,
287 T: NativeDecimalType,
288{
289 let values = array.as_slice::<S>();
290 if decimal_dtype.scale().unsigned_abs() >= primitive_max_decimal_digits(array.ptype()) {
291 return cast_integer_values_to_decimal_buffer(
293 values,
294 decimal_dtype,
295 valid_values,
296 |value| (value == S::default()).then_some(T::default()),
297 );
298 }
299
300 let carrier_type = primitive_decimal_carrier_type(array.ptype()).max(T::DECIMAL_TYPE);
303 match_each_decimal_value_type!(carrier_type, |W| {
304 let scale_factor = decimal_scale_factor::<W>(decimal_dtype.scale())?;
305 cast_integer_values_to_decimal_buffer(values, decimal_dtype, valid_values, |value| {
306 let value = <W as BigCast>::from(value)?;
307 let quotient = value / scale_factor;
308 let value = (quotient * scale_factor == value).then_some(quotient)?;
309 let value = <T as BigCast>::from(value)?;
310 decimal_value_fits_precision(value, decimal_dtype).then_some(value)
311 })
312 })
313}
314
315fn cast_integer_values_to_decimal_buffer<S, T>(
316 values: &[S],
317 decimal_dtype: DecimalDType,
318 valid_values: &Mask,
319 cast: impl Fn(S) -> Option<T>,
320) -> VortexResult<Buffer<T>>
321where
322 S: IntegerPType + ToI256,
323 T: NativeDecimalType,
324{
325 cast_primitive_to_decimal_buffer(values, valid_values, cast)
326 .map_err(|idx| primitive_to_decimal_cast_error(values[idx], decimal_dtype))
327}
328
329fn signed_primitive_decimal_type(ptype: PType) -> Option<DecimalType> {
331 match ptype {
332 PType::I8 => Some(DecimalType::I8),
333 PType::I16 => Some(DecimalType::I16),
334 PType::I32 => Some(DecimalType::I32),
335 PType::I64 => Some(DecimalType::I64),
336 PType::U8 | PType::U16 | PType::U32 | PType::U64 => None,
337 PType::F16 | PType::F32 | PType::F64 => {
338 unreachable!("floating primitives are rejected before selecting a decimal type")
339 }
340 }
341}
342
343fn primitive_decimal_carrier_type(ptype: PType) -> DecimalType {
345 match ptype {
346 PType::I8 => DecimalType::I8,
347 PType::U8 | PType::I16 => DecimalType::I16,
348 PType::U16 | PType::I32 => DecimalType::I32,
349 PType::U32 | PType::I64 => DecimalType::I64,
350 PType::U64 => DecimalType::I128,
351 PType::F16 | PType::F32 | PType::F64 => {
352 unreachable!("floating primitives are rejected before selecting a decimal carrier")
353 }
354 }
355}
356
357fn primitive_max_decimal_digits(ptype: PType) -> u8 {
359 match ptype {
360 PType::U8 | PType::I8 => 3,
361 PType::U16 | PType::I16 => 5,
362 PType::U32 | PType::I32 => 10,
363 PType::U64 => 20,
364 PType::I64 => 19,
365 PType::F16 | PType::F32 | PType::F64 => {
366 unreachable!("floating primitives are rejected before inspecting decimal digits")
367 }
368 }
369}
370
371fn decimal_scale_factor<T>(scale: i8) -> VortexResult<T>
372where
373 T: NativeDecimalType + CheckedMul,
374{
375 let exponent = if scale > 0 {
376 scale as u32
377 } else {
378 (-(scale as i16)) as u32
379 };
380 let ten = <T as BigCast>::from(10i8).ok_or_else(
381 || vortex_err!(Compute: "Cannot create decimal scale factor for scale {scale}"),
382 )?;
383 let mut factor = <T as BigCast>::from(1i8).ok_or_else(
384 || vortex_err!(Compute: "Cannot create decimal scale factor for scale {scale}"),
385 )?;
386 for _ in 0..exponent {
387 factor = factor.checked_mul(&ten).ok_or_else(
388 || vortex_err!(Compute: "Cannot create decimal scale factor for scale {scale}"),
389 )?;
390 }
391 Ok(factor)
392}
393
394fn decimal_value_fits_precision<T: NativeDecimalType>(
395 value: T,
396 decimal_dtype: DecimalDType,
397) -> bool {
398 let precision = decimal_dtype.precision() as usize;
399 value >= T::MIN_BY_PRECISION[precision] && value <= T::MAX_BY_PRECISION[precision]
400}
401
402fn cast_primitive_to_decimal_buffer<S, T>(
403 values: &[S],
404 valid_values: &Mask,
405 cast: impl Fn(S) -> Option<T>,
406) -> Result<Buffer<T>, usize>
407where
408 S: NativePType,
409 T: NativeDecimalType,
410{
411 if matches!(valid_values, Mask::AllFalse(_)) {
412 return Ok(BufferMut::<T>::zeroed(values.len()).freeze());
413 }
414
415 let mut buffer = BufferMut::<T>::with_capacity(values.len());
416 match valid_values {
417 Mask::AllTrue(_) => {
418 values.try_map_into(&mut buffer.spare_capacity_mut()[..values.len()], &cast)?;
419 }
420 Mask::Values(mask) => {
421 values.try_map_masked_into(
422 mask.bit_buffer(),
423 &mut buffer.spare_capacity_mut()[..values.len()],
424 &cast,
425 )?;
426 }
427 Mask::AllFalse(_) => unreachable!("all-null values are handled before allocating"),
428 }
429 unsafe { buffer.set_len(values.len()) };
431 Ok(buffer.freeze())
432}
433
434fn primitive_to_decimal_cast_error<S>(value: S, decimal_dtype: DecimalDType) -> VortexError
435where
436 S: IntegerPType + ToI256,
437{
438 let Some(value) = <i256 as BigCast>::from(value) else {
439 return vortex_err!(
440 Compute: "primitive value cannot be represented while casting to {}",
441 decimal_dtype
442 );
443 };
444
445 match DecimalValue::rescale_i256(value, 0, decimal_dtype.scale())
446 .and_then(|value| DecimalValue::try_from_i256(value, decimal_dtype))
447 {
448 Err(error) => error,
449 Ok(_) => {
450 debug_assert!(
451 false,
452 "primitive-to-decimal fast path rejected a value that the scalar cast accepts"
453 );
454 vortex_err!(
455 Compute: "primitive value cannot be represented while casting to {}",
456 decimal_dtype
457 )
458 }
459 }
460}
461
462fn cast_values<F, T>(
464 array: ArrayView<'_, Primitive>,
465 new_validity: Validity,
466 ctx: &mut ExecutionCtx,
467) -> VortexResult<ArrayRef>
468where
469 F: NativePType + AsPrimitive<T>,
470 T: NativePType,
471{
472 let overflow = || {
473 vortex_err!(
474 Compute: "Cannot cast {} to {} — value exceeds target range",
475 F::PTYPE, T::PTYPE,
476 )
477 };
478
479 fn casts_losslessly_to(from: PType, to: PType) -> bool {
481 if from == to {
482 return true;
483 }
484 if (from.is_unsigned_int() && to.is_unsigned_int())
485 || (from.is_signed_int() && to.is_signed_int())
486 || (from.is_float() && to.is_float())
487 {
488 return from.byte_width() <= to.byte_width();
489 }
490 if from.is_unsigned_int() && to.is_signed_int() {
491 return from.byte_width() < to.byte_width();
492 }
493 if from.is_int() && to.is_float() {
494 let minimum_float_width = match from.byte_width() {
495 1 => 2,
496 2 => 4,
497 4 => 8,
498 _ => return false,
499 };
500 return to.byte_width() >= minimum_float_width;
501 }
502 false
503 }
504
505 let target_dtype = DType::Primitive(T::PTYPE, Nullability::NonNullable);
507 let infallible = casts_losslessly_to(F::PTYPE, T::PTYPE)
508 || cached_values_fit_in(array, &target_dtype).unwrap_or(false);
509
510 let len = array.len();
511
512 let same_bit_width = F::PTYPE.byte_width() == T::PTYPE.byte_width();
514 let owned: Option<BufferMut<F>> = same_bit_width
515 .then(|| array.into_owned().try_into_buffer_mut::<F>().ok())
516 .flatten();
517 let values: &[F] = array.as_slice::<F>();
518
519 if infallible {
520 return match owned {
521 Some(mut buf) => {
522 ReinterpretSink::<F, T>::new(buf.as_mut_slice()).map_into_in_place(|v: F| v.as_());
523 let result: BufferMut<T> = unsafe { buf.transmute::<T>() };
525 Ok(PrimitiveArray::new(result.freeze(), new_validity).into_array())
526 }
527 None => {
528 let mut buffer = BufferMut::<T>::with_capacity(len);
529 values.map_into(&mut buffer.spare_capacity_mut()[..len], |v| v.as_());
530 unsafe { buffer.set_len(len) };
532 Ok(PrimitiveArray::new(buffer.freeze(), new_validity).into_array())
533 }
534 };
535 }
536
537 let mask = array.validity()?.execute_mask(len, ctx)?;
538
539 let buffer: Buffer<T> = match (&mask, owned) {
540 (Mask::AllTrue(_), Some(mut buf)) => {
541 ReinterpretSink::<F, T>::new(buf.as_mut_slice())
542 .try_map_in_place(|v: F| <T as NumCast>::from(v))
543 .map_err(|_| overflow())?;
544 let result: BufferMut<T> = unsafe { buf.transmute::<T>() };
546 result.freeze()
547 }
548 (Mask::AllTrue(_), None) => {
549 let mut buffer = BufferMut::<T>::with_capacity(len);
550 values
551 .try_map_into(&mut buffer.spare_capacity_mut()[..len], |v| {
552 <T as NumCast>::from(v)
553 })
554 .map_err(|_| overflow())?;
555 unsafe { buffer.set_len(len) };
557 buffer.freeze()
558 }
559 (Mask::AllFalse(_), _) => BufferMut::<T>::zeroed(len).freeze(),
560 (Mask::Values(m), Some(mut buf)) => {
561 ReinterpretSink::<F, T>::new(buf.as_mut_slice())
562 .try_map_masked_in_place(m.bit_buffer(), |v: F| <T as NumCast>::from(v))
563 .map_err(|_| overflow())?;
564 let result: BufferMut<T> = unsafe { buf.transmute::<T>() };
566 result.freeze()
567 }
568 (Mask::Values(m), None) => {
569 let mut buffer = BufferMut::<T>::with_capacity(len);
570 values
571 .try_map_masked_into(
572 m.bit_buffer(),
573 &mut buffer.spare_capacity_mut()[..len],
574 |v| <T as NumCast>::from(v),
575 )
576 .map_err(|_| overflow())?;
577 unsafe { buffer.set_len(len) };
579 buffer.freeze()
580 }
581 };
582
583 Ok(PrimitiveArray::new(buffer, new_validity).into_array())
584}
585
586fn reinterpret(
587 array: ArrayView<'_, Primitive>,
588 new_ptype: PType,
589 new_validity: Validity,
590) -> ArrayRef {
591 unsafe {
594 PrimitiveArray::new_unchecked_from_handle(
595 array.buffer_handle().clone(),
596 new_ptype,
597 new_validity,
598 )
599 }
600 .into_array()
601}
602
603fn values_fit_in(
609 array: ArrayView<'_, Primitive>,
610 target_ptype: PType,
611 ctx: &mut ExecutionCtx,
612 compute: bool,
613) -> bool {
614 let target_dtype = DType::Primitive(target_ptype, Nullability::NonNullable);
615 if let Some(fits) = cached_values_fit_in(array, &target_dtype) {
616 return fits;
617 }
618 if !compute {
619 return false;
620 }
621 aggregate_fn::fns::min_max::min_max(
622 array.array(),
623 ctx,
624 aggregate_fn::NumericalAggregateOpts::default(),
625 )
626 .ok()
627 .flatten()
628 .is_none_or(|mm| mm.min.cast(&target_dtype).is_ok() && mm.max.cast(&target_dtype).is_ok())
629}
630
631fn cached_values_fit_in(array: ArrayView<'_, Primitive>, target_dtype: &DType) -> Option<bool> {
634 let stats = array.array().statistics();
635 let min = stats.get(Stat::Min).as_exact()?;
636 let max = stats.get(Stat::Max).as_exact()?;
637 Some(min.cast(target_dtype).is_ok() && max.cast(target_dtype).is_ok())
638}
639
640#[cfg(test)]
641mod test {
642 use rstest::rstest;
643 use vortex_buffer::BitBuffer;
644 use vortex_buffer::buffer;
645 use vortex_error::VortexError;
646 use vortex_error::VortexResult;
647 use vortex_mask::Mask;
648
649 use crate::ArrayRef;
650 use crate::IntoArray;
651 use crate::VortexSessionExecute;
652 use crate::array_session;
653 use crate::arrays::DecimalArray;
654 use crate::arrays::PrimitiveArray;
655 use crate::assert_arrays_eq;
656 use crate::builtins::ArrayBuiltins;
657 use crate::compute::conformance::cast::test_cast_conformance;
658 use crate::dtype::DType;
659 use crate::dtype::DecimalDType;
660 use crate::dtype::DecimalType;
661 use crate::dtype::Nullability;
662 use crate::dtype::PType;
663 use crate::dtype::i256;
664 use crate::expr::stats::Stat;
665 use crate::validity::Validity;
666
667 #[test]
668 fn cast_u32_u8() {
669 let mut ctx = array_session().create_execution_ctx();
670 let arr = buffer![0u32, 10, 200].into_array();
671
672 let p = arr
674 .cast(PType::U8.into())
675 .unwrap()
676 .execute::<PrimitiveArray>(&mut ctx)
677 .unwrap();
678 assert_arrays_eq!(p, PrimitiveArray::from_iter([0u8, 10, 200]), &mut ctx);
679 assert!(matches!(p.validity(), Ok(Validity::NonNullable)));
680
681 let p = p
683 .into_array()
684 .cast(DType::Primitive(PType::U8, Nullability::Nullable))
685 .unwrap()
686 .execute::<PrimitiveArray>(&mut ctx)
687 .unwrap();
688 assert_arrays_eq!(
689 p,
690 PrimitiveArray::new(buffer![0u8, 10, 200], Validity::AllValid),
691 &mut ctx
692 );
693 assert!(matches!(p.validity(), Ok(Validity::AllValid)));
694
695 let p = p
697 .into_array()
698 .cast(DType::Primitive(PType::U8, Nullability::NonNullable))
699 .unwrap()
700 .execute::<PrimitiveArray>(&mut ctx)
701 .unwrap();
702 assert_arrays_eq!(p, PrimitiveArray::from_iter([0u8, 10, 200]), &mut ctx);
703 assert!(matches!(p.validity(), Ok(Validity::NonNullable)));
704
705 let p = p
707 .into_array()
708 .cast(DType::Primitive(PType::U32, Nullability::Nullable))
709 .unwrap()
710 .execute::<PrimitiveArray>(&mut ctx)
711 .unwrap();
712 assert_arrays_eq!(
713 p,
714 PrimitiveArray::new(buffer![0u32, 10, 200], Validity::AllValid),
715 &mut ctx
716 );
717 assert!(matches!(p.validity(), Ok(Validity::AllValid)));
718
719 let p = p
721 .into_array()
722 .cast(DType::Primitive(PType::U8, Nullability::NonNullable))
723 .unwrap()
724 .execute::<PrimitiveArray>(&mut ctx)
725 .unwrap();
726 assert_arrays_eq!(p, PrimitiveArray::from_iter([0u8, 10, 200]), &mut ctx);
727 assert!(matches!(p.validity(), Ok(Validity::NonNullable)));
728 }
729
730 #[test]
731 fn cast_u32_f32() {
732 let mut ctx = array_session().create_execution_ctx();
733 let arr = buffer![0u32, 10, 200].into_array();
734 let u8arr = arr
735 .cast(PType::F32.into())
736 .unwrap()
737 .execute::<PrimitiveArray>(&mut ctx)
738 .unwrap();
739 assert_arrays_eq!(
740 u8arr,
741 PrimitiveArray::from_iter([0.0f32, 10., 200.]),
742 &mut ctx
743 );
744 }
745
746 #[test]
747 fn cast_integer_to_decimal_rescales() -> VortexResult<()> {
748 let mut ctx = array_session().create_execution_ctx();
749 let decimal_dtype = DecimalDType::new(5, 2);
750 let casted = PrimitiveArray::from_iter([42i32, -7])
751 .into_array()
752 .cast(DType::Decimal(decimal_dtype, Nullability::NonNullable))?
753 .execute::<DecimalArray>(&mut ctx)?;
754
755 assert_eq!(
756 casted.dtype(),
757 &DType::Decimal(decimal_dtype, Nullability::NonNullable)
758 );
759 assert_eq!(casted.values_type(), DecimalType::I32);
760 assert_eq!(casted.buffer::<i32>().as_ref(), &[4_200, -700]);
761 Ok(())
762 }
763
764 #[test]
765 fn cast_same_width_signed_integer_to_decimal_reuses_buffer() -> VortexResult<()> {
766 let mut ctx = array_session().create_execution_ctx();
767 let source = PrimitiveArray::from_iter([42i32, -7]);
768 let source_ptr = source.as_slice::<i32>().as_ptr();
769 let casted = source
770 .into_array()
771 .cast(DType::Decimal(
772 DecimalDType::new(9, 0),
773 Nullability::NonNullable,
774 ))?
775 .execute::<DecimalArray>(&mut ctx)?;
776
777 assert_eq!(casted.buffer::<i32>().as_ptr(), source_ptr);
778 assert_eq!(casted.buffer::<i32>().as_ref(), &[42, -7]);
779 Ok(())
780 }
781
782 #[test]
783 fn cast_same_width_signed_integer_to_decimal_reuses_buffer_with_cached_bounds()
784 -> VortexResult<()> {
785 let mut ctx = array_session().create_execution_ctx();
786 let source = PrimitiveArray::from_iter([42i32, -7]);
787 let source_ptr = source.as_slice::<i32>().as_ptr();
788 let source = source.into_array();
789 source
790 .statistics()
791 .compute_all(&[Stat::Min, Stat::Max], &mut ctx)?;
792 let casted = source
793 .cast(DType::Decimal(
794 DecimalDType::new(9, 0),
795 Nullability::NonNullable,
796 ))?
797 .execute::<DecimalArray>(&mut ctx)?;
798
799 assert_eq!(casted.buffer::<i32>().as_ptr(), source_ptr);
800 Ok(())
801 }
802
803 #[test]
804 fn cast_same_width_signed_integer_to_decimal_ignores_out_of_range_nulls() -> VortexResult<()> {
805 let mut ctx = array_session().create_execution_ctx();
806 let source = PrimitiveArray::new(buffer![i32::MAX, 42], Validity::from_iter([false, true]));
807 let source_ptr = source.as_slice::<i32>().as_ptr();
808 let casted = source
809 .into_array()
810 .cast(DType::Decimal(
811 DecimalDType::new(9, 0),
812 Nullability::Nullable,
813 ))?
814 .execute::<DecimalArray>(&mut ctx)?;
815
816 assert_eq!(casted.buffer::<i32>().as_ptr(), source_ptr);
817 assert_eq!(
818 casted.validity()?.execute_mask(casted.len(), &mut ctx)?,
819 Mask::from(BitBuffer::from(vec![false, true]))
820 );
821 Ok(())
822 }
823
824 #[test]
825 fn cast_same_width_signed_integer_to_decimal_checks_precision() -> VortexResult<()> {
826 let mut ctx = array_session().create_execution_ctx();
827 let casted = PrimitiveArray::from_iter([i32::MAX])
828 .into_array()
829 .cast(DType::Decimal(
830 DecimalDType::new(9, 0),
831 Nullability::NonNullable,
832 ))?;
833
834 let error = casted.execute::<DecimalArray>(&mut ctx).unwrap_err();
835 assert!(error.to_string().contains("does not fit in precision"));
836 Ok(())
837 }
838
839 #[test]
840 fn cast_u64_to_decimal() -> VortexResult<()> {
841 let mut ctx = array_session().create_execution_ctx();
842 let decimal_dtype = DecimalDType::new(20, 0);
843 let casted = PrimitiveArray::from_iter([u64::MAX])
844 .into_array()
845 .cast(DType::Decimal(decimal_dtype, Nullability::NonNullable))?
846 .execute::<DecimalArray>(&mut ctx)?;
847
848 assert_eq!(casted.values_type(), DecimalType::I128);
849 assert_eq!(casted.buffer::<i128>().as_ref(), &[i128::from(u64::MAX)]);
850 Ok(())
851 }
852
853 #[test]
854 fn cast_integer_to_decimal_reports_scale_up_overflow() -> VortexResult<()> {
855 let mut ctx = array_session().create_execution_ctx();
856 let dtype = DType::Decimal(DecimalDType::new(38, 20), Nullability::NonNullable);
857 let casted = PrimitiveArray::from_iter([u64::MAX])
858 .into_array()
859 .cast(dtype)?;
860 let actual = casted.execute::<DecimalArray>(&mut ctx).unwrap_err();
861
862 assert!(
863 actual
864 .to_string()
865 .contains("does not fit in precision of decimal(38,20)")
866 );
867 Ok(())
868 }
869
870 #[test]
871 fn cast_u8_to_negative_scale_decimal() -> VortexResult<()> {
872 let mut ctx = array_session().create_execution_ctx();
873 let decimal_dtype = DecimalDType::new(2, -2);
874 let casted = PrimitiveArray::from_iter([200u8])
875 .into_array()
876 .cast(DType::Decimal(decimal_dtype, Nullability::NonNullable))?
877 .execute::<DecimalArray>(&mut ctx)?;
878
879 assert_eq!(casted.values_type(), DecimalType::I8);
880 assert_eq!(casted.buffer::<i8>().as_ref(), &[2]);
881 Ok(())
882 }
883
884 #[test]
885 fn cast_u64_to_negative_scale_decimal() -> VortexResult<()> {
886 let mut ctx = array_session().create_execution_ctx();
887 let decimal_dtype = DecimalDType::new(1, -19);
888 let casted = PrimitiveArray::from_iter([10_000_000_000_000_000_000u64])
889 .into_array()
890 .cast(DType::Decimal(decimal_dtype, Nullability::NonNullable))?
891 .execute::<DecimalArray>(&mut ctx)?;
892
893 assert_eq!(casted.values_type(), DecimalType::I8);
894 assert_eq!(casted.buffer::<i8>().as_ref(), &[1]);
895 Ok(())
896 }
897
898 #[test]
899 fn cast_integer_to_i256_decimal() -> VortexResult<()> {
900 let mut ctx = array_session().create_execution_ctx();
901 let decimal_dtype = DecimalDType::new(39, 2);
902 let casted = PrimitiveArray::from_iter([42i64])
903 .into_array()
904 .cast(DType::Decimal(decimal_dtype, Nullability::NonNullable))?
905 .execute::<DecimalArray>(&mut ctx)?;
906
907 assert_eq!(casted.values_type(), DecimalType::I256);
908 assert_eq!(casted.buffer::<i256>().as_ref(), &[i256::from_i128(4_200)]);
909 Ok(())
910 }
911
912 #[test]
913 fn cast_all_null_integer_to_decimal() -> VortexResult<()> {
914 let mut ctx = array_session().create_execution_ctx();
915 let decimal_dtype = DecimalDType::new(39, 2);
916 let casted = PrimitiveArray::new(buffer![i64::MAX, i64::MIN], Validity::AllInvalid)
917 .into_array()
918 .cast(DType::Decimal(decimal_dtype, Nullability::Nullable))?
919 .execute::<DecimalArray>(&mut ctx)?;
920
921 assert!(matches!(casted.validity(), Ok(Validity::AllInvalid)));
922 assert_eq!(casted.buffer::<i256>().as_ref(), &[i256::ZERO, i256::ZERO]);
923 Ok(())
924 }
925
926 #[test]
927 fn cast_integer_to_negative_scale_decimal_requires_exact_rescale() -> VortexResult<()> {
928 let mut ctx = array_session().create_execution_ctx();
929 let decimal_dtype = DecimalDType::new(3, -2);
930 let casted = PrimitiveArray::from_iter([1_200i32, -500])
931 .into_array()
932 .cast(DType::Decimal(decimal_dtype, Nullability::NonNullable))?
933 .execute::<DecimalArray>(&mut ctx)?;
934
935 assert_eq!(casted.buffer::<i16>().as_ref(), &[12, -5]);
936
937 let error = PrimitiveArray::from_iter([42i32])
938 .into_array()
939 .cast(DType::Decimal(decimal_dtype, Nullability::NonNullable))?
940 .execute::<DecimalArray>(&mut ctx)
941 .unwrap_err();
942 assert!(error.to_string().contains("would lose precision"));
943 Ok(())
944 }
945
946 #[test]
947 fn cast_zero_to_large_negative_scale_decimal() -> VortexResult<()> {
948 let mut ctx = array_session().create_execution_ctx();
949 let decimal_dtype = DecimalDType::new(3, -128);
950 let casted = PrimitiveArray::from_iter([0i32])
951 .into_array()
952 .cast(DType::Decimal(decimal_dtype, Nullability::NonNullable))?
953 .execute::<DecimalArray>(&mut ctx)?;
954
955 assert_eq!(casted.buffer::<i16>().as_ref(), &[0]);
956 Ok(())
957 }
958
959 #[test]
960 fn cast_integer_to_decimal_ignores_out_of_range_null_lanes() -> VortexResult<()> {
961 let mut ctx = array_session().create_execution_ctx();
962 let decimal_dtype = DecimalDType::new(3, 1);
963 let casted = PrimitiveArray::new(buffer![999i32, 42], Validity::from_iter([false, true]))
964 .into_array()
965 .cast(DType::Decimal(decimal_dtype, Nullability::Nullable))?
966 .execute::<DecimalArray>(&mut ctx)?;
967
968 assert_eq!(casted.buffer::<i16>().as_ref()[1], 420);
969 assert_eq!(
970 casted.validity()?.execute_mask(casted.len(), &mut ctx)?,
971 Mask::from(BitBuffer::from(vec![false, true]))
972 );
973 Ok(())
974 }
975
976 #[test]
977 fn cast_integer_to_decimal_checks_precision() -> VortexResult<()> {
978 let mut ctx = array_session().create_execution_ctx();
979 let casted = PrimitiveArray::from_iter([100i32])
980 .into_array()
981 .cast(DType::Decimal(
982 DecimalDType::new(2, 1),
983 Nullability::NonNullable,
984 ))?;
985
986 let error = casted.execute::<DecimalArray>(&mut ctx).unwrap_err();
987 assert!(error.to_string().contains("does not fit in precision"));
988 Ok(())
989 }
990
991 #[test]
992 fn cast_floating_primitive_to_decimal_fails() -> VortexResult<()> {
993 let mut ctx = array_session().create_execution_ctx();
994 let casted = PrimitiveArray::from_iter([1.0f64])
995 .into_array()
996 .cast(DType::Decimal(
997 DecimalDType::new(3, 1),
998 Nullability::NonNullable,
999 ))?;
1000
1001 let error = casted.execute::<DecimalArray>(&mut ctx).unwrap_err();
1002 assert!(
1003 error
1004 .to_string()
1005 .contains("Cannot cast floating primitive f64 to decimal decimal(3,1)")
1006 );
1007 Ok(())
1008 }
1009
1010 #[test]
1011 fn cast_i32_u32() {
1012 let arr = buffer![-1i32].into_array();
1013 #[expect(deprecated)]
1014 let error = arr
1015 .cast(PType::U32.into())
1016 .and_then(|a| a.to_canonical().map(|c| c.into_array()))
1017 .unwrap_err();
1018 assert!(matches!(error, VortexError::Compute(..)));
1019 assert!(error.to_string().contains("values exceed target range"));
1020 }
1021
1022 #[test]
1023 fn cast_array_with_nulls_to_nonnullable() {
1024 let arr = PrimitiveArray::from_option_iter([Some(-1i32), None, Some(10)]);
1025 #[expect(deprecated)]
1026 let err = arr
1027 .into_array()
1028 .cast(PType::I32.into())
1029 .and_then(|a| a.to_canonical().map(|c| c.into_array()))
1030 .unwrap_err();
1031
1032 assert!(matches!(err, VortexError::InvalidArgument(..)));
1033 assert!(
1034 err.to_string()
1035 .contains("Cannot cast array with invalid values to non-nullable type.")
1036 );
1037 }
1038
1039 #[test]
1040 fn cast_with_invalid_nulls() {
1041 let mut ctx = array_session().create_execution_ctx();
1042 let arr = PrimitiveArray::new(
1043 buffer![-1i32, 0, 10],
1044 Validity::from_iter([false, true, true]),
1045 );
1046 let p = arr
1047 .into_array()
1048 .cast(DType::Primitive(PType::U32, Nullability::Nullable))
1049 .unwrap()
1050 .execute::<PrimitiveArray>(&mut ctx)
1051 .unwrap();
1052 assert_arrays_eq!(
1053 p,
1054 PrimitiveArray::from_option_iter([None, Some(0u32), Some(10)]),
1055 &mut ctx
1056 );
1057 assert_eq!(
1058 p.as_ref()
1059 .validity()
1060 .unwrap()
1061 .execute_mask(
1062 p.as_ref().len(),
1063 &mut array_session().create_execution_ctx()
1064 )
1065 .unwrap(),
1066 Mask::from(BitBuffer::from(vec![false, true, true]))
1067 );
1068 }
1069
1070 #[test]
1073 fn cast_same_width_int_reinterprets_buffer() -> VortexResult<()> {
1074 let mut ctx = array_session().create_execution_ctx();
1075 let src = PrimitiveArray::from_iter([0u32, 10, 100]);
1076 let src_ptr = src.as_slice::<u32>().as_ptr();
1077
1078 let dst = src
1079 .into_array()
1080 .cast(PType::I32.into())?
1081 .execute::<PrimitiveArray>(&mut ctx)?;
1082 let dst_ptr = dst.as_slice::<i32>().as_ptr();
1083
1084 assert_eq!(src_ptr as usize, dst_ptr as usize);
1086 assert_arrays_eq!(dst, PrimitiveArray::from_iter([0i32, 10, 100]), &mut ctx);
1087 Ok(())
1088 }
1089
1090 #[test]
1093 fn cast_same_width_int_out_of_range_errors() {
1094 let arr = buffer![u32::MAX].into_array();
1095 #[expect(deprecated)]
1096 let err = arr
1097 .cast(PType::I32.into())
1098 .and_then(|a| a.to_canonical().map(|c| c.into_array()))
1099 .unwrap_err();
1100 assert!(matches!(err, VortexError::Compute(..)));
1101 }
1102
1103 #[test]
1106 fn cast_same_width_all_null() -> VortexResult<()> {
1107 let mut ctx = array_session().create_execution_ctx();
1108 let arr = PrimitiveArray::new(buffer![0xFFu8, 0xFF], Validity::AllInvalid);
1109 let casted = arr
1110 .into_array()
1111 .cast(DType::Primitive(PType::I8, Nullability::Nullable))?
1112 .execute::<PrimitiveArray>(&mut ctx)?;
1113 assert_eq!(casted.len(), 2);
1114 assert!(matches!(casted.validity(), Ok(Validity::AllInvalid)));
1115 Ok(())
1116 }
1117
1118 #[test]
1121 fn cast_same_width_int_nullable_with_out_of_range_nulls() -> VortexResult<()> {
1122 let mut ctx = array_session().create_execution_ctx();
1123 let arr = PrimitiveArray::new(
1126 buffer![u32::MAX, 0u32, 42u32],
1127 Validity::from_iter([false, true, true]),
1128 );
1129 let casted = arr
1130 .into_array()
1131 .cast(DType::Primitive(PType::I32, Nullability::Nullable))?
1132 .execute::<PrimitiveArray>(&mut ctx)?;
1133 assert_arrays_eq!(
1134 casted,
1135 PrimitiveArray::from_option_iter([None, Some(0i32), Some(42)]),
1136 &mut ctx
1137 );
1138 Ok(())
1139 }
1140
1141 #[test]
1142 fn cast_u32_to_u8_with_out_of_range_nulls() -> VortexResult<()> {
1143 let mut ctx = array_session().create_execution_ctx();
1144 let arr = PrimitiveArray::new(
1145 buffer![1000u32, 10u32, 42u32],
1146 Validity::from_iter([false, true, true]),
1147 );
1148 let casted = arr
1149 .into_array()
1150 .cast(DType::Primitive(PType::U8, Nullability::Nullable))?
1151 .execute::<PrimitiveArray>(&mut ctx)?;
1152 assert_arrays_eq!(
1153 casted,
1154 PrimitiveArray::from_option_iter([None, Some(10u8), Some(42)]),
1155 &mut ctx
1156 );
1157 Ok(())
1158 }
1159
1160 #[rstest]
1161 #[case(buffer![0u8, 1, 2, 3, 255].into_array())]
1162 #[case(buffer![0u16, 100, 1000, 65535].into_array())]
1163 #[case(buffer![0u32, 100, 1000, 1000000].into_array())]
1164 #[case(buffer![0u64, 100, 1000, 1000000000].into_array())]
1165 #[case(buffer![-128i8, -1, 0, 1, 127].into_array())]
1166 #[case(buffer![-1000i16, -1, 0, 1, 1000].into_array())]
1167 #[case(buffer![-1000000i32, -1, 0, 1, 1000000].into_array())]
1168 #[case(buffer![-1000000000i64, -1, 0, 1, 1000000000].into_array())]
1169 #[case(buffer![0.0f32, 1.5, -2.5, 100.0, 1e6].into_array())]
1170 #[case(buffer![f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 0.0f32].into_array())]
1171 #[case(buffer![0.0f64, 1.5, -2.5, 100.0, 1e12].into_array())]
1172 #[case(buffer![f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 0.0f64].into_array())]
1173 #[case(PrimitiveArray::from_option_iter([Some(1u8), None, Some(255), Some(0), None]).into_array())]
1174 #[case(PrimitiveArray::from_option_iter([Some(1i32), None, Some(-100), Some(0), None]).into_array())]
1175 #[case(buffer![42u32].into_array())]
1176 fn test_cast_primitive_conformance(#[case] array: ArrayRef) {
1177 test_cast_conformance(&array, &mut array_session().create_execution_ctx());
1178 }
1179}