Skip to content

Commit

Permalink
Add PrimitiveArray::reinterpret_cast (#2785) (#2786)
Browse files Browse the repository at this point in the history
  • Loading branch information
tustvold committed Sep 27, 2022
1 parent e97bd6f commit 322d351
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions arrow-array/src/array/primitive_array.rs
Expand Up @@ -324,6 +324,35 @@ impl<T: ArrowPrimitiveType> PrimitiveArray<T> {
indexes.map(|opt_index| opt_index.map(|index| self.value_unchecked(index)))
}

/// Reinterprets this array's contents as a different data type without copying
///
/// This can be used to efficiently convert between primitive arrays with the
/// same underlying representation
///
/// Note: this will not modify the underlying values, and therefore may change
/// the semantic values of the array, e.g. 100 milliseconds in a [`TimestampNanosecondArray`]
/// will become 100 seconds in a [`TimestampSecondArray`].
///
/// For casts that preserve the semantic value, check out the [compute kernels]
///
/// [compute kernels](https://docs.rs/arrow/latest/arrow/compute/kernels/cast/index.html)
///
/// ```
/// # use arrow_array::{Int64Array, TimestampNanosecondArray};
/// let a = Int64Array::from_iter_values([1, 2, 3, 4]);
/// let b: TimestampNanosecondArray = a.reinterpret_cast();
/// ```
pub fn reinterpret_cast<K>(&self) -> PrimitiveArray<K>
where
K: ArrowPrimitiveType<Native = T::Native>,
{
let d = self.data.clone().into_builder().data_type(K::DATA_TYPE);

// SAFETY:
// Native type is the same
PrimitiveArray::from(unsafe { d.build_unchecked() })
}

/// Applies an unary and infallible function to a primitive array.
/// This is the fastest way to perform an operation on a primitive array when
/// the benefits of a vectorized operation outweigh the cost of branching nulls and non-nulls.
Expand Down

0 comments on commit 322d351

Please sign in to comment.