scirs2_core/arrow_compat/traits.rs
1//! Conversion traits for Arrow ↔ ndarray interoperability
2//!
3//! Defines the core traits that enable type-safe conversions between
4//! Rust primitive types and Arrow array types.
5
6use super::error::ArrowResult;
7use arrow::array::ArrayRef;
8use arrow::datatypes::DataType;
9use ndarray::Array1;
10
11/// Trait for types that can be converted to Arrow arrays
12///
13/// Implemented for primitive numeric types (f32, f64, i32, i64, etc.),
14/// boolean, and String types.
15pub trait ToArrowArray: Sized {
16 /// Convert a slice of data to an Arrow array
17 fn to_arrow_array(data: &[Self]) -> ArrowResult<ArrayRef>;
18
19 /// Get the Arrow `DataType` for this Rust type
20 fn arrow_data_type() -> DataType;
21}
22
23/// Trait for types that can be extracted from Arrow arrays
24///
25/// Provides both fallible extraction (which returns an error if the
26/// Arrow array contains nulls or has wrong type) and nullable extraction
27/// (which returns `Option<T>` for nullable columns).
28pub trait FromArrowArray: Sized {
29 /// Extract data from an Arrow array into an `Array1`
30 ///
31 /// Returns an error if the array contains null values.
32 /// Use [`from_arrow_array_nullable`](FromArrowArray::from_arrow_array_nullable)
33 /// for arrays that may contain nulls.
34 fn from_arrow_array(array: &ArrayRef) -> ArrowResult<Array1<Self>>;
35
36 /// Extract data from a nullable Arrow array into an `Array1<Option<Self>>`
37 fn from_arrow_array_nullable(array: &ArrayRef) -> ArrowResult<Array1<Option<Self>>>;
38}
39
40/// Trait for types that support zero-copy conversion from Arrow buffers
41///
42/// This is only possible when the memory layout of the Rust type exactly
43/// matches the Arrow buffer layout (e.g., contiguous f64 values).
44pub trait ZeroCopyFromArrow: Sized {
45 /// Attempt a zero-copy view of the Arrow array data.
46 ///
47 /// Returns `None` if zero-copy is not possible (e.g., due to null
48 /// bitmap, non-contiguous data, or type mismatch).
49 fn try_zero_copy_view(array: &ArrayRef) -> ArrowResult<Option<ndarray::ArrayView1<'_, Self>>>;
50}