matrw 0.1.4

MAT-file serializing and deserializing
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
//! Module defining enum [`MatVariable`], which describes different MAT-file variable types.

use paste::paste;
use std::fmt::{Debug, Display};
use std::ops;

use crate::check_same_fields;
use crate::interface::index::Index;
use crate::interface::types::array::ArrayType;
use crate::interface::types::cell_array::CellArray;
use crate::interface::types::compressed_array::CompressedArray;
use crate::interface::types::matlab_types::{MatlabType, MatlabTypeMarker};
use crate::interface::types::numeric_array::NumericArray;
use crate::interface::types::sparse_array::SparseArray;
use crate::interface::types::structure::Structure;
use crate::interface::types::structure_array::StructureArray;
use crate::parser::v7::types::compressed_array::CompressedArray7;
use crate::parser::v7::variable7::MatVariable7;

/// MAT-file variable wrapper
#[derive(Debug, Clone)]
pub enum MatVariable {
    ///
    /// Full (dense) numeric arrays of arbitrary dimensions. Can contain the numeric types (`i8`, `i16`, `i32`, `i64`, `u8`, `u16`, `u32`, `u64`, `f32`, `f64`) and the character type (`char`).
    ///
    /// # Examples
    ///
    /// 1x1 `f64` scalar
    /// ```
    /// # use matrw::matvar;
    /// // Matlab: x1 = 1.;
    /// let x1 = matvar!(1.);
    /// ```
    ///
    /// 1x1 `u8` scalar
    /// ```
    /// # use matrw::matvar;
    /// // Matlab: x1u8 = uint8(1);
    /// let x1u8 = matvar!(1_u8);
    /// ```
    ///
    /// 1x2 `f64` vector
    /// ```
    /// # use matrw::matvar;
    /// // Matlab: x2 = [1.0, 2.0];
    /// let x2 = matvar!([1.0, 2.0]);
    /// ```
    ///
    /// 2x2 `f64` matrix
    /// ```
    /// # use matrw::matvar;
    /// // Matlab: x3 = [1.0, 2.0; 3.0, 4.0];
    /// let x3 = matvar!([[1.0, 2.0], [3.0, 4.0]]);
    /// ```
    ///
    /// 2x2x2 `f64` array
    /// ```
    /// # use matrw::matvar;
    /// // Matlab:
    /// // x4(:,:,1) = [1.0, 2.0; 3.0, 4.0];
    /// // x4(:,:,2) = [10.0, 20.0; 30.0, 40.0];
    /// let x4 = matvar!([
    ///     [[1.0, 2.0], [3.0, 4.0]],
    ///     [[10.0, 20.0], [30.0, 40.0]],
    ///     ]);
    /// ```
    ///
    /// # Conversion
    ///
    /// `NumericArray` data can be explicitly converted
    /// into
    /// - scalar types,
    /// - [`Vec`] types,
    ///
    /// For example, `f64` data can be converted by
    /// - [`MatVariable::to_f64`], to return the first value of the data as scalar,
    /// - [`MatVariable::to_vec_f64`], to return a clone of the variable data,
    ///
    /// ```
    /// # use matrw::{matvar};
    /// let a = matvar!(42.);
    ///
    /// let val: Vec<f64> = a.to_vec_f64().unwrap();
    ///
    /// // Variable "a" contains f64 data, so explicit conversion to f32 fails
    /// assert!(a.to_vec_f32().is_none());
    /// ```
    ///
    /// Equivalent methods exist for conversion of other Rust types.
    ///
    /// <div class="warning">
    /// Explicit conversion only works if the method used matches the data, e.g. MAT-file "double" data must be read using *vec_f64() methods, otherwise None is returned.
    /// </div>
    ///
    /// The type of a numeric variable, [`MatlabType`], can be determined with the method [`MatVariable::numeric_type`].
    /// ```
    /// # use matrw::{matvar};
    /// let a = matvar!(42.);
    ///
    /// assert!(matches!(a.numeric_type().unwrap(), matrw::MatlabType::F64(_)));
    /// ```
    ///
    /// # Indexing
    ///
    /// Indexing into [`MatVariable::NumericArray`] is done with [`OwnedIndex::elem`] which
    /// returns a dynamically constructed 1x1 [`MatVariable::NumericArray`] containing the element data.
    /// The index trait [`std::ops::Index`] can't be used here, because it can only return references.
    ///
    /// ```
    /// use matrw::{matfile, matvar, OwnedIndex};
    ///
    /// let a = matvar!([1, 2, 3, 4]);
    /// assert_eq!(a.elem(0).to_i32(), Some(1));
    /// assert_eq!(a.elem(1).to_i32(), Some(2));
    /// assert_eq!(a.elem(2).to_i32(), Some(3));
    /// assert_eq!(a.elem(3).to_i32(), Some(4));
    ///
    /// let b = matvar!([[1, 2], [3, 4]]);
    /// // Indexing via 2D tuple ...
    /// assert_eq!(b.elem([0,0]).to_i32(), Some(1));
    /// assert_eq!(b.elem([0,1]).to_i32(), Some(2));
    /// assert_eq!(b.elem([1,0]).to_i32(), Some(3));
    /// assert_eq!(b.elem([1,1]).to_i32(), Some(4));
    /// // ... or 1D column-major index
    /// assert_eq!(b.elem(0).to_i32(), Some(1));
    /// assert_eq!(b.elem(1).to_i32(), Some(3));
    /// assert_eq!(b.elem(2).to_i32(), Some(2));
    /// assert_eq!(b.elem(3).to_i32(), Some(4));
    /// ```
    ///
    NumericArray(NumericArray),
    ///
    /// Sparse arrays of dimension 2. Can contain numeric types `f64` or `bool`.
    ///
    /// # Examples
    ///
    /// 1x1 sparse `f64`
    /// ```
    /// # use matrw::matvar;
    /// // Matlab: x1 = sparse(1.);
    /// let x1 = matvar!(1.).to_sparse();
    /// ```
    ///
    /// 10x1 sparse `f64`
    /// ```
    /// # use matrw::matvar;
    /// // Matlab: x2 = sparse([1, 10], [1, 1], [42., 43.]);
    /// let x2 = matvar!([42., 0., 0., 0., 0., 0., 0., 0., 0., 43.]).to_sparse();
    /// ```
    ///
    /// # Indexing
    ///
    /// Indexing into [`MatVariable::SparseArray`] is done with [`OwnedIndex::elem`] which
    /// returns a dynamically constructed 1x1 [`MatVariable::NumericArray`] containing the element data.
    /// The index trait [`std::ops::Index`] can't be used here, because it can only return references.
    ///
    /// ```
    /// # use matrw::{matfile, matvar, OwnedIndex};
    /// #
    /// let b = matvar!([[1.0, 2.0], [3.0, 4.0]]).to_sparse().unwrap();
    ///
    /// // Indexing via 2D tuple
    /// assert_eq!(b.elem([0,0]).to_f64(), Some(1.0));
    /// assert_eq!(b.elem([0,1]).to_f64(), Some(2.0));
    /// assert_eq!(b.elem([1,0]).to_f64(), Some(3.0));
    /// assert_eq!(b.elem([1,1]).to_f64(), Some(4.0));
    /// ```
    ///
    SparseArray(SparseArray),
    ///
    /// Key-value structures in arrays of arbitrary dimensions.
    ///
    /// # Examples
    /// ```
    /// # use matrw::matvar;
    /// // Matlab:
    /// // s = [
    /// //      struct('a', 1., 'b', 2.),
    /// //      struct('a', 42., 'b', 43.)
    /// //      ];
    /// let s = matvar!([
    ///         { a: 1.0, b: 2.0 },
    ///         { a: 42.0, b: 43.0 },
    ///         ]);
    /// ```
    ///
    /// # Indexing
    ///
    /// ```
    /// # use matrw::matvar;
    /// #
    /// # let var = matvar!([
    /// #         {
    /// #             a: 1.0,
    /// #             b: 2.0,
    /// #         },
    /// #         {
    /// #             a: 42.0,
    /// #             b: 43.0,
    /// #         },
    /// #         ]);
    /// // Get field b of the second array element
    /// assert_eq!(var[1]["b"], matvar!(43.));
    /// ```
    ///
    StructureArray(StructureArray),
    ///
    /// Contains mixed MatVariable kinds in arrays of arbitrary dimensions.
    ///
    /// # Example
    ///
    /// ```
    /// // Matlab: c = { 'some text', struct('a', 42.0, 'b', 43.0) };
    /// # use matrw::matvar;
    /// #
    /// let c = matvar!([
    ///         "some text",
    ///         { a: 42.0, b: 43.0 },
    ///         ]);
    /// ```
    ///
    /// # Indexing
    ///
    /// ```
    /// # use matrw::matvar;
    /// #
    /// # let c = matvar!([
    /// #         "some text",
    /// #         { a: 42.0, b: 43.0 },
    /// #         ]);
    /// assert_eq!(c[0], matvar!("some text"));
    /// assert_eq!(c[1]["a"], matvar!(42.0));
    /// assert_eq!(c[1]["b"], matvar!(43.0));
    /// ```
    ///
    CellArray(CellArray),
    // ------------------------
    ///
    /// Support type describing scalar structure. Used in [`MatVariable::StructureArray`].
    ///
    /// # Example
    ///
    /// ```
    /// // Matlab: s = struct('a', 42.0, 'b', 43.0);
    /// # use matrw::matvar;
    /// #
    /// let s = matvar!(
    ///         { a: 42.0, b: 43.0 }
    ///         );
    /// ```
    ///
    /// # Indexing
    ///
    /// ```
    /// # use matrw::matvar;
    /// #
    /// let s = matvar!(
    ///         { a: 42.0, b: 43.0 }
    ///         );
    /// assert_eq!(s["a"], matvar!(42.0));
    /// assert_eq!(s["b"], matvar!(43.0));
    /// ```
    ///
    Structure(Structure),
    ///
    /// Null type used as return type for non-existing index
    ///
    /// # Example
    ///
    /// ```
    /// # use matrw::{matvar, MatVariable};
    /// #
    /// let s = matvar!(
    ///         { a: 42.0, b: 43.0 }
    ///         );
    /// assert_eq!(s["a"], matvar!(42.0));
    /// assert_eq!(s["b"], matvar!(43.0));
    /// // Index "c" does not exist
    /// assert!(matches!(s["c"], MatVariable::Null));
    /// ```
    ///
    ///
    Null,
    ///
    /// Wrapper type which applies compression on write when using option `compress=true` in function
    /// [`crate::save_matfile_v7`].
    ///
    /// <div class="warning">
    /// This type is used implicitly. It should not be used manually.
    /// </div>
    ///
    Compressed(CompressedArray),
    ///
    /// Support type used for description of unsupported types.
    ///
    Unsupported,
}

impl MatVariable {
    /// Get array dimensions.
    ///
    /// # Example
    ///
    /// ```
    /// # use matrw::matvar;
    /// let var = matvar!([[1.0, 2.0], [42.0, 43.0]]);
    ///
    /// assert_eq!(var.dim(), vec![2, 2]);
    /// ```
    ///
    pub fn dim(&self) -> Vec<usize> {
        match self {
            MatVariable::NumericArray(val) => val.dim.clone(),
            MatVariable::CellArray(val) => val.dim.clone(),
            MatVariable::Structure(_) => vec![1, 1],
            MatVariable::StructureArray(val) => val.dim.clone(),
            MatVariable::SparseArray(val) => val.dim.clone(),
            _ => unimplemented!(),
        }
    }

    /// If [`MatVariable`] is of type [`MatVariable::NumericArray`] or
    /// [`MatVariable::SparseArray`], return numeric type. Otherwise [`None`].
    ///
    /// # Example
    ///
    /// ```
    /// # use matrw::matvar;
    /// let var = matvar!([[1.0, 2.0], [42.0, 43.0]]);
    ///
    /// assert!(matches!(var.numeric_type().unwrap(), matrw::MatlabType::F64(_)));
    /// ```
    ///
    pub fn numeric_type(&self) -> Option<&MatlabType> {
        match self {
            MatVariable::NumericArray(val) => Some(val.numeric_type()),
            MatVariable::SparseArray(val) => Some(val.numeric_type()),
            _ => None,
        }
    }

    /// If [`MatVariable`] is of type [`MatVariable::Structure`] or
    /// [`MatVariable::StructureArray`], return field names. Otherwise [`None`].
    ///
    /// # Example
    ///
    /// ```
    /// # use matrw::matvar;
    /// let var = matvar!({ a: 1., b: 2. });
    ///
    /// assert_eq!(var.fieldnames(), Some(vec!["a".to_string(), "b".to_string()]));
    /// ```
    ///
    pub fn fieldnames(&self) -> Option<Vec<String>> {
        match self {
            MatVariable::Structure(val) => Some(val.fieldnames()),
            MatVariable::StructureArray(val) => Some(val.fieldnames()),
            _ => None,
        }
    }

    /// If [`MatVariable`] is of type [`MatVariable::NumericArray`] or
    /// [`MatVariable::SparseArray`], return if variable is complex. Otherwise [`None`].
    ///
    /// # Example
    ///
    /// ```
    /// # use matrw::matvar;
    /// let var = matvar!(1.0);
    ///
    /// assert_eq!(var.is_complex(), Some(false));
    /// ```
    ///
    pub fn is_complex(&self) -> Option<bool> {
        match self {
            MatVariable::NumericArray(val) => Some(val.is_complex()),
            MatVariable::SparseArray(val) => Some(val.is_complex()),
            _ => None,
        }
    }

    /// If [`MatVariable`] is of type [`MatVariable::NumericArray`],
    /// return real part as scalar value. Otherwise, returns [`None`].
    ///
    /// If `NumericArray` contains more than one value, the first value is returned.
    ///
    /// # Example
    ///
    /// ```
    /// # use matrw::matvar;
    /// let var = matvar!(1.0);
    ///
    /// assert_eq!(var.to_scalar(), Some(1.0));
    /// ```
    ///
    pub fn to_scalar<T: MatlabTypeMarker>(&self) -> Option<T> {
        match self {
            MatVariable::NumericArray(val) => val.real_to_scalar(),
            _ => None,
        }
    }

    /// If [`MatVariable`] is of type [`MatVariable::NumericArray`],
    /// return complex part as scalar value. Otherwise, returns [`None`].
    ///
    /// If `NumericArray` contains more than one value, the first value is returned.
    ///
    /// # Example
    ///
    /// ```
    /// # use matrw::matvar;
    /// let var = matvar!((1.0, 42.0));
    ///
    /// assert_eq!(var.comp_to_scalar(), Some(42.0));
    /// ```
    ///
    pub fn comp_to_scalar<T: MatlabTypeMarker>(&self) -> Option<T> {
        match self {
            MatVariable::NumericArray(val) => val.comp_to_scalar(),
            _ => None,
        }
    }

    /// If [`MatVariable`] is of type [`MatVariable::NumericArray`],
    /// return cloned inner real `Vec`. Otherwise, returns [`None`].
    ///
    /// # Example
    ///
    /// ```
    /// # use matrw::matvar;
    /// let var = matvar!([1.0, 2.0, 3.0]);
    ///
    /// assert_eq!(var.to_vec(), Some(vec![1.0, 2.0, 3.0]));
    /// ```
    ///
    pub fn to_vec<T: MatlabTypeMarker>(&self) -> Option<Vec<T>> {
        match self {
            MatVariable::NumericArray(val) => val.real_to_vec(),
            _ => None,
        }
    }

    /// If [`MatVariable`] is of type [`MatVariable::NumericArray`],
    /// return cloned inner complex `Vec`. Otherwise, returns [`None`].
    ///
    /// # Example
    ///
    /// ```
    /// # use matrw::matvar;
    /// let var = matvar!([(1.0, 42.), (2.0, 43.), (3.0, 44.)]);
    ///
    /// assert_eq!(var.comp_to_vec(), Some(vec![42.0, 43.0, 44.0]));
    /// ```
    ///
    pub fn comp_to_vec<T: MatlabTypeMarker>(&self) -> Option<Vec<T>> {
        match self {
            MatVariable::NumericArray(val) => val.comp_to_vec(),
            _ => None,
        }
    }

    /// If [`MatVariable`] is of type [`MatVariable::NumericArray`],
    /// return sparse transformation. Otherwise, returns [`None`].
    ///
    /// # Example
    ///
    /// ```
    /// # use matrw::{matvar, OwnedIndex};
    /// let var = matvar!([1.0, 2.0, 3.0]).to_sparse().unwrap();
    ///
    /// assert_eq!(var.elem(0), matvar!(1.0));
    /// assert_eq!(var.elem(1), matvar!(2.0));
    /// assert_eq!(var.elem(2), matvar!(3.0));
    /// ```
    ///
    pub fn to_sparse(self) -> Option<MatVariable> {
        match self {
            MatVariable::NumericArray(val) => val.to_sparse(),
            _ => None,
        }
    }

    /// Return iterator over all elements in column-major order.
    ///
    /// # Example
    ///
    /// ```
    /// # use matrw::{matvar, OwnedIndex};
    /// let var = matvar!([[1.0, 2.0], [42.0, 43.0]]);
    /// let mut var_iter = var.iter();
    ///
    /// assert_eq!(var_iter.next(), Some(matvar!(1.0)));
    /// assert_eq!(var_iter.next(), Some(matvar!(42.0)));
    /// assert_eq!(var_iter.next(), Some(matvar!(2.0)));
    /// assert_eq!(var_iter.next(), Some(matvar!(43.0)));
    /// ```
    ///
    pub fn iter(&self) -> MatVariableIterator<'_> {
        MatVariableIterator::new(self)
    }
}

macro_rules! impl_MatVariable_to {
    ($($ret: ty),*) => {
        paste! {
            $(
            //
            // to_<$ret>
            //
            #[doc = concat!("If [`MatVariable`] is of type [`MatVariable::NumericArray`], returns copied `", stringify!($ret),"`. Otherwise, returns [`None`].")]
            pub fn [<to_ $ret>](&self) -> Option<$ret> {
                match self {
                    MatVariable::NumericArray(val) if val.is_scalar() => val.real_to_scalar(),
                    _ => None,
                }
            }
            )*
        }
    };
}

macro_rules! impl_MatVariable_comp_to {
    ($($ret: ty),*) => {
        paste! {
            $(
            //
            // comp_to_<$ret>
            //
            #[doc = concat!("If [`MatVariable`] is of type [`MatVariable::NumericArray`], returns copied `", stringify!($ret),"`. Otherwise, returns [`None`].")]
            pub fn [<comp_to_ $ret>](&self) -> Option<$ret> {
                match self {
                    MatVariable::NumericArray(val) if val.is_scalar() => val.comp_to_scalar(),
                    _ => None,
                }
            }
            )*
        }
    };
}

macro_rules! impl_MatVariable_to_vec {
    ($($ret: ty),*) => {
        paste! {
            $(
            //
            // to_vec_<$ret>
            //
            #[doc = concat!("If [`MatVariable`] is of type [`MatVariable::NumericArray`], returns cloned `Vec<", stringify!($ret),">`. Otherwise, returns [`None`].")]
            pub fn [<to_vec_ $ret>](&self) -> Option<Vec<$ret>> {
                match self {
                    MatVariable::NumericArray(val) => val.real_to_vec::<$ret>(),
                    _ => None,
                }
            }
            )*
        }
    };
}

macro_rules! impl_MatVariable_comp_to_vec {
    ($($ret: ty),*) => {
        paste! {
            $(
            //
            // comp_to_vec_<$ret>
            //
            #[doc = concat!("If [`MatVariable`] is of type [`MatVariable::NumericArray`], returns complex part as cloned `Vec<", stringify!($ret),">`. Otherwise, returns [`None`].")]
            pub fn [<comp_to_vec_ $ret>](&self) -> Option<Vec<$ret>> {
                match self {
                    MatVariable::NumericArray(val) => val.comp_to_vec::<$ret>(),
                    _ => None,
                }
            }
            )*
        }
    };
}

impl MatVariable {
    impl_MatVariable_to!(u8, i8, u16, i16, u32, i32, u64, i64, f32, f64, char, bool);
    impl_MatVariable_comp_to!(u8, i8, u16, i16, u32, i32, u64, i64, f32, f64, char, bool);
    impl_MatVariable_to_vec!(u8, i8, u16, i16, u32, i32, u64, i64, f32, f64, char, bool);
    impl_MatVariable_comp_to_vec!(u8, i8, u16, i16, u32, i32, u64, i64, f32, f64, char, bool);
}

// ============================================================================
// Index
// ============================================================================

pub trait OwnedIndex<Idx> {
    type Output;
    fn elem(&self, index: Idx) -> Self::Output;
}

static NULL: MatVariable = MatVariable::Null;

impl<T> OwnedIndex<T> for MatVariable
where
    T: Index,
{
    type Output = MatVariable;

    fn elem(&self, index: T) -> Self::Output {
        index.index_into_clone(self).unwrap_or(NULL.clone())
    }
}

impl<T> ops::Index<T> for MatVariable
where
    T: Index,
{
    type Output = MatVariable;

    fn index(&self, index: T) -> &Self::Output {
        index.index_into_ref(self).unwrap_or(&NULL)
    }
}

// ============================================================================
// Iterator
// ============================================================================

pub struct MatVariableIterator<'a> {
    var: &'a MatVariable,
    count: usize,
}

impl<'a> MatVariableIterator<'a> {
    fn new(var: &'a MatVariable) -> Self {
        Self { var, count: 0 }
    }
}

impl<'a> Iterator for MatVariableIterator<'a> {
    type Item = MatVariable;

    fn next(&mut self) -> Option<Self::Item> {
        match self.var {
            MatVariable::NumericArray(v) => {
                let ret = if self.count < v.value.len() {
                    Some(v.get_clone_colmaj(self.count).unwrap())
                } else {
                    None
                };
                self.count += 1;
                ret
            }
            _ => todo!(),
        }
    }
}

pub struct MatVariableIntoIterator {
    var: MatVariable,
    count: usize,
}

impl Iterator for MatVariableIntoIterator {
    type Item = MatVariable;

    fn next(&mut self) -> Option<Self::Item> {
        match &self.var {
            MatVariable::NumericArray(v) => {
                let ret = if self.count < v.value.len() {
                    Some(v.get_clone_colmaj(self.count).unwrap())
                } else {
                    None
                };
                self.count += 1;
                ret
            }
            _ => todo!(),
        }
    }
}

impl IntoIterator for MatVariable {
    type Item = MatVariable;
    type IntoIter = MatVariableIntoIterator;

    fn into_iter(self) -> Self::IntoIter {
        match &self {
            MatVariable::NumericArray(_) => MatVariableIntoIterator { var: self, count: 0 },
            _ => todo!(),
        }
    }
}

// ============================================================================
// From
// ============================================================================

/// Create a `MatVariable` from `&str`.
///
/// # Example
///
/// ```
/// # use matrw::MatVariable;
/// let s = MatVariable::from("test");
/// ```
impl From<&str> for MatVariable {
    fn from(value: &str) -> Self {
        MatVariable::NumericArray(NumericArray::from(value))
    }
}

/// Create a `MatVariable` from `Vec<T>`.
///
/// # Example
///
/// ```
/// # use matrw::MatVariable;
/// let s = MatVariable::from(vec![1.,2.,3.]);
/// ```
impl<T> From<Vec<T>> for MatVariable
where
    T: MatlabTypeMarker,
{
    fn from(value: Vec<T>) -> Self {
        MatVariable::NumericArray(
            NumericArray::new(vec![1, value.len()], MatlabType::from(value), None)
                .expect("Could not create NumericArray."),
        )
    }
}

/// Create a `MatVariable` from `Vec<(T, T)>`.
///
/// # Example
///
/// ```
/// # use matrw::MatVariable;
/// let s = MatVariable::from(vec![(1., 1.), (2., 1.), (3., 1.)]);
/// ```
impl<T> From<Vec<(T, T)>> for MatVariable
where
    T: MatlabTypeMarker,
{
    fn from(value: Vec<(T, T)>) -> Self {
        let real = value.iter().map(|x| x.0).collect::<Vec<T>>();
        let comp = value.iter().map(|x| x.1).collect::<Vec<T>>();

        MatVariable::NumericArray(
            NumericArray::new(
                vec![1, value.len()],
                MatlabType::from(real),
                Some(MatlabType::from(comp)),
            )
            .expect("Could not create NumericArray."),
        )
    }
}

/// Create a `MatVariable` from `T`.
///
/// # Example
///
/// ```
/// # use matrw::MatVariable;
/// let s = MatVariable::from(1.);
/// ```
impl<T> From<T> for MatVariable
where
    T: MatlabTypeMarker,
{
    fn from(value: T) -> Self {
        MatVariable::NumericArray(
            NumericArray::new(vec![1, 1], MatlabType::from(vec![value]), None)
                .expect("Could not create NumericArray."),
        )
    }
}

/// Create a `MatVariable` from `(T, T)`.
///
/// # Example
///
/// ```
/// # use matrw::MatVariable;
/// let s = MatVariable::from((1., 1.));
/// ```
impl<T> From<(T, T)> for MatVariable
where
    T: MatlabTypeMarker,
{
    fn from(value: (T, T)) -> Self {
        MatVariable::NumericArray(
            NumericArray::new(
                vec![1, 1],
                MatlabType::from(vec![value.0]),
                Some(MatlabType::from(vec![value.1])),
            )
            .expect("Could not create NumericArray."),
        )
    }
}

/// Create a `MatVariable` from `Vec<MatVariable>`
///
/// If vector contains `n` structs of same topology, create `1xn` [`MatVariable::StructureArray`],
/// otherwise create `1xn` [`MatVariable::CellArray`].
///
/// # Example
///
/// ```
/// # use matrw::{MatVariable, matvar};
/// let vec: Vec<MatVariable> = vec![
///     matvar!({
///         a: 1,
///         b: 2,
///     }),
///     matvar!({
///         a: 42,
///         b: 43,
///     })
/// ];
///
/// let var: MatVariable = vec.into();
/// ```
impl From<Vec<MatVariable>> for MatVariable {
    fn from(value: Vec<MatVariable>) -> Self {
        // If inputs are structs with all equal fieldnames, make a struct array,
        // otherwise make a cell array.
        if value.iter().all(|x| matches!(x, MatVariable::Structure(_))) && check_same_fields(&value) {
            MatVariable::StructureArray(StructureArray::from_structures(vec![1, value.len()], value))
        } else {
            MatVariable::CellArray(CellArray::new(vec![1, value.len()], value).unwrap())
        }
    }
}

impl From<MatVariable7> for MatVariable {
    fn from(value: MatVariable7) -> Self {
        match value {
            MatVariable7::Compressed(v) => MatVariable::from(v),
            MatVariable7::Numeric(v) => MatVariable::NumericArray(NumericArray::from(v)),
            MatVariable7::Cell(v) => MatVariable::CellArray(CellArray::from(v)),
            MatVariable7::Structure(v) => MatVariable::Structure(Structure::from(v)),
            MatVariable7::StructureArray(v) => MatVariable::StructureArray(StructureArray::from(v)),
            MatVariable7::Sparse(v) => MatVariable::SparseArray(SparseArray::from(v)),
            MatVariable7::ObjectMCOS(_) => MatVariable::Unsupported,
            MatVariable7::ObjectHandle(_) => MatVariable::Unsupported,
            MatVariable7::Empty(_) => MatVariable::NumericArray(
                NumericArray::new(vec![0, 0], MatlabType::new(), None)
                    .expect("Could not create NumericArray."),
            ),
        }
    }
}

impl From<CompressedArray7> for MatVariable {
    fn from(value: CompressedArray7) -> Self {
        match value.value() {
            MatVariable7::Compressed(v) => MatVariable::from(v),
            MatVariable7::Numeric(v) => MatVariable::NumericArray(NumericArray::from(v)),
            MatVariable7::Cell(v) => MatVariable::CellArray(CellArray::from(v)),
            MatVariable7::Structure(v) => MatVariable::Structure(Structure::from(v)),
            MatVariable7::StructureArray(v) => MatVariable::StructureArray(StructureArray::from(v)),
            MatVariable7::Sparse(v) => MatVariable::SparseArray(SparseArray::from(v)),
            MatVariable7::ObjectMCOS(_) => MatVariable::Unsupported,
            MatVariable7::ObjectHandle(_) => MatVariable::Unsupported,
            MatVariable7::Empty(_) => MatVariable::NumericArray(
                NumericArray::new(vec![0, 0], MatlabType::new(), None)
                    .expect("Could not create NumericArray."),
            ),
        }
    }
}

// ============================================================================
// Other trait implementations
// ============================================================================

impl Display for MatVariable {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MatVariable::NumericArray(v) => write!(f, "{}", v),
            MatVariable::CellArray(_v) => todo!(),
            MatVariable::Structure(_v) => todo!(),
            MatVariable::StructureArray(_v) => todo!(),
            MatVariable::SparseArray(v) => write!(f, "{}", v),
            MatVariable::Null => todo!(),
            MatVariable::Compressed(_v) => todo!(),
            MatVariable::Unsupported => todo!(),
        }
    }
}

#[allow(unused)]
impl PartialEq for MatVariable {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::NumericArray(l0), Self::NumericArray(r0)) => l0 == r0,
            (Self::CellArray(l0), Self::CellArray(r0)) => todo!(),
            (Self::Structure(l0), Self::Structure(r0)) => todo!(),
            (Self::StructureArray(l0), Self::StructureArray(r0)) => todo!(),
            (Self::SparseArray(l0), Self::SparseArray(r0)) => todo!(),
            (Self::Compressed(l0), Self::Compressed(r0)) => todo!(),
            _ => core::mem::discriminant(self) == core::mem::discriminant(other),
        }
    }
}

// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn print_variable_size() {
        println!("MatVariable size: {}", size_of::<MatVariable>());
    }
}