Skip to main content

vortex_array/arrays/primitive/compute/
cast.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::mem::MaybeUninit;
5use std::slice;
6
7use num_traits::AsPrimitive;
8use vortex_buffer::BufferMut;
9use vortex_buffer::ByteBuffer;
10use vortex_compute::lane_kernels::IndexedSourceExt;
11use vortex_error::VortexError;
12use vortex_error::VortexResult;
13use vortex_error::vortex_bail;
14use vortex_error::vortex_err;
15use vortex_mask::Mask;
16
17use crate::ArrayRef;
18use crate::ExecutionCtx;
19use crate::IntoArray;
20use crate::array::ArrayView;
21use crate::arrays::ConstantArray;
22use crate::arrays::DecimalArray;
23use crate::arrays::Primitive;
24use crate::arrays::PrimitiveArray;
25use crate::arrays::primitive::PrimitiveArrayExt;
26use crate::arrays::primitive::compute::integer_cast;
27use crate::arrays::primitive::compute::integer_cast::IntegerCast;
28use crate::arrays::primitive::compute::integer_cast::IntegerType;
29use crate::arrays::primitive::compute::integer_cast::Remainder;
30use crate::arrays::primitive::compute::integer_cast::all_valid_lanes;
31use crate::buffer::BufferHandle;
32use crate::dtype::DType;
33use crate::dtype::DecimalDType;
34use crate::dtype::DecimalType;
35use crate::dtype::NativePType;
36use crate::dtype::Nullability;
37use crate::dtype::PType;
38use crate::dtype::half::f16;
39use crate::dtype::i256;
40use crate::match_each_float_ptype;
41use crate::match_each_integer_ptype;
42use crate::scalar::DecimalValue;
43use crate::scalar::Scalar;
44use crate::scalar_fn::builtin::cast::CastKernel;
45use crate::scalar_fn::builtin::cast::CastReduce;
46use crate::stats::Precision;
47use crate::stats::Stat;
48use crate::stats::StatsProvider;
49use crate::stats::StatsProviderExt;
50use crate::validity::Validity;
51
52impl CastReduce for Primitive {
53    fn cast(array: ArrayView<'_, Primitive>, dtype: &DType) -> VortexResult<Option<ArrayRef>> {
54        // Only the same ptype is reducible without execution; type changes need the kernel
55        // to verify values fit in the target range.
56        let DType::Primitive(new_ptype, new_nullability) = dtype else {
57            return Ok(None);
58        };
59        if *new_ptype != array.ptype() {
60            return Ok(None);
61        }
62
63        let Some(new_validity) = array
64            .validity()?
65            .trivially_cast_nullability(*new_nullability, array.len())?
66        else {
67            return Ok(None);
68        };
69
70        // SAFETY: validity and data buffer still have same length.
71        Ok(Some(unsafe {
72            PrimitiveArray::new_unchecked_from_handle(
73                array.buffer_handle().clone(),
74                array.ptype(),
75                new_validity,
76            )
77            .into_array()
78        }))
79    }
80}
81
82impl CastKernel for Primitive {
83    fn cast(
84        array: ArrayView<'_, Primitive>,
85        dtype: &DType,
86        ctx: &mut ExecutionCtx,
87    ) -> VortexResult<Option<ArrayRef>> {
88        if let DType::Decimal(decimal_dtype, nullability) = dtype {
89            return cast_to_decimal(array, *decimal_dtype, *nullability, ctx).map(Some);
90        }
91        let DType::Primitive(new_ptype, new_nullability) = dtype else {
92            return Ok(None);
93        };
94        let (new_ptype, new_nullability) = (*new_ptype, *new_nullability);
95        let src_ptype = array.ptype();
96
97        let new_validity = array
98            .validity()?
99            .cast_nullability(new_nullability, array.len(), ctx)?;
100
101        // Same bit representation: either the same ptype (only the nullability changed) or two
102        // same-width integers (identical layout under 2's complement).
103        let reinterprets = src_ptype == new_ptype
104            || (src_ptype.is_int()
105                && new_ptype.is_int()
106                && src_ptype.byte_width() == new_ptype.byte_width());
107        let all_null = || {
108            ConstantArray::new(
109                Scalar::null(DType::Primitive(new_ptype, Nullability::Nullable)),
110                array.len(),
111            )
112            .into_array()
113        };
114
115        // Only integer targets can reject a value: every float target accepts every value, with
116        // finite values rounding or saturating to infinity. The accepted values of an integer
117        // target form a single range, so checking the min and max checks every value. Once the
118        // values are known to fit, the conversion below is the infallible `as` cast.
119        let target_dtype = DType::Primitive(new_ptype, Nullability::NonNullable);
120        if new_ptype.is_int()
121            && !src_ptype.casts_losslessly_to(new_ptype)
122            && !cached_values_fit_in(array, &target_dtype).unwrap_or(false)
123        {
124            let mask = array.validity()?.execute_mask(array.len(), ctx)?;
125            if !reinterprets && !array.is_empty() && matches!(mask, Mask::AllFalse(_)) {
126                return Ok(Some(all_null()));
127            }
128            if !values_fit_in(array, new_ptype, &mask) {
129                vortex_bail!(
130                    "Cannot cast {} to {} — values exceed target range",
131                    src_ptype,
132                    new_ptype,
133                );
134            }
135        }
136
137        if reinterprets {
138            return Ok(Some(reinterpret(array, new_ptype, new_validity)));
139        }
140        // Converting null values would only produce more nulls.
141        if !array.is_empty() && matches!(array.validity()?, Validity::AllInvalid) {
142            return Ok(Some(all_null()));
143        }
144
145        let values = convert_values(array, new_ptype);
146        Ok(Some(
147            PrimitiveArray::from_byte_buffer(values, new_ptype, new_validity).into_array(),
148        ))
149    }
150}
151
152fn cast_to_decimal(
153    array: ArrayView<'_, Primitive>,
154    decimal_dtype: DecimalDType,
155    nullability: Nullability,
156    ctx: &mut ExecutionCtx,
157) -> VortexResult<ArrayRef> {
158    if !array.ptype().is_int() {
159        vortex_bail!(
160            "Cannot cast floating primitive {} to decimal {}",
161            array.ptype(),
162            decimal_dtype
163        );
164    }
165
166    let source_validity = array.validity()?;
167    let validity = source_validity
168        .clone()
169        .cast_nullability(nullability, array.len(), ctx)?;
170    let values_type = decimal_dtype.canonical_values_type();
171    let cast = IntegerCast::to_decimal(IntegerType::of_ptype(array.ptype()), 0, decimal_dtype);
172    let values = array.buffer_handle().as_host();
173
174    let error = |index| {
175        primitive_to_decimal_cast_error(cast.source_type().value_at(values, index), decimal_dtype)
176    };
177
178    // An unscaled cast from a signed integer to decimals of the same width keeps the values buffer.
179    if decimal_dtype.scale() == 0
180        && signed_primitive_decimal_type(array.ptype()) == Some(values_type)
181    {
182        let target_dtype = DType::Decimal(decimal_dtype, Nullability::NonNullable);
183        if !cached_values_fit_in(array, &target_dtype).unwrap_or(false) {
184            let valid_values = source_validity.execute_mask(array.len(), ctx)?;
185            if let Some(index) = cast.first_misfit(values, &valid_values) {
186                return Err(error(index));
187            }
188        }
189        // SAFETY: the decimal values type has the same physical representation as the source
190        // ptype, and either exact min/max statistics or the validation above prove every valid
191        // value fits.
192        return Ok(unsafe {
193            DecimalArray::new_unchecked_handle(
194                array.buffer_handle().clone(),
195                values_type,
196                decimal_dtype,
197                validity,
198            )
199            .into_array()
200        });
201    }
202
203    let valid_values = source_validity.execute_mask(array.len(), ctx)?;
204    if !array.is_empty() && matches!(valid_values, Mask::AllFalse(_)) {
205        return Ok(ConstantArray::new(
206            Scalar::null(DType::Decimal(decimal_dtype, nullability)),
207            array.len(),
208        )
209        .into_array());
210    }
211    let casted = cast.cast(values, &valid_values).map_err(error)?;
212    // Every valid value has been checked against the precision, so skip the constructor's scan.
213    Ok(DecimalArray::try_new_handle_from_trusted_values(
214        BufferHandle::new_host(casted),
215        values_type,
216        decimal_dtype,
217        validity,
218    )?
219    .into_array())
220}
221
222/// Decimal physical type with the same representation, when `ptype` is signed.
223fn signed_primitive_decimal_type(ptype: PType) -> Option<DecimalType> {
224    match ptype {
225        PType::I8 => Some(DecimalType::I8),
226        PType::I16 => Some(DecimalType::I16),
227        PType::I32 => Some(DecimalType::I32),
228        PType::I64 => Some(DecimalType::I64),
229        PType::U8 | PType::U16 | PType::U32 | PType::U64 => None,
230        PType::F16 | PType::F32 | PType::F64 => {
231            unreachable!("floating primitives are rejected before selecting a decimal type")
232        }
233    }
234}
235
236#[cold]
237#[inline(never)]
238fn primitive_to_decimal_cast_error(value: i256, decimal_dtype: DecimalDType) -> VortexError {
239    match DecimalValue::rescale_i256(value, 0, decimal_dtype.scale())
240        .and_then(|value| DecimalValue::try_from_i256(value, decimal_dtype))
241    {
242        Err(error) => error,
243        Ok(_) => {
244            debug_assert!(
245                false,
246                "primitive-to-decimal fast path rejected a value that the scalar cast accepts"
247            );
248            vortex_err!(
249                "primitive value cannot be represented while casting to {}",
250                decimal_dtype
251            )
252        }
253    }
254}
255
256/// Converts every value of `array` to `to` with `as` semantics and returns the raw values.
257///
258/// The caller has already checked that every valid value is representable in `to`. Null lanes
259/// may hold any value; `as` is defined for every input, so they convert to unspecified values.
260///
261/// Integer-to-integer conversions, the bulk of the (source, target) pairs, share the kernels of
262/// [`integer_cast::resize`], which only depend on the widths and the source's signedness.
263///
264/// Conversions to or from floats use one kernel per pair. Composing them through an integer
265/// intermediate would share kernels too, but measured 50-60% slower than converting directly.
266fn convert_values(array: ArrayView<'_, Primitive>, to: PType) -> ByteBuffer {
267    let from = array.ptype();
268    match (from.is_float(), to.is_float()) {
269        (false, false) => integer_cast::resize(
270            array.buffer_handle().as_host(),
271            IntegerType::of_ptype(from),
272            IntegerType::of_ptype(to),
273        ),
274        (false, true) => int_to_float(array, to),
275        (true, false) => float_to_int(array, to),
276        (true, true) => match (from, to) {
277            (PType::F16, PType::F32) => convert_buffer::<f16, f32>(values_as(array)),
278            (PType::F16, PType::F64) => convert_buffer::<f16, f64>(values_as(array)),
279            (PType::F32, PType::F16) => convert_buffer::<f32, f16>(values_as(array)),
280            (PType::F32, PType::F64) => convert_buffer::<f32, f64>(values_as(array)),
281            (PType::F64, PType::F16) => convert_buffer::<f64, f16>(values_as(array)),
282            (PType::F64, PType::F32) => convert_buffer::<f64, f32>(values_as(array)),
283            _ => unreachable!("float conversion from {from} to {to}"),
284        },
285    }
286}
287
288fn int_to_float(array: ArrayView<'_, Primitive>, to: PType) -> ByteBuffer {
289    match_each_float_ptype!(to, |T| {
290        match_each_integer_ptype!(array.ptype(), |F| {
291            convert_buffer::<F, T>(values_as(array))
292        })
293    })
294}
295
296fn float_to_int(array: ArrayView<'_, Primitive>, to: PType) -> ByteBuffer {
297    match_each_float_ptype!(array.ptype(), |F| {
298        match_each_integer_ptype!(to, |T| { convert_buffer::<F, T>(values_as(array)) })
299    })
300}
301
302/// Converts `src` to `B`.
303fn convert_buffer<A, B>(src: &[A]) -> ByteBuffer
304where
305    A: AsPrimitive<B>,
306    B: Copy + 'static,
307{
308    let len = src.len();
309    let mut out = BufferMut::<B>::with_capacity(len);
310    convert::<A, B>(src, &mut out.spare_capacity_mut()[..len]);
311    // SAFETY: `convert` initialized every lane.
312    unsafe { out.set_len(len) };
313    out.freeze().into_byte_buffer()
314}
315
316/// The conversion kernel, kept out of line so that each (`A`, `B`) pair is compiled once however
317/// many target types share it.
318#[inline(never)]
319fn convert<A, B>(src: &[A], dst: &mut [MaybeUninit<B>])
320where
321    A: AsPrimitive<B>,
322    B: Copy + 'static,
323{
324    src.map_into(dst, |v| v.as_());
325}
326
327/// The values of `array` as `T`, which has the same width as the array's ptype.
328fn values_as<T: NativePType>(array: ArrayView<'_, Primitive>) -> &[T] {
329    assert_eq!(
330        T::PTYPE.byte_width(),
331        array.ptype().byte_width(),
332        "can only view values as a type of the same width"
333    );
334    let bytes = array.buffer_handle().as_host();
335    // SAFETY: the buffer is aligned to the array's ptype, whose width and alignment `T` shares,
336    // and every bit pattern is a valid `T`.
337    unsafe { slice::from_raw_parts(bytes.as_ptr().cast::<T>(), bytes.len() / size_of::<T>()) }
338}
339
340fn reinterpret(
341    array: ArrayView<'_, Primitive>,
342    new_ptype: PType,
343    new_validity: Validity,
344) -> ArrayRef {
345    // SAFETY: caller has verified the bit representation is compatible and that validity length
346    // still matches the buffer length.
347    unsafe {
348        PrimitiveArray::new_unchecked_from_handle(
349            array.buffer_handle().clone(),
350            new_ptype,
351            new_validity,
352        )
353    }
354    .into_array()
355}
356
357/// Returns `true` if every valid value in `array` is representable as the integer `target_ptype`,
358/// using the same rules as [`num_traits::NumCast`]: floats truncate toward zero, and NaN and
359/// infinities never fit. Only the values that `mask` marks valid are checked.
360///
361/// The check is compiled once per source type, with the target's range passed at runtime.
362fn values_fit_in(array: ArrayView<'_, Primitive>, target_ptype: PType, mask: &Mask) -> bool {
363    if array.ptype().is_float() {
364        // Floats truncate toward zero, so the values that fit lie strictly between
365        // `target_min - 1` and `target_max + 1`.
366        let (lower, upper) = float_exclusive_bounds(target_ptype);
367        return match array.ptype() {
368            PType::F16 => floats_fit_f32(array.as_slice::<f16>(), mask, lower, upper),
369            PType::F32 => floats_fit_f32(array.as_slice::<f32>(), mask, lower, upper),
370            _ => all_valid_lanes(array.as_slice::<f64>(), mask, |v| (lower < v) & (v < upper)),
371        };
372    }
373    let cast = IntegerCast::new(
374        IntegerType::of_ptype(array.ptype()),
375        IntegerType::of_ptype(target_ptype),
376        0,
377        Remainder::Reject,
378    );
379    cast.first_misfit(array.buffer_handle().as_host(), mask)
380        .is_none()
381}
382
383/// Checks f16 or f32 values against the exclusive f64 bounds in f32, which vectorizes better
384/// than widening every value to f64.
385///
386/// Rounding each bound outward to f32 keeps the check exact: no f32 lies between a bound and its
387/// rounding, so a value is above the rounded lower bound exactly when it is above the original.
388#[expect(
389    clippy::cast_possible_truncation,
390    reason = "the bounds are rounded to f32 on purpose, and corrected outward"
391)]
392fn floats_fit_f32<F: AsPrimitive<f32>>(values: &[F], mask: &Mask, lower: f64, upper: f64) -> bool {
393    let mut lower32 = lower as f32;
394    if <f64 as From<f32>>::from(lower32) > lower {
395        lower32 = lower32.next_down();
396    }
397    let mut upper32 = upper as f32;
398    if <f64 as From<f32>>::from(upper32) < upper {
399        upper32 = upper32.next_up();
400    }
401    all_valid_lanes(values, mask, |v| {
402        let v: f32 = v.as_();
403        (lower32 < v) & (v < upper32)
404    })
405}
406
407/// The inclusive range of the integer `ptype`.
408fn integer_range(ptype: PType) -> (i128, i128) {
409    match ptype {
410        PType::U8 => (0, u8::MAX.into()),
411        PType::U16 => (0, u16::MAX.into()),
412        PType::U32 => (0, u32::MAX.into()),
413        PType::U64 => (0, u64::MAX.into()),
414        PType::I8 => (i8::MIN.into(), i8::MAX.into()),
415        PType::I16 => (i16::MIN.into(), i16::MAX.into()),
416        PType::I32 => (i32::MIN.into(), i32::MAX.into()),
417        PType::I64 => (i64::MIN.into(), i64::MAX.into()),
418        _ => unreachable!("{ptype} is not an integer type"),
419    }
420}
421
422/// The f64 bounds that a float must lie strictly between to truncate into the integer `ptype`.
423///
424/// The bounds are `min - 1` and `max + 1`, which f64 holds exactly for every integer type but
425/// `i64`. There, `min - 1` is replaced by the next f64 below `i64::MIN`, which excludes the same
426/// floats.
427#[expect(
428    clippy::cast_precision_loss,
429    reason = "f64 holds integers below 64 bits exactly, and u64::MAX rounds up to exactly max + 1"
430)]
431fn float_exclusive_bounds(ptype: PType) -> (f64, f64) {
432    match ptype {
433        PType::I64 => (i64::MIN as f64 - 2048.0, -(i64::MIN as f64)),
434        PType::U64 => (-1.0, u64::MAX as f64),
435        _ => {
436            let (min, max) = integer_range(ptype);
437            (min as f64 - 1.0, max as f64 + 1.0)
438        }
439    }
440}
441
442/// Returns whether every valid value fits `target_dtype` if exact statistics can answer it.
443///
444/// Cached min and max skip NaN, so for floats they only answer once the NaN count is known.
445fn cached_values_fit_in(array: ArrayView<'_, Primitive>, target_dtype: &DType) -> Option<bool> {
446    let stats = array.array().statistics();
447    if array.ptype().is_float() {
448        match stats.get_as::<u64>(Stat::NaNCount) {
449            Precision::Exact(0) => {}
450            Precision::Exact(_) => return Some(false),
451            _ => return None,
452        }
453    }
454    let min = stats.get(Stat::Min).as_exact()?;
455    let max = stats.get(Stat::Max).as_exact()?;
456    Some(min.cast(target_dtype).is_ok() && max.cast(target_dtype).is_ok())
457}
458
459#[cfg(test)]
460mod test {
461    use std::sync::LazyLock;
462
463    use rstest::rstest;
464    use vortex_buffer::Alignment;
465    use vortex_buffer::BitBuffer;
466    use vortex_buffer::buffer;
467    use vortex_error::VortexExpect;
468    use vortex_error::VortexResult;
469    use vortex_mask::Mask;
470    use vortex_session::VortexSession;
471
472    use crate::ArrayRef;
473    use crate::Canonical;
474    use crate::IntoArray;
475    use crate::VortexSessionExecute;
476    use crate::arrays::BoolArray;
477    use crate::arrays::Constant;
478    use crate::arrays::DecimalArray;
479    use crate::arrays::Primitive;
480    use crate::arrays::PrimitiveArray;
481    use crate::assert_arrays_eq;
482    use crate::buffer::BufferHandle;
483    use crate::builtins::ArrayBuiltins;
484    use crate::compute::conformance::cast::test_cast_conformance;
485    use crate::dtype::DType;
486    use crate::dtype::DecimalDType;
487    use crate::dtype::DecimalType;
488    use crate::dtype::Nullability;
489    use crate::dtype::PType;
490    use crate::dtype::i256;
491    use crate::match_each_decimal_value_type;
492    use crate::match_each_native_ptype;
493    use crate::scalar_fn::builtin::cast::CastKernel;
494    use crate::stats::Stat;
495    use crate::validity::Validity;
496
497    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
498
499    #[test]
500    fn cast_u32_u8() {
501        let mut ctx = SESSION.create_execution_ctx();
502        let arr = buffer![0u32, 10, 200].into_array();
503
504        // cast from u32 to u8
505        let p = arr
506            .cast(PType::U8.into())
507            .unwrap()
508            .execute::<PrimitiveArray>(&mut ctx)
509            .unwrap();
510        assert_arrays_eq!(p, PrimitiveArray::from_iter([0u8, 10, 200]), &mut ctx);
511        assert!(matches!(p.validity(), Ok(Validity::NonNullable)));
512
513        // to nullable
514        let p = p
515            .into_array()
516            .cast(DType::Primitive(PType::U8, Nullability::Nullable))
517            .unwrap()
518            .execute::<PrimitiveArray>(&mut ctx)
519            .unwrap();
520        assert_arrays_eq!(
521            p,
522            PrimitiveArray::new(buffer![0u8, 10, 200], Validity::AllValid),
523            &mut ctx
524        );
525        assert!(matches!(p.validity(), Ok(Validity::AllValid)));
526
527        // back to non-nullable
528        let p = p
529            .into_array()
530            .cast(DType::Primitive(PType::U8, Nullability::NonNullable))
531            .unwrap()
532            .execute::<PrimitiveArray>(&mut ctx)
533            .unwrap();
534        assert_arrays_eq!(p, PrimitiveArray::from_iter([0u8, 10, 200]), &mut ctx);
535        assert!(matches!(p.validity(), Ok(Validity::NonNullable)));
536
537        // to nullable u32
538        let p = p
539            .into_array()
540            .cast(DType::Primitive(PType::U32, Nullability::Nullable))
541            .unwrap()
542            .execute::<PrimitiveArray>(&mut ctx)
543            .unwrap();
544        assert_arrays_eq!(
545            p,
546            PrimitiveArray::new(buffer![0u32, 10, 200], Validity::AllValid),
547            &mut ctx
548        );
549        assert!(matches!(p.validity(), Ok(Validity::AllValid)));
550
551        // to non-nullable u8
552        let p = p
553            .into_array()
554            .cast(DType::Primitive(PType::U8, Nullability::NonNullable))
555            .unwrap()
556            .execute::<PrimitiveArray>(&mut ctx)
557            .unwrap();
558        assert_arrays_eq!(p, PrimitiveArray::from_iter([0u8, 10, 200]), &mut ctx);
559        assert!(matches!(p.validity(), Ok(Validity::NonNullable)));
560    }
561
562    #[test]
563    fn cast_u32_f32() {
564        let mut ctx = SESSION.create_execution_ctx();
565        let arr = buffer![0u32, 10, 200].into_array();
566        let u8arr = arr.cast(PType::F32.into()).unwrap();
567        assert_arrays_eq!(
568            u8arr,
569            PrimitiveArray::from_iter([0.0f32, 10., 200.]),
570            &mut ctx
571        );
572    }
573
574    #[test]
575    fn cast_integer_to_decimal_rescales() -> VortexResult<()> {
576        let mut ctx = SESSION.create_execution_ctx();
577        let decimal_dtype = DecimalDType::new(5, 2);
578        let casted = PrimitiveArray::from_iter([42i32, -7])
579            .into_array()
580            .cast(DType::Decimal(decimal_dtype, Nullability::NonNullable))?
581            .execute::<DecimalArray>(&mut ctx)?;
582
583        assert_eq!(
584            casted.dtype(),
585            &DType::Decimal(decimal_dtype, Nullability::NonNullable)
586        );
587        assert_eq!(casted.values_type(), DecimalType::I32);
588        assert_eq!(casted.buffer::<i32>().as_ref(), &[4_200, -700]);
589        Ok(())
590    }
591
592    #[test]
593    fn cast_same_width_signed_integer_to_decimal_reuses_buffer() -> VortexResult<()> {
594        let mut ctx = SESSION.create_execution_ctx();
595        let source = PrimitiveArray::from_iter([42i32, -7]);
596        let source_ptr = source.as_slice::<i32>().as_ptr();
597        let casted = source
598            .into_array()
599            .cast(DType::Decimal(
600                DecimalDType::new(9, 0),
601                Nullability::NonNullable,
602            ))?
603            .execute::<DecimalArray>(&mut ctx)?;
604
605        assert_eq!(casted.buffer::<i32>().as_ptr(), source_ptr);
606        assert_eq!(casted.buffer::<i32>().as_ref(), &[42, -7]);
607        assert_arrays_eq!(
608            &casted,
609            DecimalArray::from_iter([42i32, -7], DecimalDType::new(9, 0)),
610            &mut ctx
611        );
612        Ok(())
613    }
614
615    #[test]
616    fn cast_same_width_signed_integer_to_decimal_reuses_buffer_with_cached_bounds()
617    -> VortexResult<()> {
618        let mut ctx = SESSION.create_execution_ctx();
619        let source = PrimitiveArray::from_iter([42i32, -7]);
620        let source_ptr = source.as_slice::<i32>().as_ptr();
621        let source = source.into_array();
622        source
623            .statistics()
624            .compute_all(&[Stat::Min, Stat::Max], &mut ctx)?;
625        let casted = source
626            .cast(DType::Decimal(
627                DecimalDType::new(9, 0),
628                Nullability::NonNullable,
629            ))?
630            .execute::<DecimalArray>(&mut ctx)?;
631
632        assert_eq!(casted.buffer::<i32>().as_ptr(), source_ptr);
633        assert_arrays_eq!(
634            &casted,
635            DecimalArray::from_iter([42i32, -7], DecimalDType::new(9, 0)),
636            &mut ctx
637        );
638        Ok(())
639    }
640
641    #[test]
642    fn cast_same_width_signed_integer_to_decimal_ignores_out_of_range_nulls() -> VortexResult<()> {
643        let mut ctx = SESSION.create_execution_ctx();
644        let source = PrimitiveArray::new(buffer![i32::MAX, 42], Validity::from_iter([false, true]));
645        let source_ptr = source.as_slice::<i32>().as_ptr();
646        let casted = source
647            .into_array()
648            .cast(DType::Decimal(
649                DecimalDType::new(9, 0),
650                Nullability::Nullable,
651            ))?
652            .execute::<DecimalArray>(&mut ctx)?;
653
654        assert_eq!(casted.buffer::<i32>().as_ptr(), source_ptr);
655        assert_eq!(
656            casted.validity()?.execute_mask(casted.len(), &mut ctx)?,
657            Mask::from(BitBuffer::from(vec![false, true]))
658        );
659        assert_arrays_eq!(
660            &casted,
661            DecimalArray::from_option_iter([None, Some(42i32)], DecimalDType::new(9, 0)),
662            &mut ctx
663        );
664        Ok(())
665    }
666
667    #[test]
668    fn cast_same_width_signed_integer_to_decimal_checks_precision() -> VortexResult<()> {
669        let mut ctx = SESSION.create_execution_ctx();
670        let casted = PrimitiveArray::from_iter([i32::MAX])
671            .into_array()
672            .cast(DType::Decimal(
673                DecimalDType::new(9, 0),
674                Nullability::NonNullable,
675            ))?;
676
677        let error = casted.execute::<DecimalArray>(&mut ctx).unwrap_err();
678        assert!(error.to_string().contains("does not fit in precision"));
679        Ok(())
680    }
681
682    #[test]
683    fn cast_u64_to_decimal() -> VortexResult<()> {
684        let mut ctx = SESSION.create_execution_ctx();
685        let decimal_dtype = DecimalDType::new(20, 0);
686        let casted = PrimitiveArray::from_iter([u64::MAX])
687            .into_array()
688            .cast(DType::Decimal(decimal_dtype, Nullability::NonNullable))?
689            .execute::<DecimalArray>(&mut ctx)?;
690
691        assert_eq!(
692            casted.dtype(),
693            &DType::Decimal(decimal_dtype, Nullability::NonNullable)
694        );
695        assert_eq!(casted.values_type(), DecimalType::I128);
696        assert_eq!(casted.buffer::<i128>().as_ref(), &[i128::from(u64::MAX)]);
697        Ok(())
698    }
699
700    #[test]
701    fn cast_integer_to_decimal_reports_scale_up_overflow() -> VortexResult<()> {
702        let mut ctx = SESSION.create_execution_ctx();
703        let dtype = DType::Decimal(DecimalDType::new(38, 20), Nullability::NonNullable);
704        let casted = PrimitiveArray::from_iter([u64::MAX])
705            .into_array()
706            .cast(dtype)?;
707        let actual = casted.execute::<DecimalArray>(&mut ctx).unwrap_err();
708
709        assert!(
710            actual
711                .to_string()
712                .contains("does not fit in precision of decimal(38,20)")
713        );
714        Ok(())
715    }
716
717    #[test]
718    fn cast_u8_to_negative_scale_decimal() -> VortexResult<()> {
719        let mut ctx = SESSION.create_execution_ctx();
720        let decimal_dtype = DecimalDType::new(2, -2);
721        let casted = PrimitiveArray::from_iter([200u8])
722            .into_array()
723            .cast(DType::Decimal(decimal_dtype, Nullability::NonNullable))?
724            .execute::<DecimalArray>(&mut ctx)?;
725
726        assert_eq!(
727            casted.dtype(),
728            &DType::Decimal(decimal_dtype, Nullability::NonNullable)
729        );
730        assert_eq!(casted.values_type(), DecimalType::I8);
731        assert_eq!(casted.buffer::<i8>().as_ref(), &[2]);
732        Ok(())
733    }
734
735    #[test]
736    fn cast_u64_to_negative_scale_decimal() -> VortexResult<()> {
737        let mut ctx = SESSION.create_execution_ctx();
738        let decimal_dtype = DecimalDType::new(1, -19);
739        let casted = PrimitiveArray::from_iter([10_000_000_000_000_000_000u64])
740            .into_array()
741            .cast(DType::Decimal(decimal_dtype, Nullability::NonNullable))?
742            .execute::<DecimalArray>(&mut ctx)?;
743
744        assert_eq!(
745            casted.dtype(),
746            &DType::Decimal(decimal_dtype, Nullability::NonNullable)
747        );
748        assert_eq!(casted.values_type(), DecimalType::I8);
749        assert_eq!(casted.buffer::<i8>().as_ref(), &[1]);
750        Ok(())
751    }
752
753    #[test]
754    fn cast_integer_to_i256_decimal() -> VortexResult<()> {
755        let mut ctx = SESSION.create_execution_ctx();
756        let decimal_dtype = DecimalDType::new(39, 2);
757        let casted = PrimitiveArray::from_iter([42i64])
758            .into_array()
759            .cast(DType::Decimal(decimal_dtype, Nullability::NonNullable))?
760            .execute::<DecimalArray>(&mut ctx)?;
761
762        assert_eq!(
763            casted.dtype(),
764            &DType::Decimal(decimal_dtype, Nullability::NonNullable)
765        );
766        assert_eq!(casted.values_type(), DecimalType::I256);
767        assert_eq!(casted.buffer::<i256>().as_ref(), &[i256::from_i128(4_200)]);
768        Ok(())
769    }
770
771    #[test]
772    fn cast_all_null_integer_to_decimal() -> VortexResult<()> {
773        let mut ctx = SESSION.create_execution_ctx();
774        let decimal_dtype = DecimalDType::new(39, 2);
775        let casted = PrimitiveArray::new(buffer![i64::MAX, i64::MIN], Validity::AllInvalid)
776            .into_array()
777            .cast(DType::Decimal(decimal_dtype, Nullability::Nullable))?
778            .execute::<DecimalArray>(&mut ctx)?;
779
780        assert!(matches!(casted.validity(), Ok(Validity::AllInvalid)));
781        assert_arrays_eq!(
782            &casted,
783            DecimalArray::from_option_iter([None::<i256>; 2], decimal_dtype),
784            &mut ctx
785        );
786        Ok(())
787    }
788
789    #[test]
790    fn cast_integer_to_negative_scale_decimal_requires_exact_rescale() -> VortexResult<()> {
791        let mut ctx = SESSION.create_execution_ctx();
792        let decimal_dtype = DecimalDType::new(3, -2);
793        let casted = PrimitiveArray::from_iter([1_200i32, -500])
794            .into_array()
795            .cast(DType::Decimal(decimal_dtype, Nullability::NonNullable))?
796            .execute::<DecimalArray>(&mut ctx)?;
797
798        assert_eq!(
799            casted.dtype(),
800            &DType::Decimal(decimal_dtype, Nullability::NonNullable)
801        );
802        assert_eq!(casted.buffer::<i16>().as_ref(), &[12, -5]);
803
804        let error = PrimitiveArray::from_iter([42i32])
805            .into_array()
806            .cast(DType::Decimal(decimal_dtype, Nullability::NonNullable))?
807            .execute::<DecimalArray>(&mut ctx)
808            .unwrap_err();
809        assert!(error.to_string().contains("would lose precision"));
810        Ok(())
811    }
812
813    #[rstest]
814    fn cast_integer_to_negative_scale_decimal_every_width(
815        #[values(
816            PType::U8, PType::U16, PType::U32, PType::U64, PType::I8, PType::I16, PType::I32,
817            PType::I64
818        )]
819        ptype: PType,
820        #[values(2, 4, 9, 18, 38, 76)] precision: u8,
821    ) -> VortexResult<()> {
822        let mut ctx = SESSION.create_execution_ctx();
823        let decimal_dtype = DecimalDType::new(precision, -1);
824        let casted = PrimitiveArray::from_iter([100u8, 30])
825            .into_array()
826            .cast(DType::Primitive(ptype, Nullability::NonNullable))?
827            .cast(DType::Decimal(decimal_dtype, Nullability::NonNullable))?
828            .execute::<DecimalArray>(&mut ctx)?;
829
830        assert_eq!(casted.values_type(), decimal_dtype.canonical_values_type());
831        match_each_decimal_value_type!(casted.values_type(), |T| {
832            let expected = [10i8, 3].map(<T as crate::dtype::BigCast>::from);
833            let actual = casted
834                .buffer::<T>()
835                .iter()
836                .map(|&value| Some(value))
837                .collect::<Vec<_>>();
838            assert_eq!(actual, expected);
839        });
840        Ok(())
841    }
842
843    #[test]
844    fn cast_zero_to_large_negative_scale_decimal() -> VortexResult<()> {
845        let mut ctx = SESSION.create_execution_ctx();
846        let decimal_dtype = DecimalDType::new(3, -128);
847        let casted = PrimitiveArray::from_iter([0i32])
848            .into_array()
849            .cast(DType::Decimal(decimal_dtype, Nullability::NonNullable))?
850            .execute::<DecimalArray>(&mut ctx)?;
851
852        assert_eq!(
853            casted.dtype(),
854            &DType::Decimal(decimal_dtype, Nullability::NonNullable)
855        );
856        assert_eq!(casted.buffer::<i16>().as_ref(), &[0]);
857        Ok(())
858    }
859
860    #[test]
861    fn cast_integer_to_decimal_ignores_out_of_range_null_lanes() -> VortexResult<()> {
862        let mut ctx = SESSION.create_execution_ctx();
863        let decimal_dtype = DecimalDType::new(3, 1);
864        let casted = PrimitiveArray::new(buffer![999i32, 42], Validity::from_iter([false, true]))
865            .into_array()
866            .cast(DType::Decimal(decimal_dtype, Nullability::Nullable))?
867            .execute::<DecimalArray>(&mut ctx)?;
868
869        assert_eq!(
870            casted.dtype(),
871            &DType::Decimal(decimal_dtype, Nullability::Nullable)
872        );
873        assert_eq!(casted.buffer::<i16>().as_ref()[1], 420);
874        assert_eq!(
875            casted.validity()?.execute_mask(casted.len(), &mut ctx)?,
876            Mask::from(BitBuffer::from(vec![false, true]))
877        );
878        Ok(())
879    }
880
881    /// Scaling up into storage of the source's width multiplies and range-checks in one pass.
882    #[test]
883    fn cast_same_width_integer_to_scaled_decimal() -> VortexResult<()> {
884        let mut ctx = SESSION.create_execution_ctx();
885        let decimal_dtype = DecimalDType::new(9, 2);
886
887        let casted = PrimitiveArray::new(
888            buffer![i32::MAX, 42, -9_999_999],
889            Validity::from_iter([false, true, true]),
890        )
891        .into_array()
892        .cast(DType::Decimal(decimal_dtype, Nullability::Nullable))?;
893        assert_arrays_eq!(
894            casted,
895            DecimalArray::from_option_iter(
896                [None, Some(4_200i32), Some(-999_999_900)],
897                decimal_dtype
898            ),
899            &mut ctx
900        );
901
902        let casted = PrimitiveArray::from_iter([10_000_000u32, 3])
903            .into_array()
904            .cast(DType::Decimal(decimal_dtype, Nullability::NonNullable))?;
905        let error = casted.execute::<DecimalArray>(&mut ctx).unwrap_err();
906        assert!(error.to_string().contains("does not fit in precision"));
907        Ok(())
908    }
909
910    /// A buffer that only records byte alignment still casts when its pointer is aligned.
911    #[rstest]
912    #[case::unscaled(DecimalDType::new(9, 0), [1, 2])]
913    #[case::scaled(DecimalDType::new(9, 2), [100, 200])]
914    fn cast_integer_with_unrecorded_alignment_to_same_width_decimal(
915        #[case] decimal_dtype: DecimalDType,
916        #[case] expected: [i32; 2],
917    ) -> VortexResult<()> {
918        let mut ctx = SESSION.create_execution_ctx();
919        let bytes = buffer![1u32, 2]
920            .into_byte_buffer()
921            .aligned(Alignment::none());
922        let source = PrimitiveArray::from_buffer_handle(
923            BufferHandle::new_host(bytes),
924            PType::U32,
925            Validity::NonNullable,
926        );
927
928        let casted = source
929            .into_array()
930            .cast(DType::Decimal(decimal_dtype, Nullability::NonNullable))?;
931        assert_arrays_eq!(
932            casted,
933            DecimalArray::from_iter(expected, decimal_dtype),
934            &mut ctx
935        );
936        Ok(())
937    }
938
939    #[test]
940    fn cast_integer_to_decimal_checks_precision() -> VortexResult<()> {
941        let mut ctx = SESSION.create_execution_ctx();
942        let casted = PrimitiveArray::from_iter([100i32])
943            .into_array()
944            .cast(DType::Decimal(
945                DecimalDType::new(2, 1),
946                Nullability::NonNullable,
947            ))?;
948
949        let error = casted.execute::<DecimalArray>(&mut ctx).unwrap_err();
950        assert!(error.to_string().contains("does not fit in precision"));
951        Ok(())
952    }
953
954    #[test]
955    fn cast_floating_primitive_to_decimal_fails() -> VortexResult<()> {
956        let mut ctx = SESSION.create_execution_ctx();
957        let casted = PrimitiveArray::from_iter([1.0f64])
958            .into_array()
959            .cast(DType::Decimal(
960                DecimalDType::new(3, 1),
961                Nullability::NonNullable,
962            ))?;
963
964        let error = casted.execute::<DecimalArray>(&mut ctx).unwrap_err();
965        assert!(
966            error
967                .to_string()
968                .contains("Cannot cast floating primitive f64 to decimal decimal(3,1)")
969        );
970        Ok(())
971    }
972
973    #[test]
974    fn cast_i32_u32() {
975        let arr = buffer![-1i32].into_array();
976        let error = arr
977            .cast(PType::U32.into())
978            .and_then(|a| {
979                a.execute::<Canonical>(&mut SESSION.create_execution_ctx())
980                    .map(|c| c.into_array())
981            })
982            .unwrap_err();
983        assert!(error.to_string().contains("values exceed target range"));
984    }
985
986    #[test]
987    fn cast_array_with_nulls_to_nonnullable() {
988        let arr = PrimitiveArray::from_option_iter([Some(-1i32), None, Some(10)]);
989        let err = arr
990            .into_array()
991            .cast(PType::I32.into())
992            .and_then(|a| {
993                a.execute::<Canonical>(&mut SESSION.create_execution_ctx())
994                    .map(|c| c.into_array())
995            })
996            .unwrap_err();
997
998        assert!(
999            err.to_string()
1000                .contains("Cannot cast array with invalid values to non-nullable type.")
1001        );
1002    }
1003
1004    #[test]
1005    fn cast_with_invalid_nulls() {
1006        let mut ctx = SESSION.create_execution_ctx();
1007        let arr = PrimitiveArray::new(
1008            buffer![-1i32, 0, 10],
1009            Validity::from_iter([false, true, true]),
1010        );
1011        let p = arr
1012            .into_array()
1013            .cast(DType::Primitive(PType::U32, Nullability::Nullable))
1014            .unwrap();
1015        assert_arrays_eq!(
1016            p,
1017            PrimitiveArray::from_option_iter([None, Some(0u32), Some(10)]),
1018            &mut ctx
1019        );
1020        assert_eq!(
1021            p.validity()
1022                .unwrap()
1023                .execute_mask(p.len(), &mut SESSION.create_execution_ctx())
1024                .unwrap(),
1025            Mask::from(BitBuffer::from(vec![false, true, true]))
1026        );
1027    }
1028
1029    /// Same-width integer cast where all values fit: should reinterpret the
1030    /// buffer without allocation (pointer identity).
1031    #[test]
1032    fn cast_same_width_int_reinterprets_buffer() -> VortexResult<()> {
1033        let mut ctx = SESSION.create_execution_ctx();
1034        let src = PrimitiveArray::from_iter([0u32, 10, 100]);
1035        let src_ptr = src.as_slice::<u32>().as_ptr();
1036
1037        let dst = src
1038            .into_array()
1039            .cast(PType::I32.into())?
1040            .execute::<PrimitiveArray>(&mut ctx)?;
1041        let dst_ptr = dst.as_slice::<i32>().as_ptr();
1042
1043        // Zero-copy: the data pointer should be identical.
1044        assert_eq!(src_ptr as usize, dst_ptr as usize);
1045        assert_arrays_eq!(dst, PrimitiveArray::from_iter([0i32, 10, 100]), &mut ctx);
1046        Ok(())
1047    }
1048
1049    /// Same-width integer cast where values don't fit: should fall through
1050    /// to the allocating path and produce an error.
1051    #[test]
1052    fn cast_same_width_int_out_of_range_errors() {
1053        let arr = buffer![u32::MAX].into_array();
1054        let err = arr
1055            .cast(PType::I32.into())
1056            .and_then(|a| {
1057                a.execute::<Canonical>(&mut SESSION.create_execution_ctx())
1058                    .map(|c| c.into_array())
1059            })
1060            .unwrap_err();
1061        assert!(
1062            err.to_string().contains("values exceed target range"),
1063            "{err}"
1064        );
1065    }
1066
1067    /// All-null array cast between same-width types should succeed without
1068    /// touching the buffer contents.
1069    #[test]
1070    fn cast_same_width_all_null() -> VortexResult<()> {
1071        let mut ctx = SESSION.create_execution_ctx();
1072        let arr = PrimitiveArray::new(buffer![0xFFu8, 0xFF], Validity::AllInvalid);
1073        let casted = arr
1074            .into_array()
1075            .cast(DType::Primitive(PType::I8, Nullability::Nullable))?
1076            .execute::<PrimitiveArray>(&mut ctx)?;
1077        assert_arrays_eq!(
1078            &casted,
1079            PrimitiveArray::from_option_iter([None::<i8>; 2]),
1080            &mut ctx
1081        );
1082        assert!(matches!(casted.validity(), Ok(Validity::AllInvalid)));
1083        Ok(())
1084    }
1085
1086    /// Same-width integer cast with nullable values: out-of-range nulls should
1087    /// not prevent the cast from succeeding.
1088    #[test]
1089    fn cast_same_width_int_nullable_with_out_of_range_nulls() -> VortexResult<()> {
1090        let mut ctx = SESSION.create_execution_ctx();
1091        // The null position holds u32::MAX which doesn't fit in i32, but it's
1092        // masked as invalid so the cast should still succeed via reinterpret.
1093        let arr = PrimitiveArray::new(
1094            buffer![u32::MAX, 0u32, 42u32],
1095            Validity::from_iter([false, true, true]),
1096        );
1097        let casted = arr
1098            .into_array()
1099            .cast(DType::Primitive(PType::I32, Nullability::Nullable))?;
1100        assert_arrays_eq!(
1101            casted,
1102            PrimitiveArray::from_option_iter([None, Some(0i32), Some(42)]),
1103            &mut ctx
1104        );
1105        Ok(())
1106    }
1107
1108    #[test]
1109    fn cast_u32_to_u8_with_out_of_range_nulls() -> VortexResult<()> {
1110        let mut ctx = SESSION.create_execution_ctx();
1111        let arr = PrimitiveArray::new(
1112            buffer![1000u32, 10u32, 42u32],
1113            Validity::from_iter([false, true, true]),
1114        );
1115        let casted = arr
1116            .into_array()
1117            .cast(DType::Primitive(PType::U8, Nullability::Nullable))?;
1118        assert_arrays_eq!(
1119            casted,
1120            PrimitiveArray::from_option_iter([None, Some(10u8), Some(42)]),
1121            &mut ctx
1122        );
1123        Ok(())
1124    }
1125
1126    #[rstest]
1127    #[case(buffer![0u8, 1, 2, 3, 255].into_array())]
1128    #[case(buffer![0u16, 100, 1000, 65535].into_array())]
1129    #[case(buffer![0u32, 100, 1000, 1000000].into_array())]
1130    #[case(buffer![0u64, 100, 1000, 1000000000].into_array())]
1131    #[case(buffer![-128i8, -1, 0, 1, 127].into_array())]
1132    #[case(buffer![-1000i16, -1, 0, 1, 1000].into_array())]
1133    #[case(buffer![-1000000i32, -1, 0, 1, 1000000].into_array())]
1134    #[case(buffer![-1000000000i64, -1, 0, 1, 1000000000].into_array())]
1135    #[case(buffer![0.0f32, 1.5, -2.5, 100.0, 1e6].into_array())]
1136    #[case(buffer![f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 0.0f32].into_array())]
1137    #[case(buffer![0.0f64, 1.5, -2.5, 100.0, 1e12].into_array())]
1138    #[case(buffer![f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 0.0f64].into_array())]
1139    #[case(PrimitiveArray::from_option_iter([Some(1u8), None, Some(255), Some(0), None]).into_array())]
1140    #[case(PrimitiveArray::from_option_iter([Some(1i32), None, Some(-100), Some(0), None]).into_array())]
1141    #[case(buffer![42u32].into_array())]
1142    fn test_cast_primitive_conformance(#[case] array: ArrayRef) {
1143        test_cast_conformance(&array, &mut SESSION.create_execution_ctx());
1144    }
1145
1146    /// Floats fit an integer when they truncate into its range, matching `NumCast`.
1147    #[rstest]
1148    #[case::u8_truncates_up_to_zero(-0.9, PType::U8, true)]
1149    #[case::u8_below_range(-1.0, PType::U8, false)]
1150    #[case::u8_truncates_down_to_max(255.9, PType::U8, true)]
1151    #[case::u8_above_range(256.0, PType::U8, false)]
1152    #[case::i8_truncates_up_to_min(-128.9, PType::I8, true)]
1153    #[case::i8_below_range(-129.0, PType::I8, false)]
1154    #[case::i32_max(2_147_483_647.0, PType::I32, true)]
1155    #[case::i32_above_range(2_147_483_648.0, PType::I32, false)]
1156    #[case::i64_min(-9_223_372_036_854_775_808.0, PType::I64, true)]
1157    #[case::i64_below_range(-9_223_372_036_854_777_856.0, PType::I64, false)]
1158    #[case::i64_above_range(9_223_372_036_854_775_808.0, PType::I64, false)]
1159    #[case::u64_above_range(18_446_744_073_709_551_616.0, PType::U64, false)]
1160    #[case::nan(f64::NAN, PType::I32, false)]
1161    #[case::infinity(f64::INFINITY, PType::I64, false)]
1162    fn cast_float_to_int_range(
1163        #[case] value: f64,
1164        #[case] ptype: PType,
1165        #[case] fits: bool,
1166    ) -> VortexResult<()> {
1167        let mut ctx = SESSION.create_execution_ctx();
1168        let result = buffer![0.0f64, value]
1169            .into_array()
1170            .cast(ptype.into())?
1171            .execute::<PrimitiveArray>(&mut ctx);
1172        assert_eq!(result.is_ok(), fits, "{value} as {ptype}");
1173        Ok(())
1174    }
1175
1176    /// Integer-to-integer casts check the source value against the target range.
1177    #[rstest]
1178    #[case::i64_to_u8_max(255, PType::U8, true)]
1179    #[case::i64_to_u8_above(256, PType::U8, false)]
1180    #[case::i64_to_u8_negative(-1, PType::U8, false)]
1181    #[case::i64_to_i16_min(-32_768, PType::I16, true)]
1182    #[case::i64_to_i16_below(-32_769, PType::I16, false)]
1183    #[case::i64_to_u32_max(4_294_967_295, PType::U32, true)]
1184    #[case::i64_to_u64_negative(-1, PType::U64, false)]
1185    fn cast_int_to_int_range(
1186        #[case] value: i64,
1187        #[case] ptype: PType,
1188        #[case] fits: bool,
1189    ) -> VortexResult<()> {
1190        let mut ctx = SESSION.create_execution_ctx();
1191        let result = buffer![0i64, value]
1192            .into_array()
1193            .cast(ptype.into())?
1194            .execute::<PrimitiveArray>(&mut ctx);
1195        assert_eq!(result.is_ok(), fits, "{value} as {ptype}");
1196        Ok(())
1197    }
1198
1199    /// Cached min/max skip NaN, so they must not prove that a float array fits an integer type.
1200    #[test]
1201    fn cast_float_with_nan_and_cached_min_max_to_int_errors() -> VortexResult<()> {
1202        let mut ctx = SESSION.create_execution_ctx();
1203        let arr = buffer![1.0f64, f64::NAN, 3.0].into_array();
1204        arr.statistics()
1205            .compute_all(&[Stat::Min, Stat::Max], &mut ctx)?;
1206        let result = arr
1207            .cast(PType::I32.into())?
1208            .execute::<PrimitiveArray>(&mut ctx);
1209        assert!(result.is_err());
1210        Ok(())
1211    }
1212
1213    /// Null lanes may hold NaN or out-of-range floats without failing the cast.
1214    #[test]
1215    fn cast_float_to_int_ignores_null_lanes() -> VortexResult<()> {
1216        let mut ctx = SESSION.create_execution_ctx();
1217        let arr = PrimitiveArray::new(
1218            buffer![f32::NAN, 1.5, 1e10, -2.5],
1219            Validity::from_iter([false, true, false, true]),
1220        );
1221        let casted = arr
1222            .into_array()
1223            .cast(DType::Primitive(PType::I8, Nullability::Nullable))?;
1224        assert_arrays_eq!(
1225            casted,
1226            PrimitiveArray::from_option_iter([None, Some(1i8), None, Some(-2)]),
1227            &mut ctx
1228        );
1229        Ok(())
1230    }
1231
1232    /// Every pair of primitive types converts each value like `as`.
1233    #[test]
1234    fn cast_every_ptype_pair() -> VortexResult<()> {
1235        let mut ctx = SESSION.create_execution_ctx();
1236        let ptypes = [
1237            PType::U8,
1238            PType::U16,
1239            PType::U32,
1240            PType::U64,
1241            PType::I8,
1242            PType::I16,
1243            PType::I32,
1244            PType::I64,
1245            PType::F16,
1246            PType::F32,
1247            PType::F64,
1248        ];
1249        // Values that every type holds exactly, including a negative value for signed types.
1250        let values = [0i8, 1, 7, 100, 127];
1251        for from in ptypes {
1252            for to in ptypes {
1253                let signed = |p: PType| p.is_signed_int() || p.is_float();
1254                let source: Vec<i8> = if signed(from) && signed(to) {
1255                    values.iter().map(|v| -v).chain(values).collect()
1256                } else {
1257                    values.to_vec()
1258                };
1259                let make = |ptype: PType| {
1260                    match_each_native_ptype!(ptype, |T| {
1261                        PrimitiveArray::from_iter(source.iter().map(|&v| {
1262                            <T as num_traits::NumCast>::from(v)
1263                                .vortex_expect("every type holds the value")
1264                        }))
1265                        .into_array()
1266                    })
1267                };
1268                assert_arrays_eq!(make(from).cast(to.into())?, make(to), &mut ctx);
1269            }
1270        }
1271        Ok(())
1272    }
1273
1274    /// Casts that convert values return a constant null for all-null input instead of
1275    /// converting values nobody can see; casts that reinterpret the buffer keep it.
1276    #[rstest]
1277    #[case::checked_all_false_mask(
1278        PrimitiveArray::new(
1279            buffer![1000i32, -1],
1280            Validity::Array(BoolArray::from_iter([false, false]).into_array()),
1281        ),
1282        PType::U8,
1283        true
1284    )]
1285    #[case::checked_all_invalid(
1286        PrimitiveArray::new(buffer![1000i32, -1], Validity::AllInvalid),
1287        PType::U8,
1288        true
1289    )]
1290    #[case::unchecked_all_invalid(
1291        PrimitiveArray::new(buffer![1i32, 2], Validity::AllInvalid),
1292        PType::F64,
1293        true
1294    )]
1295    #[case::reinterpret_all_invalid(
1296        PrimitiveArray::new(buffer![1i32, 2], Validity::AllInvalid),
1297        PType::U32,
1298        false
1299    )]
1300    fn cast_all_null(
1301        #[case] array: PrimitiveArray,
1302        #[case] ptype: PType,
1303        #[case] constant: bool,
1304    ) -> VortexResult<()> {
1305        let mut ctx = SESSION.create_execution_ctx();
1306        let target = DType::Primitive(ptype, Nullability::Nullable);
1307        let casted = <Primitive as CastKernel>::cast(array.as_view(), &target, &mut ctx)?
1308            .vortex_expect("primitive casts to primitives are handled");
1309        assert_eq!(casted.is::<Constant>(), constant);
1310        assert_eq!(casted.dtype(), &target);
1311        assert_eq!(casted.invalid_count(&mut ctx)?, array.len());
1312        Ok(())
1313    }
1314}