qfall-math 0.1.1

Mathematical foundations for rapid prototyping of lattice-based cryptography
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
// Copyright © 2023 Marcel Luca Schmidt, Niklas Siemer
//
// This file is part of qFALL-math.
//
// qFALL-math is free software: you can redistribute it and/or modify it under
// the terms of the Mozilla Public License Version 2.0 as published by the
// Mozilla Foundation. See <https://mozilla.org/en-US/MPL/2.0/>.

//! Implementation to manipulate a [`MatQ`] matrix.

use crate::{
    error::MathError,
    rational::{MatQ, Q},
    traits::{MatrixDimensions, MatrixSetEntry, MatrixSetSubmatrix, MatrixSwaps},
    utils::index::{evaluate_index_for_vector, evaluate_indices_for_matrix},
};
use flint_sys::{
    fmpq::{fmpq_set, fmpq_swap},
    fmpq_mat::{
        fmpq_mat_entry, fmpq_mat_invert_cols, fmpq_mat_invert_rows, fmpq_mat_set,
        fmpq_mat_swap_cols, fmpq_mat_swap_rows, fmpq_mat_window_clear, fmpq_mat_window_init,
    },
};
use std::{
    fmt::Display,
    mem::MaybeUninit,
    ptr::{null, null_mut},
};

impl<Rational: Into<Q>> MatrixSetEntry<Rational> for MatQ {
    /// Sets the value of a specific matrix entry according to a given `value`
    /// that implements [`Into<Q>`] without checking whether the coordinate is part of the matrix.
    ///
    /// Parameters:
    /// - `row`: specifies the row in which the entry is located
    /// - `column`: specifies the column in which the entry is located
    /// - `value`: specifies the value to which the entry is set
    ///
    /// # Safety
    /// To use this function safely, make sure that the selected entry is part
    /// of the matrix. If it is not, memory leaks, unexpected panics, etc. might
    /// occur.
    ///
    /// # Examples
    /// ```
    /// use qfall_math::rational::MatQ;
    /// use qfall_math::rational::Q;
    /// use qfall_math::traits::*;
    ///
    /// let mut matrix = MatQ::new(3, 3);
    /// let value = Q::from((5, 2));
    ///
    /// unsafe {
    ///     matrix.set_entry_unchecked(0, 1, &value);
    ///     matrix.set_entry_unchecked(2, 2, 5);
    ///     matrix.set_entry_unchecked(0, 2, (2, 3));
    /// }
    ///
    /// assert_eq!("[[0, 5/2, 2/3],[0, 0, 0],[0, 0, 5]]", matrix.to_string());
    /// ```
    unsafe fn set_entry_unchecked(&mut self, row: i64, column: i64, value: Rational) {
        let value: Q = value.into();

        unsafe {
            let entry = fmpq_mat_entry(&self.matrix, row, column);
            fmpq_set(entry, &value.value)
        };
    }
}

impl MatrixSetSubmatrix for MatQ {
    /// Sets the matrix entries in `self` to entries defined in `other`.
    /// The entries in `self` starting from `(row_self_start, col_self_start)` up to
    /// `(row_self_end, col_self_end)`are set to be
    /// the entries from the submatrix from `other` defined by `(row_other_start, col_other_start)`
    /// to `(row_other_end, col_other_end)` (exclusively).
    ///
    /// Parameters:
    /// `row_self_start`: the starting row of the matrix in which to set a submatrix
    /// `col_self_start`: the starting column of the matrix in which to set a submatrix
    /// `other`: the matrix from where to take the submatrix to set
    /// `row_other_start`: the starting row of the specified submatrix
    /// `col_other_start`: the starting column of the specified submatrix
    /// `row_other_end`: the ending row of the specified submatrix
    /// `col_other_end`:the ending column of the specified submatrix
    ///
    /// # Examples
    /// ```
    /// use qfall_math::{rational::MatQ, traits::MatrixSetSubmatrix};
    /// use std::str::FromStr;
    ///
    /// let mut mat = MatQ::identity(3, 3);
    ///
    /// mat.set_submatrix(0, 1, &mat.clone(), 0, 0, 1, 1).unwrap();
    /// // [[1,1,0],[0,0,1],[0,0,1]]
    /// let mat_cmp = MatQ::from_str("[[1, 1, 0],[0, 0, 1],[0, 0, 1]]").unwrap();
    /// assert_eq!(mat, mat_cmp);
    ///
    /// unsafe{ mat.set_submatrix_unchecked(2, 0, 3, 2, &mat.clone(), 0, 0, 1, 2) };
    /// let mat_cmp = MatQ::from_str("[[1, 1, 0],[0, 0, 1],[1, 1, 1]]").unwrap();
    /// assert_eq!(mat, mat_cmp);
    /// ```
    ///
    /// # Safety
    /// To use this function safely, make sure that the selected submatrices are part
    /// of the matrices, the submatrices are of the same dimensions and the base types are the same.
    /// If not, memory leaks, unexpected panics, etc. might occur.
    unsafe fn set_submatrix_unchecked(
        &mut self,
        row_self_start: i64,
        col_self_start: i64,
        row_self_end: i64,
        col_self_end: i64,
        other: &Self,
        row_other_start: i64,
        col_other_start: i64,
        row_other_end: i64,
        col_other_end: i64,
    ) {
        let mut window_self = MaybeUninit::uninit();
        // The memory for the elements of window is shared with self.
        unsafe {
            fmpq_mat_window_init(
                window_self.as_mut_ptr(),
                &self.matrix,
                row_self_start,
                col_self_start,
                row_self_end,
                col_self_end,
            )
        };
        let mut window_other = MaybeUninit::uninit();
        // The memory for the elements of window is shared with other.
        unsafe {
            fmpq_mat_window_init(
                window_other.as_mut_ptr(),
                &other.matrix,
                row_other_start,
                col_other_start,
                row_other_end,
                col_other_end,
            )
        };
        unsafe {
            // TODO: this should not be mutable for the other window
            fmpq_mat_set(window_self.as_mut_ptr(), window_other.as_mut_ptr());

            // Clears the matrix window and releases any memory that it uses. Note that
            // the memory to the underlying matrix that window points to is not freed
            fmpq_mat_window_clear(window_self.as_mut_ptr());
            fmpq_mat_window_clear(window_other.as_mut_ptr());
        }
    }
}

impl MatrixSwaps for MatQ {
    /// Swaps two entries of the specified matrix.
    ///
    /// Parameters:
    /// - `row_0`: specifies the row, in which the first entry is located
    /// - `col_0`: specifies the column, in which the first entry is located
    /// - `row_1`: specifies the row, in which the second entry is located
    /// - `col_1`: specifies the column, in which the second entry is located
    ///
    /// Negative indices can be used to index from the back, e.g., `-1` for
    /// the last element.
    ///
    /// Returns an empty `Ok` if the action could be performed successfully.
    /// Otherwise, a [`MathError`] is returned if one of the specified entries
    /// is not part of the matrix.
    ///
    /// # Examples
    /// ```
    /// use qfall_math::{rational::MatQ, traits::MatrixSwaps};
    ///
    /// let mut matrix = MatQ::new(4, 3);
    /// matrix.swap_entries(0, 0, 2, 1);
    /// ```
    ///
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type [`MathError::OutOfBounds`]
    ///   if row or column are greater than the matrix size.
    fn swap_entries(
        &mut self,
        row_0: impl TryInto<i64> + Display,
        col_0: impl TryInto<i64> + Display,
        row_1: impl TryInto<i64> + Display,
        col_1: impl TryInto<i64> + Display,
    ) -> Result<(), MathError> {
        let (row_0, col_0) = evaluate_indices_for_matrix(self, row_0, col_0)?;
        let (row_1, col_1) = evaluate_indices_for_matrix(self, row_1, col_1)?;

        unsafe {
            fmpq_swap(
                fmpq_mat_entry(&self.matrix, row_0, col_0),
                fmpq_mat_entry(&self.matrix, row_1, col_1),
            )
        };
        Ok(())
    }

    /// Swaps two columns of the specified matrix.
    ///
    /// Parameters:
    /// - `col_0`: specifies the first column which is swapped with the second one
    /// - `col_1`: specifies the second column which is swapped with the first one
    ///
    /// Negative indices can be used to index from the back, e.g., `-1` for
    /// the last element.
    ///
    /// Returns an empty `Ok` if the action could be performed successfully.
    /// Otherwise, a [`MathError`] is returned if one of the specified columns is not part of the matrix.
    ///
    /// # Examples
    /// ```
    /// use qfall_math::{rational::MatQ, traits::MatrixSwaps};
    ///
    /// let mut matrix = MatQ::new(4, 3);
    /// matrix.swap_columns(0, 2);
    /// ```
    ///
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type [`OutOfBounds`](MathError::OutOfBounds)
    ///   if one of the given columns is greater than the matrix.
    fn swap_columns(
        &mut self,
        col_0: impl TryInto<i64> + Display,
        col_1: impl TryInto<i64> + Display,
    ) -> Result<(), MathError> {
        let num_cols = self.get_num_columns();
        let col_0 = evaluate_index_for_vector(col_0, num_cols)?;
        let col_1 = evaluate_index_for_vector(col_1, num_cols)?;

        if col_0 >= num_cols || col_1 >= num_cols {
            return Err(MathError::OutOfBounds(
                format!("smaller than {num_cols}"),
                if col_0 > col_1 {
                    col_0.to_string()
                } else {
                    col_1.to_string()
                },
            ));
        }
        unsafe { fmpq_mat_swap_cols(&mut self.matrix, null(), col_0, col_1) }
        Ok(())
    }

    /// Swaps two rows of the specified matrix.
    ///
    /// Parameters:
    /// - `row_0`: specifies the first row which is swapped with the second one
    /// - `row_1`: specifies the second row which is swapped with the first one
    ///
    /// Negative indices can be used to index from the back, e.g., `-1` for
    /// the last element.
    ///
    /// Returns an empty `Ok` if the action could be performed successfully.
    /// Otherwise, a [`MathError`] is returned if one of the specified rows is not part of the matrix.
    ///
    /// # Examples
    /// ```
    /// use qfall_math::{rational::MatQ, traits::MatrixSwaps};
    ///
    /// let mut matrix = MatQ::new(4, 3);
    /// matrix.swap_rows(0, 2);
    /// ```
    ///
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type [`OutOfBounds`](MathError::OutOfBounds)
    ///   if one of the given rows is greater than the matrix.
    fn swap_rows(
        &mut self,
        row_0: impl TryInto<i64> + Display,
        row_1: impl TryInto<i64> + Display,
    ) -> Result<(), MathError> {
        let num_rows = self.get_num_rows();
        let row_0 = evaluate_index_for_vector(row_0, num_rows)?;
        let row_1 = evaluate_index_for_vector(row_1, num_rows)?;

        if row_0 >= num_rows || row_1 >= num_rows {
            return Err(MathError::OutOfBounds(
                format!("smaller than {num_rows}"),
                if row_0 > row_1 {
                    row_0.to_string()
                } else {
                    row_1.to_string()
                },
            ));
        }
        unsafe { fmpq_mat_swap_rows(&mut self.matrix, null(), row_0, row_1) }
        Ok(())
    }
}

impl MatQ {
    /// Swaps the `i`-th column with the `n-i`-th column for all `i <= n/2`
    /// of the specified matrix with `n` columns.
    ///
    /// # Examples
    /// ```
    /// use qfall_math::rational::MatQ;
    ///
    /// let mut matrix = MatQ::new(4, 3);
    /// matrix.reverse_columns();
    /// ```
    pub fn reverse_columns(&mut self) {
        // If the second argument to this function is not null, the permutation
        // of the columns is also applied to this argument.
        // Hence, passing in null is justified here.
        unsafe { fmpq_mat_invert_cols(&mut self.matrix, null_mut()) }
    }

    /// Swaps the `i`-th row with the `n-i`-th row for all `i <= n/2`
    /// of the specified matrix with `n` rows.
    ///
    /// # Examples
    /// ```
    /// use qfall_math::rational::MatQ;
    ///
    /// let mut matrix = MatQ::new(4, 3);
    /// matrix.reverse_rows();
    /// ```
    pub fn reverse_rows(&mut self) {
        // If the second argument to this function is not null, the permutation
        // of the rows is also applied to this argument.
        // Hence, passing in null is justified here.
        unsafe { fmpq_mat_invert_rows(&mut self.matrix, null_mut()) }
    }
}

#[cfg(test)]
mod test_setter {
    use super::Q;
    use crate::{
        integer::Z,
        integer_mod_q::Modulus,
        rational::MatQ,
        traits::{MatrixGetEntry, MatrixSetEntry, MatrixSetSubmatrix},
    };
    use std::str::FromStr;

    /// Test the different types that can be used to set an entry.
    #[test]
    fn availability() {
        let mut matrix = MatQ::new(1, 1);

        // Set with rationals
        matrix.set_entry(0, 0, (1, 2)).unwrap();
        matrix.set_entry(0, 0, (1i16, 2u64)).unwrap();
        matrix.set_entry(0, 0, Q::from((1, 2))).unwrap();
        matrix.set_entry(0, 0, &Q::from((1, 2))).unwrap();

        // Set with integers
        matrix.set_entry(0, 0, 1u8).unwrap();
        matrix.set_entry(0, 0, 1i8).unwrap();
        matrix.set_entry(0, 0, 1u16).unwrap();
        matrix.set_entry(0, 0, 1i16).unwrap();
        matrix.set_entry(0, 0, 1u32).unwrap();
        matrix.set_entry(0, 0, 1i32).unwrap();
        matrix.set_entry(0, 0, 1u64).unwrap();
        matrix.set_entry(0, 0, 1i64).unwrap();
        matrix.set_entry(0, 0, Z::from(1)).unwrap();
        matrix.set_entry(0, 0, &Z::from(1)).unwrap();
        matrix.set_entry(0, 0, Modulus::from(3)).unwrap();
        matrix.set_entry(0, 0, &Modulus::from(3)).unwrap();
    }

    /// Ensure that setting entries works with standard numbers.
    #[test]
    fn standard_value() {
        let mut matrix = MatQ::new(5, 10);
        let value = Q::from(869);
        matrix.set_entry(4, 7, &value).unwrap();

        let entry = matrix.get_entry(4, 7).unwrap();

        assert_eq!(Q::from(869), entry);
    }

    /// Ensure that setting entries works with large large numerators and denominators.
    #[test]
    fn max_int_positive() {
        let mut matrix = MatQ::new(5, 10);
        let value_1 = Q::from(i64::MAX);
        let value_2 = Q::from((1, i64::MAX));
        matrix.set_entry(0, 0, value_1).unwrap();
        matrix.set_entry(1, 1, value_2).unwrap();

        let entry_1 = matrix.get_entry(0, 0).unwrap();
        let entry_2 = matrix.get_entry(1, 1).unwrap();

        assert_eq!(Q::from(i64::MAX), entry_1);
        assert_eq!(Q::from((1, i64::MAX)), entry_2);
    }

    /// Ensure that setting entries works with large numerators and denominators (larger than [`i64`]).
    #[test]
    fn large_positive() {
        let mut matrix = MatQ::new(5, 10);
        let value_1 = Q::from(u64::MAX);
        let value_2 = Q::from((1, u64::MAX));
        matrix.set_entry(0, 0, value_1).unwrap();
        matrix.set_entry(1, 1, value_2).unwrap();

        let entry_1 = matrix.get_entry(0, 0).unwrap();
        let entry_2 = matrix.get_entry(1, 1).unwrap();

        assert_eq!(Q::from(u64::MAX), entry_1);
        assert_eq!(Q::from((1, u64::MAX)), entry_2);
    }

    /// Ensure that setting entries works with large negative numerators and denominators.
    #[test]
    fn max_int_negative() {
        let mut matrix = MatQ::new(5, 10);
        let value_1 = Q::from(i64::MIN);
        let value_2 = Q::from((1, i64::MIN));
        matrix.set_entry(0, 0, value_1).unwrap();
        matrix.set_entry(1, 1, value_2).unwrap();

        let entry_1 = matrix.get_entry(0, 0).unwrap();
        let entry_2 = matrix.get_entry(1, 1).unwrap();

        assert_eq!(Q::from(i64::MIN), entry_1);
        assert_eq!(Q::from((1, i64::MIN)), entry_2);
    }

    /// Ensure that setting entries works with large negative numerators and denominators (larger than [`i64`]).
    #[test]
    fn large_negative() {
        let mut matrix = MatQ::new(5, 10);
        let value_1 = format!("-{}", u64::MAX);
        let value_2 = format!("1/-{}", u64::MAX);
        matrix
            .set_entry(0, 0, Q::from_str(&value_1).unwrap())
            .unwrap();
        matrix
            .set_entry(1, 1, Q::from_str(&value_2).unwrap())
            .unwrap();

        let entry_1 = matrix.get_entry(0, 0).unwrap();
        let entry_2 = matrix.get_entry(1, 1).unwrap();

        assert_eq!(Q::from_str(&format!("-{}", u64::MAX)).unwrap(), entry_1);
        assert_eq!(Q::from_str(&format!("1/-{}", u64::MAX)).unwrap(), entry_2);
    }

    /// Ensure that setting entries at (0, 0) works.
    #[test]
    fn getting_at_zero() {
        let mut matrix = MatQ::new(5, 10);
        let value = Q::from(i64::MIN);
        matrix.set_entry(0, 0, value).unwrap();

        let entry = matrix.get_entry(0, 0).unwrap();

        assert_eq!(entry, Q::from(i64::MIN));
    }

    /// Ensure that a wrong number of rows yields an Error.
    #[test]
    fn error_wrong_row() {
        let matrix = MatQ::new(5, 10);

        assert!(matrix.get_entry(5, 1).is_err());
        assert!(matrix.get_entry(-6, 1).is_err());
    }

    /// Ensure that a wrong number of columns yields an Error.
    #[test]
    fn error_wrong_column() {
        let matrix = MatQ::new(5, 10);

        assert!(matrix.get_entry(1, 100).is_err());
        assert!(matrix.get_entry(1, -11).is_err());
    }

    /// Ensure that negative indices return address the correct entires.
    #[test]
    fn negative_indexing() {
        let mut matrix = MatQ::new(3, 3);

        matrix.set_entry(-1, -1, 9).unwrap();
        matrix.set_entry(-1, -2, 8).unwrap();
        matrix.set_entry(-3, -3, 1).unwrap();

        let matrix_cmp = MatQ::from_str("[[1, 0, 0],[0, 0, 0],[0, 8, 9]]").unwrap();
        assert_eq!(matrix_cmp, matrix);
    }

    /// Ensures that setting columns works fine for small entries
    #[test]
    fn column_small_entries() {
        let mut mat_1 = MatQ::from_str("[[1, 2, 3/-1],[-4/3, 5, 6]]").unwrap();
        let mat_2 = MatQ::from_str("[[0],[-1]]").unwrap();
        let cmp = MatQ::from_str("[[1, 0, -3],[4/-3, -1, 6]]").unwrap();

        mat_1.set_column(1, &mat_2, 0).unwrap();

        assert_eq!(cmp, mat_1);
    }

    /// Ensures that setting columns works fine for large entries
    #[test]
    fn column_large_entries() {
        let mut mat_1 = MatQ::from_str(&format!(
            "[[{}/1, 1, 3, 4],[{}/-1, 4, -1/{}, 5],[7, 6, 8, 9]]",
            i64::MIN,
            i64::MAX,
            u64::MAX
        ))
        .unwrap();
        let mat_2 =
            MatQ::from_str(&format!("[[1, -2/{}],[{}, 0],[7, -1]]", i64::MIN, i64::MAX)).unwrap();
        let cmp = MatQ::from_str(&format!(
            "[[-2/{}, 1, 3, 4],[0, 4, -1/{}, 5],[-1, 6, 8, 9]]",
            i64::MIN,
            u64::MAX
        ))
        .unwrap();

        mat_1.set_column(0, &mat_2, 1).unwrap();

        assert_eq!(cmp, mat_1);
    }

    /// Ensures that setting the column to itself does not change anything
    #[test]
    fn column_swap_same_entry() {
        let mut mat_1 = MatQ::from_str(&format!(
            "[[{}/-3, 1, 3, 4],[{}/-1, 4, -{}/2, 5],[7, 6, 8, 9]]",
            i64::MIN,
            i64::MAX,
            u64::MAX
        ))
        .unwrap();
        let cmp = mat_1.clone();

        mat_1.set_column(0, &cmp, 0).unwrap();
        mat_1.set_column(1, &cmp, 1).unwrap();

        assert_eq!(cmp, mat_1);
    }

    /// Ensures that `set_column` returns an error if one of the specified columns is out of bounds
    #[test]
    fn column_out_of_bounds() {
        let mut mat_1 = MatQ::new(5, 2);
        let mat_2 = mat_1.clone();

        assert!(mat_1.set_column(-3, &mat_2, 0).is_err());
        assert!(mat_1.set_column(2, &mat_2, 0).is_err());
        assert!(mat_1.set_column(1, &mat_2, -3).is_err());
        assert!(mat_1.set_column(1, &mat_2, 2).is_err());
    }

    /// Ensures that mismatching row dimensions result in an error
    #[test]
    fn column_mismatching_columns() {
        let mut mat_1 = MatQ::new(5, 2);
        let mat_2 = MatQ::new(2, 2);

        assert!(mat_1.set_column(0, &mat_2, 0).is_err());
        assert!(mat_1.set_column(1, &mat_2, 1).is_err());
    }

    /// Ensures that setting rows works fine for small entries
    #[test]
    fn row_small_entries() {
        let mut mat_1 = MatQ::from_str("[[1, 2, 3/-1],[-4/3, 5, 6]]").unwrap();
        let mat_2 = MatQ::from_str("[[0, -1/2, 2]]").unwrap();
        let cmp = MatQ::from_str("[[1, 2, -3],[0, -1/2, 2]]").unwrap();

        let _ = mat_1.set_row(1, &mat_2, 0);

        assert_eq!(cmp, mat_1);
    }

    /// Ensures that setting rows works fine for large entries
    #[test]
    fn row_large_entries() {
        let mut mat_1 = MatQ::from_str(&format!(
            "[[{}, 1, 3, 4],[{}, 4, {}, 5],[7, 6, 8, 9]]",
            i64::MIN,
            i64::MAX,
            u64::MAX
        ))
        .unwrap();
        let mat_2 = MatQ::from_str(&format!(
            "[[0, 0, 0, 0],[1/{}, 0, {}/3, 0]]",
            i64::MIN,
            i64::MAX
        ))
        .unwrap();
        let cmp = MatQ::from_str(&format!(
            "[[1/{}, 0, {}/3, 0],[{}, 4, {}, 5],[7, 6, 8, 9]]",
            i64::MIN,
            i64::MAX,
            i64::MAX,
            u64::MAX
        ))
        .unwrap();

        let _ = mat_1.set_row(0, &mat_2, 1);

        assert_eq!(cmp, mat_1);
    }

    /// Ensures that setting the rows to itself does not change anything
    #[test]
    fn row_swap_same_entry() {
        let mut mat_1 = MatQ::from_str(&format!(
            "[[{}, 1, 3, 4],[-{}/-1, 4, {}/-3, 5],[7, 6, 8, 9]]",
            i64::MIN,
            i64::MAX,
            u64::MAX
        ))
        .unwrap();
        let cmp = mat_1.clone();

        let _ = mat_1.set_row(0, &cmp, 0);
        let _ = mat_1.set_row(1, &cmp, 1);

        assert_eq!(cmp, mat_1);
    }

    /// Ensures that `set_row` returns an error if one of the specified rows is out of bounds
    #[test]
    fn row_out_of_bounds() {
        let mut mat_1 = MatQ::new(5, 2);
        let mat_2 = mat_1.clone();

        assert!(mat_1.set_row(-6, &mat_2, 0).is_err());
        assert!(mat_1.set_row(5, &mat_2, 0).is_err());
        assert!(mat_1.set_row(2, &mat_2, -6).is_err());
        assert!(mat_1.set_row(2, &mat_2, 5).is_err());
    }

    /// Ensures that mismatching column dimensions result in an error
    #[test]
    fn row_mismatching_columns() {
        let mut mat_1 = MatQ::new(3, 2);
        let mat_2 = MatQ::new(3, 3);

        assert!(mat_1.set_row(0, &mat_2, 0).is_err());
        assert!(mat_1.set_row(1, &mat_2, 1).is_err());
    }

    /// Ensure that negative indices work for set_column/row.
    #[test]
    fn negative_indexing_row_column() {
        let mut matrix = MatQ::identity(3, 3);
        let matrix2 = MatQ::identity(3, 3);

        matrix.set_column(-1, &matrix2, -2).unwrap();
        matrix.set_row(-1, &matrix2, -2).unwrap();

        let matrix_cmp = MatQ::from_str("[[1, 0, 0],[0, 1, 1],[0, 1, 0]]").unwrap();
        assert_eq!(matrix_cmp, matrix);
    }
}

#[cfg(test)]
mod test_swaps {
    use super::MatQ;
    use crate::traits::{MatrixGetSubmatrix, MatrixSwaps};
    use std::str::FromStr;

    /// Ensures that swapping entries works fine for small entries
    #[test]
    fn entries_small_entries() {
        let mut matrix = MatQ::from_str("[[1, 1/2, 3/-5],[-4/3, -5, 6]]").unwrap();
        let cmp = MatQ::from_str("[[1, -5, 3/-5],[-4/3, 1/2, 6]]").unwrap();

        let _ = matrix.swap_entries(1, 1, 0, 1);

        assert_eq!(cmp, matrix);
    }

    /// Ensures that swapping entries works fine for large entries
    #[test]
    fn entries_large_entries() {
        let mut matrix = MatQ::from_str(&format!(
            "[[{}/2, 1, 3, 4],[{}, 4, -1/{}, 5],[7, 6, 8, 9]]",
            i64::MIN,
            i64::MAX,
            u64::MAX
        ))
        .unwrap();
        let cmp = MatQ::from_str(&format!(
            "[[-1/{}, 1, 3, 4],[{}, 4, {}/2, 5],[7, 6, 8, 9]]",
            u64::MAX,
            i64::MAX,
            i64::MIN
        ))
        .unwrap();

        let _ = matrix.swap_entries(0, 0, 1, 2);

        assert_eq!(cmp, matrix);
    }

    /// Ensures that swapping the same entry does not change anything
    #[test]
    fn entries_swap_same_entry() {
        let mut matrix = MatQ::from_str(&format!(
            "[[{}, 1, 3, 4],[{}, 4, {}, 5],[7, 6, 8, 9]]",
            i64::MIN,
            i64::MAX,
            u64::MAX
        ))
        .unwrap();
        let cmp = matrix.clone();

        let _ = matrix.swap_entries(0, 0, 0, 0);
        let _ = matrix.swap_entries(1, 1, 1, 1);

        assert_eq!(cmp, matrix);
    }

    /// Ensures that `swap_entries` returns an error if one of the specified entries is out of bounds
    #[test]
    fn entries_out_of_bounds() {
        let mut matrix = MatQ::new(5, 2);

        assert!(matrix.swap_entries(-6, 0, 0, 0).is_err());
        assert!(matrix.swap_entries(0, -3, 0, 0).is_err());
        assert!(matrix.swap_entries(0, 0, 5, 0).is_err());
        assert!(matrix.swap_entries(0, 5, 0, 0).is_err());
    }

    /// Ensures that swapping columns works fine for small entries
    #[test]
    fn columns_small_entries() {
        let mut matrix = MatQ::from_str("[[1, 2/-1, -3/1],[1/4, 5/7, 6]]").unwrap();
        let cmp_vec_0 = MatQ::from_str("[[1],[1/4]]").unwrap();
        let cmp_vec_1 = MatQ::from_str("[[-3],[6]]").unwrap();
        let cmp_vec_2 = MatQ::from_str("[[-2],[5/7]]").unwrap();

        let _ = matrix.swap_columns(1, 2);

        assert_eq!(cmp_vec_0, matrix.get_column(0).unwrap());
        assert_eq!(cmp_vec_1, matrix.get_column(1).unwrap());
        assert_eq!(cmp_vec_2, matrix.get_column(2).unwrap());
    }

    /// Ensures that swapping columns works fine for large entries
    #[test]
    fn columns_large_entries() {
        let mut matrix = MatQ::from_str(&format!(
            "[[{}, 1, 3, 4/-3],[{}/2, 4, -1/{}, 5],[7, 6, 8/9, 9]]",
            i64::MIN,
            i64::MAX,
            u64::MAX
        ))
        .unwrap();
        let cmp_vec_0 = MatQ::from_str(&format!("[[3],[-1/{}],[8/9]]", u64::MAX)).unwrap();
        let cmp_vec_1 = MatQ::from_str("[[1],[4],[6]]").unwrap();
        let cmp_vec_2 = MatQ::from_str(&format!("[[{}],[{}/2],[7]]", i64::MIN, i64::MAX)).unwrap();
        let cmp_vec_3 = MatQ::from_str("[[4/-3],[5],[9]]").unwrap();

        let _ = matrix.swap_columns(0, 2);

        assert_eq!(cmp_vec_0, matrix.get_column(0).unwrap());
        assert_eq!(cmp_vec_1, matrix.get_column(1).unwrap());
        assert_eq!(cmp_vec_2, matrix.get_column(2).unwrap());
        assert_eq!(cmp_vec_3, matrix.get_column(3).unwrap());
    }

    /// Ensures that swapping the same column does not change anything
    #[test]
    fn columns_swap_same_col() {
        let mut matrix = MatQ::from_str(&format!(
            "[[{}, 1, 3, 4],[{}, 4, {}, 5],[7, 6, 8, 9]]",
            i64::MIN,
            i64::MAX,
            u64::MAX
        ))
        .unwrap();
        let cmp = matrix.clone();

        let _ = matrix.swap_columns(0, 0);

        assert_eq!(cmp, matrix);
    }

    /// Ensures that `swap_columns` returns an error if one of the specified columns is out of bounds
    #[test]
    fn column_out_of_bounds() {
        let mut matrix = MatQ::new(5, 2);

        assert!(matrix.swap_columns(-6, 0).is_err());
        assert!(matrix.swap_columns(0, -6).is_err());
        assert!(matrix.swap_columns(5, 0).is_err());
        assert!(matrix.swap_columns(0, 5).is_err());
    }

    /// Ensures that swapping rows works fine for small entries
    #[test]
    fn rows_small_entries() {
        let mut matrix = MatQ::from_str("[[1, 2/-3],[3, -4/3]]").unwrap();
        let cmp_vec_0 = MatQ::from_str("[[3, -4/3]]").unwrap();
        let cmp_vec_1 = MatQ::from_str("[[1, 2/-3]]").unwrap();

        let _ = matrix.swap_rows(1, 0);

        assert_eq!(cmp_vec_0, matrix.get_row(0).unwrap());
        assert_eq!(cmp_vec_1, matrix.get_row(1).unwrap());
    }

    /// Ensures that swapping rows works fine for large entries
    #[test]
    fn rows_large_entries() {
        let mut matrix = MatQ::from_str(&format!(
            "[[{}, 1, 3, 4],[7, 6/-1, 8, 9/4],[1/{}, 4, -2/{}, 5/3]]",
            i64::MIN,
            i64::MAX,
            u64::MAX
        ))
        .unwrap();
        let cmp_vec_0 =
            MatQ::from_str(&format!("[[1/{}, 4, -2/{}, 5/3]]", i64::MAX, u64::MAX)).unwrap();
        let cmp_vec_1 = MatQ::from_str("[[7, 6/-1, 8, 9/4]]").unwrap();
        let cmp_vec_2 = MatQ::from_str(&format!("[[{}, 1, 3, 4]]", i64::MIN)).unwrap();

        let _ = matrix.swap_rows(0, 2);

        assert_eq!(cmp_vec_0, matrix.get_row(0).unwrap());
        assert_eq!(cmp_vec_1, matrix.get_row(1).unwrap());
        assert_eq!(cmp_vec_2, matrix.get_row(2).unwrap());
    }

    /// Ensures that swapping the same row does not change anything
    #[test]
    fn rows_swap_same_row() {
        let mut matrix = MatQ::from_str(&format!(
            "[[{}, 1, 3, 4],[{}, 4, {}, 5],[7, 6, 8, 9]]",
            i64::MIN,
            i64::MAX,
            u64::MAX
        ))
        .unwrap();
        let cmp = matrix.clone();

        let _ = matrix.swap_rows(1, 1);

        assert_eq!(cmp, matrix);
    }

    /// Ensures that `swap_rows` returns an error if one of the specified rows is out of bounds
    #[test]
    fn row_out_of_bounds() {
        let mut matrix = MatQ::new(2, 4);

        assert!(matrix.swap_rows(-3, 0).is_err());
        assert!(matrix.swap_rows(0, -3).is_err());
        assert!(matrix.swap_rows(4, 0).is_err());
        assert!(matrix.swap_rows(0, 4).is_err());
    }

    /// Ensure that negative indices work for swap_column/row.
    #[test]
    fn negative_indexing_row_column() {
        let mut matrix = MatQ::identity(3, 3);
        let mut matrix2 = MatQ::identity(3, 3);

        matrix.swap_columns(-1, -2).unwrap();
        matrix2.swap_rows(-1, -2).unwrap();

        let matrix_cmp = MatQ::from_str("[[1, 0, 0],[0, 0, 1],[0, 1, 0]]").unwrap();
        assert_eq!(matrix_cmp, matrix);
        assert_eq!(matrix_cmp, matrix2);
    }
}

#[cfg(test)]
mod test_reverses {
    use super::MatQ;
    use crate::traits::MatrixGetSubmatrix;
    use std::str::FromStr;

    /// Ensures that reversing columns works fine for small entries
    #[test]
    fn columns_small_entries() {
        let mut matrix = MatQ::from_str("[[1, 2/-1, -3/1],[4, 5/6, 6]]").unwrap();
        let cmp_vec_0 = MatQ::from_str("[[1],[4]]").unwrap();
        let cmp_vec_1 = MatQ::from_str("[[-2],[5/6]]").unwrap();
        let cmp_vec_2 = MatQ::from_str("[[-3],[6]]").unwrap();

        matrix.reverse_columns();

        assert_eq!(cmp_vec_2, matrix.get_column(0).unwrap());
        assert_eq!(cmp_vec_1, matrix.get_column(1).unwrap());
        assert_eq!(cmp_vec_0, matrix.get_column(2).unwrap());
    }

    /// Ensures that reversing columns works fine for large entries
    #[test]
    fn columns_large_entries() {
        let mut matrix = MatQ::from_str(&format!(
            "[[1/{}, 1, 3, 4],[-1/{}, 4, {}, 5],[7, 6, 8/9, 9]]",
            i64::MIN,
            i64::MAX,
            u64::MAX
        ))
        .unwrap();
        let cmp_vec_0 =
            MatQ::from_str(&format!("[[1/{}],[-1/{}],[7]]", i64::MIN, i64::MAX)).unwrap();
        let cmp_vec_1 = MatQ::from_str("[[1],[4],[6]]").unwrap();
        let cmp_vec_2 = MatQ::from_str(&format!("[[3],[{}],[8/9]]", u64::MAX)).unwrap();
        let cmp_vec_3 = MatQ::from_str("[[4],[5],[9]]").unwrap();

        matrix.reverse_columns();

        assert_eq!(cmp_vec_3, matrix.get_column(0).unwrap());
        assert_eq!(cmp_vec_2, matrix.get_column(1).unwrap());
        assert_eq!(cmp_vec_1, matrix.get_column(2).unwrap());
        assert_eq!(cmp_vec_0, matrix.get_column(3).unwrap());
    }

    /// Ensures that reversing rows works fine for small entries
    #[test]
    fn rows_small_entries() {
        let mut matrix = MatQ::from_str("[[1, 2/-1],[-3/1, 4]]").unwrap();
        let cmp_vec_0 = MatQ::from_str("[[1, -2]]").unwrap();
        let cmp_vec_1 = MatQ::from_str("[[-3, 4]]").unwrap();

        matrix.reverse_rows();

        assert_eq!(cmp_vec_1, matrix.get_row(0).unwrap());
        assert_eq!(cmp_vec_0, matrix.get_row(1).unwrap());
    }

    /// Ensures that reversing rows works fine for large entries
    #[test]
    fn rows_large_entries() {
        let mut matrix = MatQ::from_str(&format!(
            "[[{}, 1, 3, 4],[7, 6, 8, 9],[{}, 4, -2/{}, 5]]",
            i64::MIN,
            i64::MAX,
            u64::MAX
        ))
        .unwrap();
        let cmp_vec_0 = MatQ::from_str(&format!("[[{}, 1, 3, 4]]", i64::MIN)).unwrap();
        let cmp_vec_1 = MatQ::from_str("[[7, 6, 8, 9]]").unwrap();
        let cmp_vec_2 =
            MatQ::from_str(&format!("[[{}, 4, -2/{}, 5]]", i64::MAX, u64::MAX)).unwrap();

        matrix.reverse_rows();

        assert_eq!(cmp_vec_2, matrix.get_row(0).unwrap());
        assert_eq!(cmp_vec_1, matrix.get_row(1).unwrap());
        assert_eq!(cmp_vec_0, matrix.get_row(2).unwrap());
    }
}

#[cfg(test)]
mod test_set_submatrix {
    use crate::{rational::MatQ, traits::MatrixSetSubmatrix};
    use std::str::FromStr;

    /// Ensure that the entire matrix can be set.
    #[test]
    fn entire_matrix() {
        let mut mat = MatQ::new(10, 10);
        let identity = MatQ::identity(10, 10);

        mat.set_submatrix(0, 0, &identity, 0, 0, 9, 9).unwrap();

        assert_eq!(identity, mat);
    }

    /// Ensure that matrix access out of bounds leadss to an error.
    #[test]
    fn out_of_bounds() {
        let mut mat = MatQ::identity(10, 10);

        assert!(mat.set_submatrix(10, 0, &mat.clone(), 0, 0, 9, 9).is_err());
        assert!(mat.set_submatrix(0, 10, &mat.clone(), 0, 0, 9, 9).is_err());
        assert!(mat.set_submatrix(0, 0, &mat.clone(), 10, 0, 9, 9).is_err());
        assert!(mat.set_submatrix(0, 0, &mat.clone(), 0, 10, 9, 9).is_err());
        assert!(mat.set_submatrix(0, 0, &mat.clone(), 0, 0, 10, 9).is_err());
        assert!(mat.set_submatrix(0, 0, &mat.clone(), 0, 0, 9, 10).is_err());
        assert!(mat.set_submatrix(-11, 0, &mat.clone(), 0, 0, 9, 9).is_err());
        assert!(mat.set_submatrix(0, -11, &mat.clone(), 0, 0, 9, 9).is_err());
        assert!(mat.set_submatrix(0, 0, &mat.clone(), -11, 0, 9, 9).is_err());
        assert!(mat.set_submatrix(0, 0, &mat.clone(), 0, -11, 9, 9).is_err());
        assert!(mat.set_submatrix(0, 0, &mat.clone(), 0, 0, -11, 9).is_err());
        assert!(mat.set_submatrix(0, 0, &mat.clone(), 0, 0, 9, -11).is_err());
    }

    /// Ensure that the function returns an error if the defined submatrix is too large
    /// and there is not enough space in the original matrix.
    #[test]
    fn submatrix_too_large() {
        let mut mat = MatQ::new(10, 10);

        assert!(
            mat.set_submatrix(0, 0, &MatQ::identity(11, 11), 0, 0, 10, 10)
                .is_err()
        );
        assert!(mat.set_submatrix(1, 2, &mat.clone(), 0, 0, 9, 9).is_err());
    }

    /// Ensure that setting submatrices with large values works.
    #[test]
    fn large_values() {
        let mut mat = MatQ::from_str(&format!("[[1, {}],[-{}/3, 0]]", u64::MAX, u64::MAX)).unwrap();
        let cmp_mat =
            MatQ::from_str(&format!("[[-{}/3, 0],[-{}/3, 0]]", u64::MAX, u64::MAX)).unwrap();

        mat.set_submatrix(0, 0, &mat.clone(), 1, 0, 1, 1).unwrap();
        assert_eq!(cmp_mat, mat);
    }

    /// Ensure that setting with an undefined submatrix.
    #[test]
    #[should_panic]
    fn submatrix_negative() {
        let mut mat = MatQ::identity(10, 10);

        let _ = mat.set_submatrix(0, 0, &mat.clone(), 0, 9, 9, 5);
    }
}