Skip to main content

minarrow/
aliases.rs

1// Copyright 2025 Peter Garfield Bower
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! # **Aliases & View Tuples** - *Lightweight Tuple Views and Fast-To-Type Aliases*
16//!
17//! Aliases for convenience and lightweight *view tuple* types used across the crate.
18//!
19//! ## What’s here
20//! - **Record batch names:** `RecordBatch` -> [`Table`], `ChunkedTable` -> [`SuperTable`].
21//! - **Window metadata:** [`Offset`] and [`Length`] for logical row ranges; plus helpers like
22//!   [`DictLength`] and [`BytesLength`] for dictionary and string buffers.
23//! - **Zero-copy views:** Compact `(..., Offset, Length)` View-Tuple (*VT*) tuples (e.g. [`ArrayVT`], [`BitmaskVT`],
24//!   [`StringAVT`]) that carry a reference to the source plus a window, without allocating.
25//! - **Ergonomic column aliases:** Short forms like [`IntArr`], [`FltArr`], [`StrArr`], etc.
26//! for those such inclined.
27//!
28//! ## Why it exists
29//! Many APIs only need “where to look” (offset/len) and “what to look at” (a reference).
30//! These aliases centralise the naming and keep signatures short, while remaining zero-copy.
31//!
32//! ## Picking a view
33//! - Use **`ArrayV`** (full view struct) when you want methods (typed access, null counts, etc.).
34//! - Use **VT tuples** (e.g. `(&Array, Offset, Length)`) for the lightest possible window with
35//!   no extra behavior. For inner array types, only the Array View Tuples (*AVT*) are provided
36//! to avoid lots of boilerplate redundancy polluting the main library and binary size.
37//! - For fixed-width primitives you can often use native slices (`&[T]`) directly; VT types are
38//!   provided for consistency where needed.
39//!
40//! ## Feature gates
41//! Some aliases are enabled only when relevant features are on (e.g. `datetime`, `views`, `cube`, `chunked`).
42//!
43//! ## Notes
44//! All offsets/lengths are **logical row counts** unless specified otherwise (e.g. `BytesLength`).
45//! These helpers do not copy data and are safe to clone cheaply.
46
47#[cfg(feature = "datetime")]
48use crate::DatetimeArray;
49#[cfg(all(feature = "cube", feature = "views"))]
50use crate::TableV;
51use crate::{
52    Array, Bitmask, BooleanArray, CategoricalArray, Field, FieldArray, FloatArray, IntegerArray,
53    StringArray, Table,
54};
55
56#[cfg(feature = "chunked")]
57use crate::SuperTable;
58
59#[cfg(feature = "ndarray")]
60use crate::NdArray;
61#[cfg(all(feature = "ndarray", feature = "chunked"))]
62use crate::SuperNdArray;
63#[cfg(feature = "xarray")]
64use crate::XArray;
65
66/// # RecordBatch
67///
68/// Standard Arrow `Record Batch`. Alias of *Minarrow* `Table`.
69///
70/// # Description
71/// - Standard columnar table batch with named columns (`FieldArray`),
72/// a fixed number of rows, and an optional logical table name.
73/// - All columns are required to be equal length and have consistent schema.
74/// - Supports zero-copy slicing, efficient iteration, and bulk operations.
75/// - Equivalent to the `RecordBatch` in *Apache Arrow*.
76///
77/// # Structure
78/// - `cols`: A vector of `FieldArray`, each representing a column with metadata and data.
79/// - `n_rows`: The logical number of rows (guaranteed equal for all columns).
80/// - `name`: Optional logical name or alias for this table instance.
81///
82/// # Usage
83/// - Use `Table` as a general-purpose, in-memory columnar data container.
84/// - Good for analytics, transformation pipelines, and FFI or Arrow interoperability.
85/// - For batched/partitioned tables, see [`ChunkedTable`] or windowed/chunked abstractions.
86///
87/// # Notes
88/// - Table instances are typically lightweight to clone and pass by value.
89/// - For mutation, construct a new table or replace individual columns as needed.
90///
91/// # Example
92/// ```rust
93/// use minarrow::{fa_i32, fa_str32, Print, aliases::RecordBatch};
94///
95/// let col1 = fa_i32!("numbers", 1, 2, 3);
96/// let col2 = fa_str32!("letters", "x", "y", "z");
97///
98/// let mut tbl = RecordBatch::new("Demo", vec![col1, col2].into());
99/// tbl.print();
100/// ```
101pub type RecordBatch = Table;
102
103/// # ChunkedTable
104///
105/// Batched (windowed/chunked) table - collection of `Tables`.
106///
107/// ### Data structure
108/// Each Table represents a record batch with schema consistency enforced.
109/// Windows/row-chunks are tracked as Vec<Table>.
110///
111/// - `batches`: Ordered record batches.
112/// - `schema`: schema of the first batch, cached for fast access.
113/// - `n_rows`: total number of rows across all batches.
114/// - `name`: logical group name.
115///
116/// ### Use cases
117/// Useful for cases such as :
118///     1. Streaming *(and mini-batch processing)*
119///     2. Reading from multiple memory mapped arrow files from disk
120///     3. In-memory analytics, where chunks can be used as a source for
121///     parallelism, or windowing, etc., depending on use case semantics.
122#[cfg(feature = "chunked")]
123pub type ChunkedTable = SuperTable;
124
125// ----------------- Array Views --------------------------------
126//
127// Combined zero-copy views, and/or windows that facilitate
128// slicing only the required array portions that hold onto the
129// parameters to support reconstruction.
130//
131// -----------------------------------------------------------------
132
133/// The `ArrayView` offset lower bound, for a windowed view.
134/// Set to `0` for the whole set.
135pub type Offset = usize;
136
137/// The logical length of the `ArrayView`.
138/// Set to `arr.len()` for the whole set.
139pub type Length = usize;
140
141/// Dictionary field length for a `DictionaryArray`
142pub type DictLength = usize;
143
144/// Raw bytes data length for a `StringArray`
145///
146/// Physical length, rather than logical offsets.\
147/// Useful when keying back into it downstream.
148pub type BytesLength = usize;
149
150// Top-level type
151
152/// Windowed ***V**iew **T**uple* for Array, when one isn't using the
153/// full `ArrayView` abstraction, doesn't want to use it, couple a
154/// function signature to it or doesn't have that feature enabled.
155pub type ArrayVT<'a> = (&'a Array, Offset, Length);
156
157/// Windowed ***V**iew **T**uple* for Bitmask
158pub type BitmaskVT<'a> = (&'a Bitmask, Offset, Length);
159
160/// Windowed ***V**iew **T**uple* for NdArray. Offset and length are
161/// axis-0 observation counts.
162#[cfg(feature = "ndarray")]
163pub type NdArrayVT<'a, T> = (&'a NdArray<T>, Offset, Length);
164
165/// Windowed ***V**iew **T**uple* for SuperNdArray. Offset and length are
166/// axis-0 observation counts across batches. For chunk-spanning access
167/// with methods, use [`SuperNdArrayV`](crate::SuperNdArrayV).
168#[cfg(all(feature = "ndarray", feature = "chunked"))]
169pub type SuperNdArrayVT<'a, T> = (&'a SuperNdArray<T>, Offset, Length);
170
171/// Windowed ***V**iew **T**uple* for XArray. Offset and length are
172/// axis-0 observation counts.
173#[cfg(feature = "xarray")]
174pub type XArrayVT<'a, T> = (&'a XArray<T>, Offset, Length);
175
176/// Subset per respective table within the cube
177///
178/// Respects the means in which each table is windowed,
179/// e.g., if offsets and lengths are different due to category lengths,
180/// time windows etc.
181#[cfg(all(feature = "cube", feature = "views"))]
182pub type CubeV = Vec<TableV>;
183
184// Low-level types
185
186// Also see `crate::bitmask_view::BitmaskView`
187
188/// Logical windowed ***A**rray **V**iew **T**uple* over a Boolean array.
189pub type BooleanAVT<'a, T> = (&'a BooleanArray<T>, Offset, Length);
190
191/// Logical windowed ***A**rray **V**iew **T**uple* over a categorical array.
192pub type CategoricalAVT<'a, T> = (&'a CategoricalArray<T>, Offset, Length);
193
194/// Logical windowed ***A**rray **V**iew **T**uple* over a categorical array, including dictionary length.
195pub type CategoricalAVTExt<'a, T> = (&'a CategoricalArray<T>, Offset, Length, DictLength);
196
197/// Logical windowed ***A**rray **V**iew **T**uple* over a UTF-8 string array.
198pub type StringAVT<'a, T> = (&'a StringArray<T>, Offset, Length);
199
200/// Logical windowed ***A**rray **V**iew **T**uple* over a UTF-8 string array, including byte length.
201pub type StringAVTExt<'a, T> = (&'a StringArray<T>, Offset, Length, BytesLength);
202
203/// Logical windowed ***A**rray **V**iew **T**uple* over a datetime array.
204#[cfg(feature = "datetime")]
205pub type DatetimeAVT<'a, T> = (&'a DatetimeArray<T>, Offset, Length);
206
207// When working with Float and Integer, `as_slice` or `slice_tuple` off those arrays is already sufficient,
208// and the recommended pattern. Slice &[T] already pre-slices to a 1:1 index <-> memory layout.
209// Regardless, they are included below for completeness.
210//
211// The others are different, because they include context on the source object that's lost when
212// moving to slice, and/or hold different physical vs. logical layouts.
213
214/// Logical windowed ***A**rray **V**iew **T**uple* over a primitive integer array.
215pub type IntegerAVT<'a, T> = (&'a IntegerArray<T>, Offset, Length);
216
217/// Logical windowed ***A**rray **V**iew **T**uple* over a primitive float array.
218pub type FloatAVT<'a, T> = (&'a FloatArray<T>, Offset, Length);
219
220/// Logical windowed ***A**rray **V**iew **T**uple* over an `Array` and its `Field`: *((array, offset, len), field)*.
221///
222/// Available if desired, but it's recommended to avoid due to reduced clarity and ergonomics (e.g., `.0.1` access).\
223/// In many cases, there are cleaner ways to retain a `Field` for reconstruction without coupling or polluting downstream APIs.
224pub type FieldAVT<'a> = ((&'a Array, Offset, Length), &'a Field);
225
226// ----------------- Standard Aliases --------------------------------
227
228// Less syllables
229
230pub type IntArr<T> = IntegerArray<T>;
231pub type FltArr<T> = FloatArray<T>;
232pub type StrArr<T> = StringArray<T>;
233pub type CatArr<T> = CategoricalArray<T>;
234#[cfg(feature = "datetime")]
235pub type DtArr<T> = DatetimeArray<T>;
236pub type BoolArr = BooleanArray<()>;
237pub type FA = FieldArray;