Skip to main content

FieldArray

Struct FieldArray 

Source
pub struct FieldArray {
    pub field: Arc<Field>,
    pub array: Array,
    pub null_count: usize,
}
Expand description

§FieldArray

Named and typed data column with associated array values.

§Role

  • Combines a Field with an immutable Array instance.
  • FieldArray integrates naturally into a Table, where immutability enforces row-length guarantees. It can also serve as a self-documenting array and is required when sending Minarrow data over FFI to Apache Arrow. In such cases, it’s worth ensuring the correct logical Datetime Arrow type is built when constructing the Field, as this determines the Arrow type on the receiving side.

§Examples

use minarrow::{Array, Field, FieldArray, MaskedArray};
use minarrow::ffi::arrow_dtype::ArrowType;
use minarrow::structs::variants::integer::IntegerArray;

// Build a typed array
let mut ints = IntegerArray::<i32>::default();
ints.push(1);
ints.push(2);
let arr = Array::from_int32(ints);

// Construct with a Field and Array
let field = Field::new("id", ArrowType::Int32, false, None);
let fa = FieldArray::new(field, arr);

assert_eq!(fa.field.name, "id");
assert_eq!(fa.arrow_type(), ArrowType::Int32);
assert_eq!(fa.len(), 2);

// Take an owned slice [offset..offset+len)
let sub = fa.slice_clone(0, 1);
assert_eq!(sub.len(), 1);

The fa_* macros are a concise construction shorthand:

use minarrow::{fa_i32, fa_i32_opt, fa_str32};
use minarrow::ffi::arrow_dtype::ArrowType;

// From literal values - type and nullability inferred
let fa = fa_i32!("id", 1, 2);
assert_eq!(fa.field.name, "id");
assert_eq!(fa.arrow_type(), ArrowType::Int32);
assert_eq!(fa.len(), 2);

// Nullable variant with Option values
let fa = fa_i32_opt!("score", Some(10i32), None::<i32>, Some(30));
assert_eq!(fa.len(), 3);
assert!(fa.field.nullable);
assert_eq!(fa.null_count(), 1);

// String columns
let names = fa_str32!("name", "alice", "bob");
assert_eq!(names.field.name, "name");
assert_eq!(names.len(), 2);

Fields§

§field: Arc<Field>

Array metadata

§array: Array

The array’s inner payload is wrapped in Arc for immutability so it can safely share across threads. When part of a Table (or higher-dimensional structure), immutability also upholds shape constraints.

§null_count: usize

Null count for the immutable array to support skipping null-mask operations when it’s 0, and/or related strategies.

Implementations§

Source§

impl FieldArray

Source

pub fn new(field: Field, array: Array) -> FieldArray

Constructs a new FieldArray from an existing Field and Array.

Examples found in repository?
examples/pycapsule_exchange.rs (lines 166-169)
149fn example_2_export_table_stream(py: Python<'_>) -> PyResult<()> {
150    println!("Example 2: Export MinArrow table -> PyArrow via __arrow_c_stream__");
151    println!("------------------------------------------------------------------");
152
153    let mut ids = IntegerArray::<i32>::default();
154    ids.push(1);
155    ids.push(2);
156    ids.push(3);
157
158    let mut scores = FloatArray::<f64>::default();
159    scores.push(9.5);
160    scores.push(8.3);
161    scores.push(7.1);
162
163    let table = Table::new(
164        "results".to_string(),
165        Some(vec![
166            FieldArray::new(
167                Field::new("id", ArrowType::Int32, false, None),
168                Array::from_int32(ids),
169            ),
170            FieldArray::new(
171                Field::new("score", ArrowType::Float64, false, None),
172                Array::from_float64(scores),
173            ),
174        ]),
175    );
176    println!("  Created MinArrow table: 3 rows x 2 columns (id, score)");
177
178    // Export as a stream capsule and extract the raw pointer for PyArrow
179    let stream_capsule = to_py::table_to_stream_capsule(&table, py)?;
180    let stream_ptr = unsafe {
181        pyo3::ffi::PyCapsule_GetPointer(
182            stream_capsule.as_ptr(),
183            c"arrow_array_stream".as_ptr(),
184        )
185    } as usize;
186
187    let pyarrow = py.import("pyarrow")?;
188    let reader = pyarrow
189        .getattr("RecordBatchReader")?
190        .call_method1("_import_from_c", (stream_ptr,))?;
191    let pa_table = reader.call_method0("read_all")?;
192
193    let num_rows: usize = pa_table.getattr("num_rows")?.extract()?;
194    let schema_repr: String = pa_table.getattr("schema")?.call_method0("__repr__")?.extract()?;
195    println!("  PyArrow received: {} rows", num_rows);
196    println!("  Schema: {}", schema_repr.lines().next().unwrap_or(""));
197    println!("  Done.\n");
198    Ok(())
199}
Source

pub fn new_arc(field: Arc<Field>, array: Array) -> FieldArray

Constructs a new FieldArray from an existing Arc<Field> and Array.

Source

pub fn from_arr<N, A>(name: N, arr: A) -> FieldArray
where N: Into<String>, A: Into<Array>,

Constructs a new FieldArray from a name and any supported typed array, automatically wrapping as Array and inferring type and nullability.

Source

pub fn from_parts<T>( field_name: T, dtype: ArrowType, nullable: Option<bool>, metadata: Option<BTreeMap<String, String>>, array: Array, ) -> FieldArray
where T: Into<String>,

Constructs a new FieldArray from raw field components and an Array.

Source

pub fn len(&self) -> usize

Source

pub fn is_empty(&self) -> bool

Source

pub fn arrow_type(&self) -> ArrowType

Source

pub fn tz(&self, tz: &str) -> Result<FieldArray, MinarrowError>

Returns a new FieldArray with updated timezone metadata.

The underlying timestamp data (always UTC) remains unchanged. Only the timezone metadata in the Field’s ArrowType is updated for interpretation/display purposes.

§Arguments
  • tz - Timezone string in Arrow format (IANA like “America/New_York” or offset like “+05:00”)
§Errors

Returns an error if the array is not a Timestamp type.

Source

pub fn utc(&self) -> Result<FieldArray, MinarrowError>

Returns a new FieldArray with timezone metadata set to “UTC”.

The underlying timestamp data (always UTC) remains unchanged. Only the timezone metadata in the Field’s ArrowType is updated.

§Errors

Returns an error if the array is not a Timestamp type.

Source

pub fn view( &self, offset: usize, len: usize, ) -> ((&Array, usize, usize), &Field)

Returns a zero-copy view (FieldArraySlice) into the window [offset, offset+len).

The returned object holds references into the original FieldArray.

The (&Array, Offset, WindowLength), &Field) FieldArraySlice pattern here is a once-off we avoid recommending.

Source

pub fn slice_clone(&self, offset: usize, len: usize) -> FieldArray

Returns a new owned FieldArray with array sliced [offset, offset+len).

Source

pub fn refresh_null_count(&mut self)

Updates the cached null_count from the underlying array. Should be called after any mutation of the array that could change null count.

Source

pub fn null_count(&self) -> usize

Returns the cached null count. This is kept in sync with the underlying array via refresh_null_count().

Source

pub fn concat_field_array(&mut self, other: &FieldArray)

Concatenates another FieldArray’s data into this one using copy-on-write semantics. If this FieldArray’s array has Arc reference count > 1, the data is cloned first. Both FieldArrays must have compatible types. Updates the cached null_count.

Source

pub fn concat_range( &mut self, other: &FieldArray, offset: usize, len: usize, ) -> Result<(), MinarrowError>

Appends rows [offset..offset+len) from another FieldArray into self. Extends data directly from the source’s backing buffer.

Source

pub fn with_array_mut<F, R>(&mut self, f: F) -> R
where F: FnOnce(&mut Array) -> R,

Provides mutable access to the underlying array with automatic null_count refresh. Uses copy-on-write semantics - clones array data if Arc reference count > 1. Use this for operations that may change the null count.

Trait Implementations§

Source§

impl Clone for FieldArray

Source§

fn clone(&self) -> FieldArray

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Concatenate for FieldArray

Source§

fn concat(self, other: FieldArray) -> Result<FieldArray, MinarrowError>

Concatenates two FieldArrays, consuming both.

§Requirements
  • Both FieldArrays must have matching field metadata:
    • Same name
    • Same dtype
    • Same nullability
§Returns

A new FieldArray with the concatenated array data

§Errors
  • IncompatibleTypeError if field metadata doesn’t match
Source§

impl Debug for FieldArray

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Display for FieldArray

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl From<FieldArray> for PyArray

Source§

fn from(field_array: FieldArray) -> Self

Converts to this type from the input type.
Source§

impl From<FieldArray> for SuperArray

Source§

fn from(fa: FieldArray) -> SuperArray

Converts to this type from the input type.
Source§

impl From<PyArray> for FieldArray

Source§

fn from(value: PyArray) -> Self

Converts to this type from the input type.
Source§

impl FromIterator<FieldArray> for SuperArray

Source§

fn from_iter<T>(iter: T) -> SuperArray
where T: IntoIterator<Item = FieldArray>,

Creates a value from an iterator. Read more
Source§

impl PartialEq for FieldArray

Source§

fn eq(&self, other: &FieldArray) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl RowSelection for FieldArray

Available on crate features select and views only.
Source§

type View = ArrayV

The view type returned by selection operations
Source§

fn r<S>(&self, selection: S) -> ArrayV
where S: DataSelector,

Select rows by index or range Read more
Source§

fn get_row_count(&self) -> usize

Get the count for data resolution
Source§

impl Shape for FieldArray

Source§

fn shape(&self) -> ShapeDim

Returns arbitrary Shape dimension for any data shape
Source§

fn shape_1d(&self) -> usize

Returns the first dimension shape Read more
Source§

fn shape_2d(&self) -> (usize, usize)

Returns the first and second dimension shapes Read more
Source§

fn shape_3d(&self) -> (usize, usize, usize)

Returns the first, second and third dimension shapes Read more
Source§

fn shape_4d(&self) -> (usize, usize, usize, usize)

Returns the first, second, third and fourth dimension shapes Read more
Source§

impl StructuralPartialEq for FieldArray

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> CustomValue for T
where T: Any + Send + Sync + Clone + PartialEq + Debug,

Source§

fn as_any(&self) -> &(dyn Any + 'static)

Downcasts the type as Any
Source§

fn deep_clone(&self) -> Arc<dyn CustomValue>

Returns a deep clone of the object. Read more
Source§

fn eq_box(&self, other: &(dyn CustomValue + 'static)) -> bool

Performs semantic equality on the boxed object. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Print for T
where T: Display,

Source§

fn print(&self)
where Self: Display,

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> Ungil for T
where T: Send,