minarrow 0.10.1

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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
// 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::Bitmask;
#[cfg(feature = "cube")]
use crate::Cube;
#[cfg(all(feature = "cube", feature = "scalar_type"))]
use crate::Scalar;
use crate::enums::error::KernelError;
use crate::kernels::broadcast::table::broadcast_table_add;

#[cfg(feature = "cube")]
use crate::{Array, FieldArray, Table};

#[cfg(all(feature = "cube", feature = "views"))]
use crate::ArrayV;

use crate::enums::{error::MinarrowError, operators::ArithmeticOperator};

#[cfg(feature = "cube")]
use crate::kernels::broadcast::{
    array::broadcast_array_to_table,
    table::{broadcast_table_to_array, broadcast_table_to_scalar, broadcast_table_with_operator},
};

/// Broadcasts addition over Cube tables (3D structure)
///
/// Cubes are 3D structures where the Vec<Table> acts as the 'z' axis.
/// Both cubes must have the same number of tables and compatible table shapes.
/// Addition is applied table-wise between corresponding tables.
pub fn broadcast_cube_add(
    lhs: Cube,
    rhs: Cube,
    null_mask: Option<Arc<Bitmask>>,
) -> Result<Cube, KernelError> {
    // Check table count compatibility
    if lhs.tables.len() != rhs.tables.len() {
        return Err(KernelError::BroadcastingError(format!(
            "Cube table count mismatch: LHS {} tables, RHS {} tables",
            lhs.tables.len(),
            rhs.tables.len()
        )));
    }

    // Apply addition table-wise
    let mut result_tables = Vec::with_capacity(lhs.tables.len());

    for (i, (lhs_table, rhs_table)) in lhs.tables.iter().zip(rhs.tables.iter()).enumerate() {
        let result_table =
            broadcast_table_add(lhs_table.clone(), rhs_table.clone(), null_mask.clone()).map_err(
                |e| KernelError::BroadcastingError(format!("Table {} addition failed: {}", i, e)),
            )?;

        result_tables.push(result_table);
    }

    // Create result Cube with same metadata as left cube
    Ok(Cube::from_tables(result_tables, lhs.name.clone(), lhs.third_dim_index.clone()))
}

/// Broadcast Cube to Scalar - apply scalar to each table in the cube
#[cfg(all(feature = "cube", feature = "scalar_type"))]
pub fn broadcast_cube_to_scalar(
    op: ArithmeticOperator,
    cube: &Cube,
    scalar: &Scalar,
) -> Result<Cube, MinarrowError> {
    let mut result_tables = Vec::with_capacity(cube.tables.len());
    for table in &cube.tables {
        let broadcasted = broadcast_table_to_scalar(op, table, scalar)?;
        result_tables.push(broadcasted);
    }
    Ok(Cube::from_tables(result_tables, cube.name.clone(), cube.third_dim_index.clone()))
}

/// Broadcast Cube to Array - apply array to each table in the cube
#[cfg(feature = "cube")]
pub fn broadcast_cube_to_array(
    op: ArithmeticOperator,
    cube: &Cube,
    array: &Array,
) -> Result<Cube, MinarrowError> {
    let mut result_tables = Vec::with_capacity(cube.tables.len());
    for table in &cube.tables {
        let broadcasted = broadcast_table_to_array(op, table, array)?;
        result_tables.push(broadcasted);
    }
    Ok(Cube::from_tables(result_tables, cube.name.clone(), cube.third_dim_index.clone()))
}

/// Broadcast FieldArray to Cube - apply field array's inner array to each table in the cube
#[cfg(feature = "cube")]
pub fn broadcast_fieldarray_to_cube(
    op: ArithmeticOperator,
    field_array: &FieldArray,
    cube: &Cube,
) -> Result<Cube, MinarrowError> {
    let array = &field_array.array;
    let mut result_tables = Vec::with_capacity(cube.tables.len());
    for table in &cube.tables {
        let broadcasted = broadcast_array_to_table(op, array, table)?;
        result_tables.push(broadcasted);
    }
    Ok(Cube::from_tables(result_tables, cube.name.clone(), cube.third_dim_index.clone()))
}

/// Broadcast Cube to FieldArray - apply field array's inner array to each table in the cube
#[cfg(feature = "cube")]
pub fn broadcast_cube_to_fieldarray(
    op: ArithmeticOperator,
    cube: &Cube,
    field_array: &FieldArray,
) -> Result<Cube, MinarrowError> {
    let array = &field_array.array;
    let mut result_tables = Vec::with_capacity(cube.tables.len());
    for table in &cube.tables {
        let broadcasted = broadcast_table_to_array(op, table, array)?;
        result_tables.push(broadcasted);
    }
    Ok(Cube::from_tables(result_tables, cube.name.clone(), cube.third_dim_index.clone()))
}

/// Broadcast Table to Cube - apply table to each table in the cube
#[cfg(feature = "cube")]
pub fn broadcast_table_to_cube(
    op: ArithmeticOperator,
    table: &Table,
    cube: &Cube,
) -> Result<Cube, MinarrowError> {
    let mut result_tables = Vec::with_capacity(cube.tables.len());
    for cube_table in &cube.tables {
        let broadcasted = broadcast_table_with_operator(op, table.clone(), cube_table.clone())?;
        result_tables.push(broadcasted);
    }
    Ok(Cube::from_tables(result_tables, cube.name.clone(), cube.third_dim_index.clone()))
}

/// Broadcast Cube to Table - apply table to each table in the cube
#[cfg(feature = "cube")]
pub fn broadcast_cube_to_table(
    op: ArithmeticOperator,
    cube: &Cube,
    table: &Table,
) -> Result<Cube, MinarrowError> {
    let mut result_tables = Vec::with_capacity(cube.tables.len());
    for cube_table in &cube.tables {
        let broadcasted = broadcast_table_with_operator(op, cube_table.clone(), table.clone())?;
        result_tables.push(broadcasted);
    }
    Ok(Cube::from_tables(result_tables, cube.name.clone(), cube.third_dim_index.clone()))
}

/// Broadcast ArrayView to Cube - apply array view to each table in the cube
#[cfg(all(feature = "cube", feature = "views"))]
pub fn broadcast_arrayview_to_cube(
    op: ArithmeticOperator,
    array_view: &crate::ArrayV,
    cube: &Cube,
) -> Result<Cube, MinarrowError> {
    use crate::kernels::broadcast::array_view::broadcast_arrayview_to_table;
    let mut result_tables = Vec::with_capacity(cube.tables.len());
    for table in &cube.tables {
        let broadcasted = broadcast_arrayview_to_table(op, array_view, table)?;
        result_tables.push(broadcasted);
    }
    Ok(Cube::from_tables(result_tables, cube.name.clone(), cube.third_dim_index.clone()))
}

/// Broadcast Cube to ArrayView - apply array view to each table in the cube
#[cfg(all(feature = "cube", feature = "views"))]
pub fn broadcast_cube_to_arrayview(
    op: ArithmeticOperator,
    cube: &Cube,
    array_view: &crate::ArrayV,
) -> Result<Cube, MinarrowError> {
    use crate::kernels::broadcast::table::broadcast_table_to_arrayview;
    let mut result_tables = Vec::with_capacity(cube.tables.len());
    for table in &cube.tables {
        let broadcasted = broadcast_table_to_arrayview(op, table, array_view)?;
        result_tables.push(broadcasted);
    }
    Ok(Cube::from_tables(result_tables, cube.name.clone(), cube.third_dim_index.clone()))
}

/// Broadcast NumericArrayView to Cube - apply numeric array view to each table in the cube
#[cfg(all(feature = "cube", feature = "views"))]
pub fn broadcast_numericarrayview_to_cube(
    op: ArithmeticOperator,
    num_array_view: &crate::NumericArrayV,
    cube: &Cube,
) -> Result<Cube, MinarrowError> {
    use crate::kernels::broadcast::array_view::broadcast_arrayview_to_table;

    let array_view: ArrayV = num_array_view.clone().into();
    let mut result_tables = Vec::with_capacity(cube.tables.len());
    for table in &cube.tables {
        let broadcasted = broadcast_arrayview_to_table(op, &array_view, table)?;
        result_tables.push(broadcasted);
    }
    Ok(Cube::from_tables(result_tables, cube.name.clone(), cube.third_dim_index.clone()))
}

/// Broadcast Cube to NumericArrayView - apply numeric array view to each table in the cube
#[cfg(all(feature = "cube", feature = "views"))]
pub fn broadcast_cube_to_numericarrayview(
    op: ArithmeticOperator,
    cube: &Cube,
    num_array_view: &crate::NumericArrayV,
) -> Result<Cube, MinarrowError> {
    use crate::kernels::broadcast::table::broadcast_table_to_arrayview;

    let array_view: ArrayV = num_array_view.clone().into();
    let mut result_tables = Vec::with_capacity(cube.tables.len());
    for table in &cube.tables {
        let broadcasted = broadcast_table_to_arrayview(op, table, &array_view)?;
        result_tables.push(broadcasted);
    }
    Ok(Cube::from_tables(result_tables, cube.name.clone(), cube.third_dim_index.clone()))
}

/// Broadcast TextArrayView to Cube - apply text array view to each table in the cube
#[cfg(all(feature = "cube", feature = "views"))]
pub fn broadcast_textarrayview_to_cube(
    op: ArithmeticOperator,
    text_array_view: &crate::TextArrayV,
    cube: &Cube,
) -> Result<Cube, MinarrowError> {
    use crate::kernels::broadcast::array_view::broadcast_arrayview_to_table;

    let array_view: ArrayV = text_array_view.clone().into();
    let mut result_tables = Vec::with_capacity(cube.tables.len());
    for table in &cube.tables {
        let broadcasted = broadcast_arrayview_to_table(op, &array_view, table)?;
        result_tables.push(broadcasted);
    }
    Ok(Cube::from_tables(result_tables, cube.name.clone(), cube.third_dim_index.clone()))
}

/// Broadcast Cube to TextArrayView - apply text array view to each table in the cube
#[cfg(all(feature = "cube", feature = "views"))]
pub fn broadcast_cube_to_textarrayview(
    op: ArithmeticOperator,
    cube: &Cube,
    text_array_view: &crate::TextArrayV,
) -> Result<Cube, MinarrowError> {
    use crate::kernels::broadcast::table::broadcast_table_to_arrayview;

    let array_view: ArrayV = text_array_view.clone().into();
    let mut result_tables = Vec::with_capacity(cube.tables.len());
    for table in &cube.tables {
        let broadcasted = broadcast_table_to_arrayview(op, table, &array_view)?;
        result_tables.push(broadcasted);
    }
    Ok(Cube::from_tables(result_tables, cube.name.clone(), cube.third_dim_index.clone()))
}

/// Broadcast TemporalArrayView to Cube - apply temporal array view to each table in the cube
#[cfg(all(feature = "cube", feature = "views", feature = "datetime"))]
pub fn broadcast_temporalarrayview_to_cube(
    op: ArithmeticOperator,
    temporal_array_view: &crate::TemporalArrayV,
    cube: &Cube,
) -> Result<Cube, MinarrowError> {
    use crate::kernels::broadcast::array_view::broadcast_arrayview_to_table;

    let array_view: ArrayV = temporal_array_view.clone().into();
    let mut result_tables = Vec::with_capacity(cube.tables.len());
    for table in &cube.tables {
        let broadcasted = broadcast_arrayview_to_table(op, &array_view, table)?;
        result_tables.push(broadcasted);
    }
    Ok(Cube::from_tables(result_tables, cube.name.clone(), cube.third_dim_index.clone()))
}

/// Broadcast Cube to TemporalArrayView - apply temporal array view to each table in the cube
#[cfg(all(feature = "cube", feature = "views", feature = "datetime"))]
pub fn broadcast_cube_to_temporalarrayview(
    op: ArithmeticOperator,
    cube: &Cube,
    temporal_array_view: &crate::TemporalArrayV,
) -> Result<Cube, MinarrowError> {
    use crate::kernels::broadcast::table::broadcast_table_to_arrayview;

    let array_view: ArrayV = temporal_array_view.clone().into();
    let mut result_tables = Vec::with_capacity(cube.tables.len());
    for table in &cube.tables {
        let broadcasted = broadcast_table_to_arrayview(op, table, &array_view)?;
        result_tables.push(broadcasted);
    }
    Ok(Cube::from_tables(result_tables, cube.name.clone(), cube.third_dim_index.clone()))
}

/// Broadcast TableView to Cube - apply table view to each table in the cube
#[cfg(all(feature = "cube", feature = "views"))]
pub fn broadcast_tableview_to_cube(
    op: ArithmeticOperator,
    table_view: &crate::TableV,
    cube: &Cube,
) -> Result<Cube, MinarrowError> {
    let table = table_view.to_table();
    let mut result_tables = Vec::with_capacity(cube.tables.len());
    for cube_table in &cube.tables {
        let broadcasted = broadcast_table_with_operator(op, table.clone(), cube_table.clone())?;
        result_tables.push(broadcasted);
    }
    Ok(Cube::from_tables(result_tables, cube.name.clone(), cube.third_dim_index.clone()))
}

/// Helper: Materialise SuperArray into a single contiguous Array by concatenating chunks
#[cfg(feature = "chunked")]
fn materialise_super_array(super_array: &crate::SuperArray) -> Result<Array, MinarrowError> {
    use crate::NumericArray;

    let chunks = super_array.chunks();
    if chunks.is_empty() {
        return Ok(Array::Null);
    }

    // Get the first chunk to determine type
    let first_array = &chunks[0];

    // For now, handle numeric arrays (can be extended for other types)
    match first_array {
        Array::NumericArray(NumericArray::Int32(_)) => {
            use crate::IntegerArray;
            let mut all_values = Vec::new();
            for chunk in chunks {
                if let Array::NumericArray(NumericArray::Int32(arr)) = chunk {
                    all_values.extend_from_slice(arr.data.as_slice());
                } else {
                    return Err(MinarrowError::TypeError {
                        from: "SuperArray chunks",
                        to: "Int32",
                        message: Some("All chunks must have same type".to_string()),
                    });
                }
            }
            Ok(Array::from_int32(IntegerArray::from_vec(all_values, None)))
        }
        Array::NumericArray(NumericArray::Int64(_)) => {
            use crate::IntegerArray;
            let mut all_values = Vec::new();
            for chunk in chunks {
                if let Array::NumericArray(NumericArray::Int64(arr)) = chunk {
                    all_values.extend_from_slice(arr.data.as_slice());
                } else {
                    return Err(MinarrowError::TypeError {
                        from: "SuperArray chunks",
                        to: "Int64",
                        message: Some("All chunks must have same type".to_string()),
                    });
                }
            }
            Ok(Array::from_int64(IntegerArray::from_vec(all_values, None)))
        }
        Array::NumericArray(NumericArray::Float32(_)) => {
            use crate::FloatArray;
            let mut all_values = Vec::new();
            for chunk in chunks {
                if let Array::NumericArray(NumericArray::Float32(arr)) = chunk {
                    all_values.extend_from_slice(arr.data.as_slice());
                } else {
                    return Err(MinarrowError::TypeError {
                        from: "SuperArray chunks",
                        to: "Float32",
                        message: Some("All chunks must have same type".to_string()),
                    });
                }
            }
            Ok(Array::from_float32(FloatArray::from_vec(all_values, None)))
        }
        Array::NumericArray(NumericArray::Float64(_)) => {
            use crate::FloatArray;
            let mut all_values = Vec::new();
            for chunk in chunks {
                if let Array::NumericArray(NumericArray::Float64(arr)) = chunk {
                    all_values.extend_from_slice(arr.data.as_slice());
                } else {
                    return Err(MinarrowError::TypeError {
                        from: "SuperArray chunks",
                        to: "Float64",
                        message: Some("All chunks must have same type".to_string()),
                    });
                }
            }
            Ok(Array::from_float64(FloatArray::from_vec(all_values, None)))
        }
        _ => {
            // For other types, fall back to slower clone-based concatenation
            Err(MinarrowError::NotImplemented {
                feature: format!(
                    "Materialisation not yet implemented for array type: {:?}",
                    first_array
                ),
            })
        }
    }
}

/// Helper: Materialise SuperArrayView into a single contiguous Array by concatenating view slices
#[cfg(all(feature = "chunked", feature = "views"))]
fn materialise_super_array_view(
    super_array_view: &crate::SuperArrayV,
) -> Result<Array, MinarrowError> {
    if super_array_view.slices.is_empty() {
        return Ok(Array::Null);
    }

    // Materialise first slice to determine type
    let first_array = super_array_view.slices[0].to_array();

    use crate::NumericArray;
    match first_array {
        Array::NumericArray(NumericArray::Int32(_)) => {
            use crate::IntegerArray;
            let mut all_values = Vec::new();
            for slice_view in &super_array_view.slices {
                let array = slice_view.to_array();
                if let Array::NumericArray(NumericArray::Int32(arr)) = array {
                    all_values.extend_from_slice(arr.data.as_slice());
                } else {
                    return Err(MinarrowError::TypeError {
                        from: "SuperArrayView slices",
                        to: "Int32",
                        message: Some("All slices must have same type".to_string()),
                    });
                }
            }
            Ok(Array::from_int32(IntegerArray::from_vec(all_values, None)))
        }
        Array::NumericArray(NumericArray::Int64(_)) => {
            use crate::IntegerArray;
            let mut all_values = Vec::new();
            for slice_view in &super_array_view.slices {
                let array = slice_view.to_array();
                if let Array::NumericArray(NumericArray::Int64(arr)) = array {
                    all_values.extend_from_slice(arr.data.as_slice());
                } else {
                    return Err(MinarrowError::TypeError {
                        from: "SuperArrayView slices",
                        to: "Int64",
                        message: Some("All slices must have same type".to_string()),
                    });
                }
            }
            Ok(Array::from_int64(IntegerArray::from_vec(all_values, None)))
        }
        Array::NumericArray(NumericArray::Float32(_)) => {
            use crate::FloatArray;
            let mut all_values = Vec::new();
            for slice_view in &super_array_view.slices {
                let array = slice_view.to_array();
                if let Array::NumericArray(NumericArray::Float32(arr)) = array {
                    all_values.extend_from_slice(arr.data.as_slice());
                } else {
                    return Err(MinarrowError::TypeError {
                        from: "SuperArrayView slices",
                        to: "Float32",
                        message: Some("All slices must have same type".to_string()),
                    });
                }
            }
            Ok(Array::from_float32(FloatArray::from_vec(all_values, None)))
        }
        Array::NumericArray(NumericArray::Float64(_)) => {
            use crate::FloatArray;
            let mut all_values = Vec::new();
            for slice_view in &super_array_view.slices {
                let array = slice_view.to_array();
                if let Array::NumericArray(NumericArray::Float64(arr)) = array {
                    all_values.extend_from_slice(arr.data.as_slice());
                } else {
                    return Err(MinarrowError::TypeError {
                        from: "SuperArrayView slices",
                        to: "Float64",
                        message: Some("All slices must have same type".to_string()),
                    });
                }
            }
            Ok(Array::from_float64(FloatArray::from_vec(all_values, None)))
        }
        _ => Err(MinarrowError::NotImplemented {
            feature: "SuperArrayView materialisation for this array type".to_string(),
        }),
    }
}

/// Helper: Merge SuperTableView slices into a single Table by vertical concatenation
#[cfg(all(feature = "chunked", feature = "views"))]
fn merge_supertableview_slices(
    super_table_view: &crate::SuperTableV,
) -> Result<Table, MinarrowError> {
    if super_table_view.slices.is_empty() {
        return Err(MinarrowError::ShapeError {
            message: "Cannot merge empty SuperTableView".to_string(),
        });
    }

    // Convert all slices to tables and merge using existing helper
    let tables: Vec<Table> = super_table_view
        .slices
        .iter()
        .map(|slice| slice.to_table())
        .collect();

    // Create a temporary SuperTable from the tables and merge it
    let temp_super_table = crate::SuperTable::from_batches(
        tables.into_iter().map(Arc::new).collect(),
        Some("temp".to_string()),
    );

    merge_supertable_batches(&temp_super_table)
}

/// Helper: Merge SuperTable batches into a single Table by vertical concatenation
#[cfg(feature = "chunked")]
fn merge_supertable_batches(super_table: &crate::SuperTable) -> Result<Table, MinarrowError> {
    use crate::NumericArray;

    if super_table.batches.is_empty() {
        return Err(MinarrowError::ShapeError {
            message: "Cannot merge empty SuperTable".to_string(),
        });
    }

    let first_table = &super_table.batches[0];
    let n_cols = first_table.n_cols();

    // Validate all batches have same column count
    for (i, batch) in super_table.batches.iter().enumerate() {
        if batch.n_cols() != n_cols {
            return Err(MinarrowError::ShapeError {
                message: format!(
                    "SuperTable batch {} has {} columns, expected {}",
                    i,
                    batch.n_cols(),
                    n_cols
                ),
            });
        }
    }

    // Concatenate each column vertically across all batches
    let mut merged_cols = Vec::with_capacity(n_cols);

    for col_idx in 0..n_cols {
        let first_col = &first_table.cols[col_idx];
        let field = first_col.field.clone();

        // Collect all values for this column across batches
        match &first_col.array {
            Array::NumericArray(NumericArray::Int32(_)) => {
                use crate::IntegerArray;
                let mut all_values = Vec::new();
                for batch in &super_table.batches {
                    if let Array::NumericArray(NumericArray::Int32(arr)) =
                        &batch.cols[col_idx].array
                    {
                        all_values.extend_from_slice(arr.data.as_slice());
                    } else {
                        return Err(MinarrowError::TypeError {
                            from: "SuperTable batch column",
                            to: "Int32",
                            message: Some("All batch columns must have same type".to_string()),
                        });
                    }
                }
                merged_cols.push(FieldArray::new(
                    field.as_ref().clone(),
                    Array::from_int32(IntegerArray::from_vec(all_values, None)),
                ));
            }
            Array::NumericArray(NumericArray::Int64(_)) => {
                use crate::IntegerArray;
                let mut all_values = Vec::new();
                for batch in &super_table.batches {
                    if let Array::NumericArray(NumericArray::Int64(arr)) =
                        &batch.cols[col_idx].array
                    {
                        all_values.extend_from_slice(arr.data.as_slice());
                    } else {
                        return Err(MinarrowError::TypeError {
                            from: "SuperTable batch column",
                            to: "Int64",
                            message: Some("All batch columns must have same type".to_string()),
                        });
                    }
                }
                merged_cols.push(FieldArray::new(
                    field.as_ref().clone(),
                    Array::from_int64(IntegerArray::from_vec(all_values, None)),
                ));
            }
            Array::NumericArray(NumericArray::Float32(_)) => {
                use crate::FloatArray;
                let mut all_values = Vec::new();
                for batch in &super_table.batches {
                    if let Array::NumericArray(NumericArray::Float32(arr)) =
                        &batch.cols[col_idx].array
                    {
                        all_values.extend_from_slice(arr.data.as_slice());
                    } else {
                        return Err(MinarrowError::TypeError {
                            from: "SuperTable batch column",
                            to: "Float32",
                            message: Some("All batch columns must have same type".to_string()),
                        });
                    }
                }
                merged_cols.push(FieldArray::new(
                    field.as_ref().clone(),
                    Array::from_float32(FloatArray::from_vec(all_values, None)),
                ));
            }
            Array::NumericArray(NumericArray::Float64(_)) => {
                use crate::FloatArray;
                let mut all_values = Vec::new();
                for batch in &super_table.batches {
                    if let Array::NumericArray(NumericArray::Float64(arr)) =
                        &batch.cols[col_idx].array
                    {
                        all_values.extend_from_slice(arr.data.as_slice());
                    } else {
                        return Err(MinarrowError::TypeError {
                            from: "SuperTable batch column",
                            to: "Float64",
                            message: Some("All batch columns must have same type".to_string()),
                        });
                    }
                }
                merged_cols.push(FieldArray::new(
                    field.as_ref().clone(),
                    Array::from_float64(FloatArray::from_vec(all_values, None)),
                ));
            }
            _ => {
                return Err(MinarrowError::NotImplemented {
                    feature: format!(
                        "Merging not yet implemented for array type in column {}",
                        col_idx
                    ),
                });
            }
        }
    }

    let table_out = Table::new(super_table.name.clone(), Some(merged_cols));
    #[cfg(feature = "table_metadata")]
    {
        let mut t = table_out;
        t.metadata = super_table.metadata().clone();
        return Ok(t);
    }
    #[cfg(not(feature = "table_metadata"))]
    Ok(table_out)
}

/// Broadcast SuperArray to Cube - apply super array against each table in the cube (left operand)
#[cfg(all(feature = "cube", feature = "chunked"))]
pub fn broadcast_superarray_to_cube(
    op: ArithmeticOperator,
    super_array: &crate::SuperArray,
    cube: &Cube,
) -> Result<Cube, MinarrowError> {
    // Validate cube shape: all tables must have same row count
    let expected_rows = cube
        .tables
        .first()
        .ok_or_else(|| MinarrowError::ShapeError {
            message: "Cannot broadcast to empty cube".to_string(),
        })?
        .n_rows;

    for (i, table) in cube.tables.iter().enumerate() {
        if table.n_rows != expected_rows {
            return Err(MinarrowError::ShapeError {
                message: format!(
                    "Cube tables must have equal row counts: table 0 has {} rows, table {} has {} rows",
                    expected_rows, i, table.n_rows
                ),
            });
        }
    }

    // Validate SuperArray length matches cube row count
    if super_array.len() != expected_rows {
        return Err(MinarrowError::ShapeError {
            message: format!(
                "SuperArray length ({}) doesn't match cube row count ({})",
                super_array.len(),
                expected_rows
            ),
        });
    }

    // Materialise SuperArray chunks into a single array for efficient broadcasting
    // Concatenate all chunks into one contiguous array
    let materialised_array = materialise_super_array(super_array)?;

    // Broadcast materialised array to each table in the cube
    let mut result_tables = Vec::with_capacity(cube.tables.len());
    for table in &cube.tables {
        let broadcasted = broadcast_array_to_table(op, &materialised_array, table)?;
        result_tables.push(broadcasted);
    }

    Ok(Cube::from_tables(result_tables, cube.name.clone(), cube.third_dim_index.clone()))
}

/// Broadcast Cube to SuperArray - apply super array to each table in the cube
#[cfg(all(feature = "cube", feature = "chunked"))]
pub fn broadcast_cube_to_superarray(
    op: ArithmeticOperator,
    cube: &Cube,
    super_array: &crate::SuperArray,
) -> Result<Cube, MinarrowError> {
    // Validate cube shape: all tables must have same row count
    let expected_rows = cube
        .tables
        .first()
        .ok_or_else(|| MinarrowError::ShapeError {
            message: "Cannot broadcast empty cube".to_string(),
        })?
        .n_rows;

    for (i, table) in cube.tables.iter().enumerate() {
        if table.n_rows != expected_rows {
            return Err(MinarrowError::ShapeError {
                message: format!(
                    "Cube tables must have equal row counts: table 0 has {} rows, table {} has {} rows",
                    expected_rows, i, table.n_rows
                ),
            });
        }
    }

    // Validate SuperArray length matches cube row count
    if super_array.len() != expected_rows {
        return Err(MinarrowError::ShapeError {
            message: format!(
                "SuperArray length ({}) doesn't match cube row count ({})",
                super_array.len(),
                expected_rows
            ),
        });
    }

    // Materialise SuperArray chunks into a single array for efficient broadcasting
    let materialised_array = materialise_super_array(super_array)?;

    // Broadcast each table to the materialised array
    let mut result_tables = Vec::with_capacity(cube.tables.len());
    for table in &cube.tables {
        let broadcasted = broadcast_table_to_array(op, table, &materialised_array)?;
        result_tables.push(broadcasted);
    }

    Ok(Cube::from_tables(result_tables, cube.name.clone(), cube.third_dim_index.clone()))
}

/// Broadcast SuperTable to Cube - apply super table to each table in the cube
#[cfg(all(feature = "cube", feature = "chunked"))]
pub fn broadcast_supertable_to_cube(
    op: ArithmeticOperator,
    super_table: &crate::SuperTable,
    cube: &Cube,
) -> Result<Cube, MinarrowError> {
    // Merge SuperTable batches into a single logical table
    let merged_table = merge_supertable_batches(super_table)?;

    // Broadcast the merged table against each cube table
    let mut result_tables = Vec::with_capacity(cube.tables.len());
    for cube_table in &cube.tables {
        let broadcasted =
            broadcast_table_with_operator(op, merged_table.clone(), cube_table.clone())?;
        result_tables.push(broadcasted);
    }

    Ok(Cube::from_tables(result_tables, cube.name.clone(), cube.third_dim_index.clone()))
}

/// Broadcast Cube to SuperTable - apply super table to each table in the cube
#[cfg(all(feature = "cube", feature = "chunked"))]
pub fn broadcast_cube_to_supertable(
    op: ArithmeticOperator,
    cube: &Cube,
    super_table: &crate::SuperTable,
) -> Result<Cube, MinarrowError> {
    // Merge SuperTable batches into a single logical table
    let merged_table = merge_supertable_batches(super_table)?;

    // Broadcast each cube table against the merged table
    let mut result_tables = Vec::with_capacity(cube.tables.len());
    for cube_table in &cube.tables {
        let broadcasted =
            broadcast_table_with_operator(op, cube_table.clone(), merged_table.clone())?;
        result_tables.push(broadcasted);
    }

    Ok(Cube::from_tables(result_tables, cube.name.clone(), cube.third_dim_index.clone()))
}

/// Broadcast SuperArrayView to Cube - apply super array view to each table in the cube
#[cfg(all(feature = "cube", feature = "chunked", feature = "views"))]
pub fn broadcast_superarrayview_to_cube(
    op: ArithmeticOperator,
    super_array_view: &crate::SuperArrayV,
    cube: &Cube,
) -> Result<Cube, MinarrowError> {
    use crate::kernels::broadcast::array::broadcast_array_to_table;

    // Validate cube shape
    let expected_rows = cube
        .tables
        .first()
        .ok_or_else(|| MinarrowError::ShapeError {
            message: "Cannot broadcast to empty cube".to_string(),
        })?
        .n_rows;

    for (i, table) in cube.tables.iter().enumerate() {
        if table.n_rows != expected_rows {
            return Err(MinarrowError::ShapeError {
                message: format!(
                    "Cube tables must have equal row counts: table 0 has {} rows, table {} has {} rows",
                    expected_rows, i, table.n_rows
                ),
            });
        }
    }

    // Validate SuperArrayView length
    if super_array_view.len != expected_rows {
        return Err(MinarrowError::ShapeError {
            message: format!(
                "SuperArrayView length ({}) doesn't match cube row count ({})",
                super_array_view.len, expected_rows
            ),
        });
    }

    // Materialise view slices using helper
    let materialised = materialise_super_array_view(super_array_view)?;

    // Broadcast to each table
    let mut result_tables = Vec::with_capacity(cube.tables.len());
    for table in &cube.tables {
        let broadcasted = broadcast_array_to_table(op, &materialised, table)?;
        result_tables.push(broadcasted);
    }

    Ok(Cube::from_tables(result_tables, cube.name.clone(), cube.third_dim_index.clone()))
}

/// Broadcast Cube to SuperArrayView - apply super array view to each table in the cube
#[cfg(all(feature = "cube", feature = "chunked", feature = "views"))]
pub fn broadcast_cube_to_superarrayview(
    op: ArithmeticOperator,
    cube: &Cube,
    super_array_view: &crate::SuperArrayV,
) -> Result<Cube, MinarrowError> {
    // Validate cube shape: all tables must have same row count
    let expected_rows = cube
        .tables
        .first()
        .ok_or_else(|| MinarrowError::ShapeError {
            message: "Cannot broadcast empty cube".to_string(),
        })?
        .n_rows;

    for (i, table) in cube.tables.iter().enumerate() {
        if table.n_rows != expected_rows {
            return Err(MinarrowError::ShapeError {
                message: format!(
                    "Cube tables must have equal row counts: table 0 has {} rows, table {} has {} rows",
                    expected_rows, i, table.n_rows
                ),
            });
        }
    }

    // Validate SuperArrayView length matches cube row count
    if super_array_view.len != expected_rows {
        return Err(MinarrowError::ShapeError {
            message: format!(
                "SuperArrayView length ({}) doesn't match cube row count ({})",
                super_array_view.len, expected_rows
            ),
        });
    }

    // Materialise view slices using helper
    let materialised = materialise_super_array_view(super_array_view)?;

    // Broadcast each table to the materialised array
    let mut result_tables = Vec::with_capacity(cube.tables.len());
    for table in &cube.tables {
        let broadcasted = broadcast_table_to_array(op, table, &materialised)?;
        result_tables.push(broadcasted);
    }

    Ok(Cube::from_tables(result_tables, cube.name.clone(), cube.third_dim_index.clone()))
}

/// Broadcast SuperTableView to Cube - apply super table view to each table in the cube
#[cfg(all(feature = "cube", feature = "chunked", feature = "views"))]
pub fn broadcast_supertableview_to_cube(
    op: ArithmeticOperator,
    super_table_view: &crate::SuperTableV,
    cube: &Cube,
) -> Result<Cube, MinarrowError> {
    // Merge SuperTableView slices into a single logical table
    let merged_table = merge_supertableview_slices(super_table_view)?;

    // Broadcast the merged table against each cube table
    let mut result_tables = Vec::with_capacity(cube.tables.len());
    for cube_table in &cube.tables {
        let broadcasted =
            broadcast_table_with_operator(op, merged_table.clone(), cube_table.clone())?;
        result_tables.push(broadcasted);
    }

    Ok(Cube::from_tables(result_tables, cube.name.clone(), cube.third_dim_index.clone()))
}

/// Broadcast Cube to SuperTableView - apply super table view to each table in the cube
#[cfg(all(feature = "cube", feature = "chunked", feature = "views"))]
pub fn broadcast_cube_to_supertableview(
    op: ArithmeticOperator,
    cube: &Cube,
    super_table_view: &crate::SuperTableV,
) -> Result<Cube, MinarrowError> {
    // Merge SuperTableView slices into a single logical table
    let merged_table = merge_supertableview_slices(super_table_view)?;

    // Broadcast each cube table against the merged table
    let mut result_tables = Vec::with_capacity(cube.tables.len());
    for cube_table in &cube.tables {
        let broadcasted =
            broadcast_table_with_operator(op, cube_table.clone(), merged_table.clone())?;
        result_tables.push(broadcasted);
    }

    Ok(Cube::from_tables(result_tables, cube.name.clone(), cube.third_dim_index.clone()))
}

#[cfg(all(test, feature = "cube"))]
mod tests {
    use super::*;
    use crate::traits::selection::ColumnSelection;
    use crate::{Array, FieldArray, IntegerArray, Table, vec64};

    fn create_test_table(name: &str, base_val: i32) -> Table {
        // Create a simple table with 2 columns and 2 rows
        let col1 = FieldArray::from_arr(
            "col1",
            Array::from_int32(IntegerArray::from_slice(&vec64![base_val, base_val + 1])),
        );
        let col2 = FieldArray::from_arr(
            "col2",
            Array::from_int32(IntegerArray::from_slice(&vec64![
                base_val * 10,
                (base_val + 1) * 10
            ])),
        );

        Table::new(format!("{}_{}", name, base_val), Some(vec![col1, col2]))
    }

    #[test]
    fn test_cube_addition() {
        // Create first cube with 2 tables
        let table1_a = create_test_table("table1", 1); // [1,2] and [10,20]
        let table2_a = create_test_table("table2", 3); // [3,4] and [30,40]
        let cube_a = Cube::from_tables(vec![table1_a, table2_a], "cubeA".to_string(), None);

        // Create second cube with 2 tables
        let table1_b = create_test_table("table1", 5); // [5,6] and [50,60]
        let table2_b = create_test_table("table2", 7); // [7,8] and [70,80]
        let cube_b = Cube::from_tables(vec![table1_b, table2_b], "cubeB".to_string(), None);

        // Perform addition
        let result = broadcast_cube_add(cube_a, cube_b, None).unwrap();

        assert_eq!(result.tables.len(), 2);
        assert_eq!(result.name, "cubeA"); // Takes name from left operand
        // Verify each result table has 2 rows
        assert!(result.tables.iter().all(|t| t.n_rows == 2));

        // Check first table: [1,2] + [5,6] = [6,8] and [10,20] + [50,60] = [60,80]
        let first_table = &result.tables[0];

        // Check first column of first table: [1,2] + [5,6] = [6,8]
        if let Some(col1) = first_table.col_ix(0) {
            if let crate::Array::NumericArray(crate::NumericArray::Int32(arr)) = &col1.array {
                assert_eq!(arr.data.as_slice(), &[6, 8]);
            } else {
                panic!("Expected Int32 array in first column");
            }
        } else {
            panic!("Could not get first column");
        }

        // Check second column of first table: [10,20] + [50,60] = [60,80]
        if let Some(col2) = first_table.col_ix(1) {
            if let crate::Array::NumericArray(crate::NumericArray::Int32(arr)) = &col2.array {
                assert_eq!(arr.data.as_slice(), &[60, 80]);
            } else {
                panic!("Expected Int32 array in second column");
            }
        } else {
            panic!("Could not get second column");
        }
    }

    #[test]
    #[should_panic(expected = "table count mismatch")]
    fn test_mismatched_table_count() {
        let table1_a = create_test_table("table1", 1);
        let cube_a = Cube::from_tables(vec![table1_a], "cubeA".to_string(), None); // 1 table

        let table1_b = create_test_table("table1", 5);
        let table2_b = create_test_table("table2", 7);
        let cube_b = Cube::from_tables(vec![table1_b, table2_b], "cubeB".to_string(), None); // 2 tables

        let _ = broadcast_cube_add(cube_a, cube_b, None).unwrap();
    }
}