minarrow 0.10.0

Apache Arrow-compatible, Rust-first columnar data library for high-performance computing, native streaming, and embedded workloads. Minimal dependencies, ultra-low-latency access, automatic 64-byte SIMD alignment, and fast compile times. Great for real-time analytics, HPC pipelines, and systems integration.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
// Copyright 2025 Peter Garfield Bower
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::sync::Arc;

use crate::enums::error::MinarrowError;
use crate::enums::operators::ArithmeticOperator;
use crate::kernels::broadcast::broadcast_value;
use crate::kernels::routing::arithmetic::resolve_binary_arithmetic;
use crate::{ArrayV, FieldArray, Scalar, SuperArrayV, SuperTableV, Table, TableV, Value};

/// Helper function for TableView-TableView broadcasting - work directly with views
#[cfg(feature = "views")]
pub fn broadcast_tableview_to_tableview(
    op: ArithmeticOperator,
    table_view_l: &TableV,
    table_view_r: &TableV,
) -> Result<Table, MinarrowError> {
    // Ensure tables have same number of columns
    if table_view_l.cols.len() != table_view_r.cols.len() {
        return Err(MinarrowError::ShapeError {
            message: format!(
                "TableView column count mismatch: {} vs {}",
                table_view_l.cols.len(),
                table_view_r.cols.len()
            ),
        });
    }

    let mut result_field_arrays = Vec::new();

    // No conversion needed
    for ((array_view_l, field_l), array_view_r) in table_view_l
        .cols
        .iter()
        .zip(&table_view_l.fields)
        .zip(table_view_r.cols.iter())
    {
        // Route through array broadcasting using the ArrayViews directly
        let result_array =
            resolve_binary_arithmetic(op, array_view_l.clone(), array_view_r.clone(), None)?;

        // Create new FieldArray with result
        let result_field_array = FieldArray::new(field_l.as_ref().clone(), result_array);
        result_field_arrays.push(result_field_array);
    }

    Ok(Table::new("".to_string(), Some(result_field_arrays)))
}

/// Helper function for tableview-scalar broadcasting - work directly with views
#[cfg(all(feature = "scalar_type", feature = "views"))]
pub fn broadcast_tableview_to_scalar(
    op: ArithmeticOperator,
    table_view: &TableV,
    scalar: &Scalar,
) -> Result<Table, MinarrowError> {
    // Broadcast each column view with scalar directly
    let new_cols: Result<Vec<_>, _> = table_view
        .cols
        .iter()
        .map(|col_view| {
            // Broadcast scalar with the column directly
            let scalar_value = Value::Scalar(scalar.clone());

            // Broadcast with the column view
            let result = broadcast_value(
                op,
                Value::ArrayView(Arc::new(col_view.clone())),
                scalar_value,
            )?;

            match result {
                Value::Array(arr) => Ok(Arc::unwrap_or_clone(arr)),
                _ => Err(MinarrowError::TypeError {
                    from: "tableview-scalar broadcasting",
                    to: "Array result",
                    message: Some("Expected Array result from broadcasting".to_string()),
                }),
            }
        })
        .collect();

    // Create FieldArrays from the result arrays
    let field_arrays: Vec<FieldArray> = table_view
        .fields
        .iter()
        .zip(new_cols?)
        .map(|(field, array)| FieldArray::new_arc(field.clone(), array))
        .collect();

    Ok(Table::new(table_view.name.clone(), Some(field_arrays)))
}

/// Helper function for tableview-arrayview broadcasting - work directly with views
#[cfg(feature = "views")]
pub fn broadcast_tableview_to_arrayview(
    op: ArithmeticOperator,
    table_view: &TableV,
    array_view: &ArrayV,
) -> Result<TableV, MinarrowError> {
    let new_cols: Result<Vec<_>, _> = table_view
        .cols
        .iter()
        .map(|col_view| {
            let result_array = match (
                Value::ArrayView(Arc::new(col_view.clone())),
                Value::ArrayView(Arc::new(array_view.clone())),
            ) {
                (a, b) => broadcast_value(op, a, b)?,
            };

            match result_array {
                Value::Array(result_array) => Ok(ArrayV::from(Arc::unwrap_or_clone(result_array))),
                _ => Err(MinarrowError::TypeError {
                    from: "tableview-arrayview broadcasting",
                    to: "ArrayView result",
                    message: Some("Expected Array result from broadcasting".to_string()),
                }),
            }
        })
        .collect();

    Ok(TableV {
        name: table_view.name.clone(),
        fields: table_view.fields.clone(),
        cols: new_cols?,
        offset: table_view.offset,
        len: table_view.len,
        #[cfg(feature = "select")]
        active_col_selection: None,
    })
}

/// Helper function for TableView-SuperArrayView broadcasting - promote TableView to aligned SuperTableView
#[cfg(all(feature = "chunked", feature = "views"))]
pub fn broadcast_tableview_to_superarrayview(
    op: ArithmeticOperator,
    table_view: &TableV,
    super_array_view: &SuperArrayV,
) -> Result<SuperTableV, MinarrowError> {
    // 1. Validate lengths match
    if table_view.len != super_array_view.len {
        return Err(MinarrowError::ShapeError {
            message: format!(
                "TableView length ({}) does not match SuperArrayView length ({})",
                table_view.len, super_array_view.len
            ),
        });
    }

    // 2. Promote TableView to SuperTableView with aligned chunking
    let mut current_offset = 0;
    let mut table_slices = Vec::new();

    for array_slice in super_array_view.slices.iter() {
        let chunk_len = array_slice.len();
        let table_slice = table_view.from_self(current_offset, chunk_len);
        table_slices.push(table_slice);
        current_offset += chunk_len;
    }

    let aligned_super_table = SuperTableV {
        slices: table_slices,
        len: table_view.len,
    };

    // 3. Broadcast per chunk using indexed loops
    let mut result_slices = Vec::new();
    for i in 0..aligned_super_table.slices.len() {
        let table_slice = &aligned_super_table.slices[i];
        let array_slice = &super_array_view.slices[i];
        let slice_result = broadcast_tableview_to_arrayview(op, table_slice, array_slice)?;
        result_slices.push(slice_result);
    }

    Ok(SuperTableV {
        slices: result_slices,
        len: super_array_view.len,
    })
}

#[cfg(all(test, feature = "views"))]
mod tests {
    use super::*;
    use crate::ffi::arrow_dtype::ArrowType;
    use crate::{Array, Field, FieldArray, IntegerArray, NumericArray, Table, vec64};

    #[test]
    fn test_tableview_to_tableview_add() {
        // Create two tables
        let arr1 = Array::from_int32(IntegerArray::from_slice(&vec64![1, 2, 3]));
        let arr2 = Array::from_int32(IntegerArray::from_slice(&vec64![10, 20, 30]));
        let table1 = Table::build(
            vec![
                FieldArray::new(
                    Field::new("col1".to_string(), ArrowType::Int32, false, None),
                    arr1,
                ),
                FieldArray::new(
                    Field::new("col2".to_string(), ArrowType::Int32, false, None),
                    arr2,
                ),
            ],
            3,
            "test".to_string(),
        );
        let table_view1 = TableV::from_table(table1, 0, 3);

        let arr3 = Array::from_int32(IntegerArray::from_slice(&vec64![5, 5, 5]));
        let arr4 = Array::from_int32(IntegerArray::from_slice(&vec64![100, 100, 100]));
        let table2 = Table::build(
            vec![
                FieldArray::new(
                    Field::new("col1".to_string(), ArrowType::Int32, false, None),
                    arr3,
                ),
                FieldArray::new(
                    Field::new("col2".to_string(), ArrowType::Int32, false, None),
                    arr4,
                ),
            ],
            3,
            "test".to_string(),
        );
        let table_view2 = TableV::from_table(table2, 0, 3);

        let result =
            broadcast_tableview_to_tableview(ArithmeticOperator::Add, &table_view1, &table_view2)
                .unwrap();

        assert_eq!(result.n_rows, 3);
        assert_eq!(result.n_cols(), 2);

        // col1: [1,2,3] + [5,5,5] = [6,7,8]
        if let Array::NumericArray(NumericArray::Int32(arr)) = &result.cols[0].array {
            assert_eq!(arr.data.as_slice(), &[6, 7, 8]);
        } else {
            panic!("Expected Int32 array");
        }

        // col2: [10,20,30] + [100,100,100] = [110,120,130]
        if let Array::NumericArray(NumericArray::Int32(arr)) = &result.cols[1].array {
            assert_eq!(arr.data.as_slice(), &[110, 120, 130]);
        } else {
            panic!("Expected Int32 array");
        }
    }

    #[test]
    fn test_tableview_to_tableview_column_mismatch() {
        // Create tables with different numbers of columns
        let arr1 = Array::from_int32(IntegerArray::from_slice(&vec64![1, 2, 3]));
        let table1 = Table::build(
            vec![FieldArray::new(
                Field::new("col1".to_string(), ArrowType::Int32, false, None),
                arr1,
            )],
            3,
            "test".to_string(),
        );
        let table_view1 = TableV::from_table(table1, 0, 3);

        let arr2 = Array::from_int32(IntegerArray::from_slice(&vec64![5, 5, 5]));
        let arr3 = Array::from_int32(IntegerArray::from_slice(&vec64![10, 10, 10]));
        let table2 = Table::build(
            vec![
                FieldArray::new(
                    Field::new("col1".to_string(), ArrowType::Int32, false, None),
                    arr2,
                ),
                FieldArray::new(
                    Field::new("col2".to_string(), ArrowType::Int32, false, None),
                    arr3,
                ),
            ],
            3,
            "test".to_string(),
        );
        let table_view2 = TableV::from_table(table2, 0, 3);

        let result =
            broadcast_tableview_to_tableview(ArithmeticOperator::Add, &table_view1, &table_view2);

        assert!(result.is_err());
        if let Err(MinarrowError::ShapeError { message }) = result {
            assert!(message.contains("column count mismatch"));
        } else {
            panic!("Expected ShapeError");
        }
    }

    #[cfg(feature = "scalar_type")]
    #[test]
    fn test_tableview_to_scalar_multiply() {
        let arr1 = Array::from_int32(IntegerArray::from_slice(&vec64![2, 3, 4]));
        let arr2 = Array::from_int32(IntegerArray::from_slice(&vec64![5, 6, 7]));
        let table = Table::build(
            vec![
                FieldArray::new(
                    Field::new("col1".to_string(), ArrowType::Int32, false, None),
                    arr1,
                ),
                FieldArray::new(
                    Field::new("col2".to_string(), ArrowType::Int32, false, None),
                    arr2,
                ),
            ],
            3,
            "test".to_string(),
        );
        let table_view = TableV::from_table(table, 0, 3);

        let scalar = Scalar::Int32(10);

        let result =
            broadcast_tableview_to_scalar(ArithmeticOperator::Multiply, &table_view, &scalar)
                .unwrap();

        // col1: [2,3,4] * 10 = [20,30,40]
        if let Array::NumericArray(NumericArray::Int32(arr)) = &result.cols[0].array {
            assert_eq!(arr.data.as_slice(), &[20, 30, 40]);
        } else {
            panic!("Expected Int32 array");
        }

        // col2: [5,6,7] * 10 = [50,60,70]
        if let Array::NumericArray(NumericArray::Int32(arr)) = &result.cols[1].array {
            assert_eq!(arr.data.as_slice(), &[50, 60, 70]);
        } else {
            panic!("Expected Int32 array");
        }
    }

    #[test]
    fn test_tableview_to_arrayview_subtract() {
        let arr1 = Array::from_int32(IntegerArray::from_slice(&vec64![100, 200, 300]));
        let table = Table::build(
            vec![FieldArray::new(
                Field::new("col1".to_string(), ArrowType::Int32, false, None),
                arr1,
            )],
            3,
            "test".to_string(),
        );
        let table_view = TableV::from_table(table, 0, 3);

        let arr2 = Array::from_int32(IntegerArray::from_slice(&vec64![10, 20, 30]));
        let array_view = ArrayV::from(arr2);

        let result = broadcast_tableview_to_arrayview(
            ArithmeticOperator::Subtract,
            &table_view,
            &array_view,
        )
        .unwrap();

        assert_eq!(result.len, 3);

        // [100,200,300] - [10,20,30] = [90,180,270]
        let result_table = result.to_table();
        if let Array::NumericArray(NumericArray::Int32(arr)) = &result_table.cols[0].array {
            assert_eq!(arr.data.as_slice(), &[90, 180, 270]);
        } else {
            panic!("Expected Int32 array");
        }
    }

    #[cfg(feature = "chunked")]
    #[test]
    fn test_tableview_to_superarrayview() {
        use crate::SuperArrayV;
        use std::sync::Arc;

        // Create table with 6 rows
        let arr1 = Array::from_int32(IntegerArray::from_slice(&vec64![1, 2, 3, 4, 5, 6]));
        let table = Table::build(
            vec![FieldArray::new(
                Field::new("col1".to_string(), ArrowType::Int32, false, None),
                arr1,
            )],
            6,
            "test".to_string(),
        );
        let table_view = TableV::from_table(table, 0, 6);

        // Create SuperArrayView with 2 chunks of 3 elements each
        let field = Field::new("data".to_string(), ArrowType::Int32, false, None);
        let arr = Array::from_int32(IntegerArray::from_slice(&vec64![10, 20, 30, 40, 50, 60]));

        let slices = vec![
            ArrayV::from(arr.clone()).slice(0, 3),
            ArrayV::from(arr.clone()).slice(3, 3),
        ];
        let super_array_view = SuperArrayV {
            slices,
            field: Arc::new(field),
            len: 6,
        };

        let result = broadcast_tableview_to_superarrayview(
            ArithmeticOperator::Multiply,
            &table_view,
            &super_array_view,
        )
        .unwrap();

        assert_eq!(result.len, 6);
        assert_eq!(result.slices.len(), 2);

        // First slice: [1,2,3] * [10,20,30] = [10,40,90]
        let slice1 = result.slices[0].to_table();
        if let Array::NumericArray(NumericArray::Int32(arr)) = &slice1.cols[0].array {
            assert_eq!(arr.data.as_slice(), &[10, 40, 90]);
        } else {
            panic!("Expected Int32 array");
        }

        // Second slice: [4,5,6] * [40,50,60] = [160,250,360]
        let slice2 = result.slices[1].to_table();
        if let Array::NumericArray(NumericArray::Int32(arr)) = &slice2.cols[0].array {
            assert_eq!(arr.data.as_slice(), &[160, 250, 360]);
        } else {
            panic!("Expected Int32 array");
        }
    }

    #[cfg(feature = "chunked")]
    #[test]
    fn test_tableview_to_superarrayview_length_mismatch() {
        use crate::{FieldArray as FA, SuperArray, SuperArrayV};

        let arr1 = Array::from_int32(IntegerArray::from_slice(&vec64![1, 2, 3, 4, 5]));
        let table = Table::build(
            vec![FieldArray::new(
                Field::new("col1".to_string(), ArrowType::Int32, false, None),
                arr1,
            )],
            5,
            "test".to_string(),
        );
        let table_view = TableV::from_table(table, 0, 5);

        // Create SuperArrayView with 6 elements (mismatch)
        let fa1 = FA::new(
            Field::new("test".to_string(), ArrowType::Int32, false, None),
            Array::from_int32(IntegerArray::from_slice(&vec64![10, 20, 30])),
        );
        let fa2 = FA::new(
            Field::new("test".to_string(), ArrowType::Int32, false, None),
            Array::from_int32(IntegerArray::from_slice(&vec64![40, 50, 60])),
        );
        let super_array = SuperArray::from_chunks(vec![fa1, fa2]);
        let super_array_view = SuperArrayV::from(super_array);

        let result = broadcast_tableview_to_superarrayview(
            ArithmeticOperator::Add,
            &table_view,
            &super_array_view,
        );

        assert!(result.is_err());
        if let Err(MinarrowError::ShapeError { message }) = result {
            assert!(message.contains("does not match"));
        } else {
            panic!("Expected ShapeError");
        }
    }
}