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
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
// 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 [`MatZq`] matrix.

use crate::{
    error::MathError,
    integer::Z,
    integer_mod_q::{MatZq, Modulus, Zq},
    macros::for_others::implement_for_owned,
    traits::{AsInteger, MatrixDimensions, MatrixSetEntry, MatrixSetSubmatrix, MatrixSwaps},
    utils::index::{evaluate_index_for_vector, evaluate_indices_for_matrix},
};
use flint_sys::{
    fmpz::fmpz_swap,
    fmpz_mat::{
        fmpz_mat_entry, fmpz_mat_invert_cols, fmpz_mat_invert_rows, fmpz_mat_swap_cols,
        fmpz_mat_swap_rows,
    },
    fmpz_mod_mat::{
        _fmpz_mod_mat_reduce, _fmpz_mod_mat_set_mod, fmpz_mod_mat_set, fmpz_mod_mat_set_entry,
        fmpz_mod_mat_window_clear, fmpz_mod_mat_window_init,
    },
};
use std::{
    fmt::Display,
    mem::MaybeUninit,
    ptr::{null, null_mut},
};

impl<Integer: Into<Z>> MatrixSetEntry<Integer> for MatZq {
    /// Sets the value of a specific matrix entry according to a given `value`
    /// that implements [`Into<Z>`].
    ///
    /// 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
    ///
    /// 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 the specified entry is not part of the matrix.
    ///
    /// # Examples
    /// ```
    /// use qfall_math::integer_mod_q::MatZq;
    /// use qfall_math::traits::*;
    ///
    /// let mut matrix = MatZq::new(3, 3, 10);
    ///
    /// matrix.set_entry(0, 1, 5).unwrap();
    /// matrix.set_entry(-1, 2, 19).unwrap();
    ///
    /// assert_eq!("[[0, 5, 0],[0, 0, 0],[0, 0, 9]] mod 10", matrix.to_string());
    /// ```
    ///
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type [`MathError::OutOfBounds`]
    ///   if `row` or `column` are greater than the matrix size.
    fn set_entry(
        &mut self,
        row: impl TryInto<i64> + Display,
        column: impl TryInto<i64> + Display,
        value: Integer,
    ) -> Result<(), MathError> {
        // Calculate mod q before adding the entry to the matrix.
        let value: Zq = Zq::from((value, &self.modulus));

        self.set_entry(row, column, value)
    }

    /// Sets the value of a specific matrix entry according to a given `value`
    /// that implements [`Into<Z>`] without checking whether the coordinate is part of the matrix,
    /// if the moduli match or the entry is reduced.
    ///
    /// 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::integer_mod_q::MatZq;
    /// use qfall_math::traits::*;
    ///
    /// let mut matrix = MatZq::new(3, 3, 10);
    ///
    /// unsafe {
    ///     matrix.set_entry_unchecked(0, 1, 5);
    ///     matrix.set_entry_unchecked(2, 2, 19);
    /// }
    ///
    /// assert_eq!("[[0, 5, 0],[0, 0, 0],[0, 0, 19]] mod 10", matrix.to_string());
    /// ```
    unsafe fn set_entry_unchecked(&mut self, row: i64, column: i64, value: Integer) {
        let value: Z = value.into();

        unsafe {
            // get entry and replace the pointed at value with the specified value
            fmpz_mod_mat_set_entry(&mut self.matrix, row, column, &value.value)
        };
    }
}

impl MatrixSetEntry<&Zq> for MatZq {
    /// Sets the value of a specific matrix entry according to a given `value` of type [`Zq`]
    /// without checking whether the coordinate is part of the matrix,
    /// if the moduli match or the entry is reduced.
    ///
    /// 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::integer_mod_q::{MatZq, Zq};
    /// use qfall_math::traits::*;
    ///
    /// let mut matrix = MatZq::new(3, 3, 10);
    /// let value = Zq::from((5, 10));
    ///
    /// unsafe {
    ///     matrix.set_entry_unchecked(0, 1, &value);
    ///     matrix.set_entry_unchecked(2, 2, Zq::from((19, 10)));
    /// }
    ///
    /// assert_eq!("[[0, 5, 0],[0, 0, 0],[0, 0, 9]] mod 10", matrix.to_string());
    /// ```
    unsafe fn set_entry_unchecked(&mut self, row: i64, column: i64, value: &Zq) {
        unsafe {
            // get entry and replace the pointed at value with the specified value
            fmpz_mod_mat_set_entry(&mut self.matrix, row, column, &value.value.value)
        };
    }
}

implement_for_owned!(Zq, MatZq, MatrixSetEntry);

impl MatrixSetSubmatrix for MatZq {
    /// 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::integer_mod_q::{MatZq, Modulus};
    /// use qfall_math::integer::MatZ;
    /// use qfall_math::traits::MatrixSetSubmatrix;
    /// use std::str::FromStr;
    ///
    /// let mat = MatZ::identity(3, 3);
    /// let modulus = Modulus::from(17);
    /// let mut mat = MatZq::from((&mat, &modulus));
    ///
    /// mat.set_submatrix(0, 1, &mat.clone(), 0, 0, 1, 1).unwrap();
    /// // [[1,1,0],[0,0,1],[0,0,1]]
    /// let mat_cmp = MatZ::from_str("[[1, 1, 0],[0, 0, 1],[0, 0, 1]]").unwrap();
    /// assert_eq!(mat, MatZq::from((&mat_cmp, &modulus)));
    ///
    /// unsafe{ mat.set_submatrix_unchecked(2, 0, 3, 2, &mat.clone(), 0, 0, 1, 2) };
    /// let mat_cmp = MatZ::from_str("[[1, 1, 0],[0, 0, 1],[1, 1, 1]]").unwrap();
    /// assert_eq!(mat, MatZq::from((&mat_cmp, &modulus)));
    /// ```
    ///
    /// # 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 {
                fmpz_mod_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 {
                fmpz_mod_mat_window_init(
                    window_other.as_mut_ptr(),
                    &other.matrix,
                    row_other_start,
                    col_other_start,
                    row_other_end,
                    col_other_end,
                )
            };
            unsafe {
                fmpz_mod_mat_set(window_self.as_mut_ptr(), window_other.as_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
                fmpz_mod_mat_window_clear(window_self.as_mut_ptr());
                fmpz_mod_mat_window_clear(window_other.as_mut_ptr());
            }
        }
    }
}

impl MatrixSwaps for MatZq {
    /// 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::{integer_mod_q::MatZq, traits::MatrixSwaps};
    ///
    /// let mut matrix = MatZq::new(4, 3, 5);
    /// 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 {
            fmpz_swap(
                fmpz_mat_entry(&self.matrix.mat[0], row_0, col_0),
                fmpz_mat_entry(&self.matrix.mat[0], 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::{integer_mod_q::MatZq, traits::MatrixSwaps};
    ///
    /// let mut matrix = MatZq::new(4, 3, 5);
    /// 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 { fmpz_mat_swap_cols(&mut self.matrix.mat[0], 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::{integer_mod_q::MatZq, traits::MatrixSwaps};
    ///
    /// let mut matrix = MatZq::new(4, 3, 5);
    /// 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 { fmpz_mat_swap_rows(&mut self.matrix.mat[0], null(), row_0, row_1) }
        Ok(())
    }
}

impl MatZq {
    /// 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::integer_mod_q::MatZq;
    ///
    /// let mut matrix = MatZq::new(4, 3, 5);
    /// 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 { fmpz_mat_invert_cols(&mut self.matrix.mat[0], 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::integer_mod_q::MatZq;
    ///
    /// let mut matrix = MatZq::new(4, 3, 5);
    /// 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 { fmpz_mat_invert_rows(&mut self.matrix.mat[0], null_mut()) }
    }

    /// Changes the modulus of the given matrix to the new modulus.
    /// It takes the representation of each coefficient in [0, q) as the new
    /// matrix entries and reduces them by the new modulus automatically.
    ///
    /// Parameters:
    /// - `modulus`: the new modulus of the matrix
    ///
    /// # Examples
    /// ```
    /// use qfall_math::integer_mod_q::{MatZq, Modulus};
    /// use std::str::FromStr;
    ///
    /// let mut mat = MatZq::from_str("[[1, 2]] mod 3").unwrap();
    /// mat.change_modulus(2);
    /// ```
    ///
    /// # Panics ...
    /// - if `modulus` is smaller than `2`.
    pub fn change_modulus(&mut self, modulus: impl Into<Modulus>) {
        self.modulus = modulus.into();
        unsafe {
            _fmpz_mod_mat_set_mod(&mut self.matrix, self.modulus.get_fmpz_ref().unwrap());
            _fmpz_mod_mat_reduce(&mut self.matrix)
        }
    }
}

#[cfg(test)]
mod test_setter {
    use crate::{
        integer::Z,
        integer_mod_q::{MatZq, Zq},
        traits::{MatrixGetEntry, MatrixSetEntry, MatrixSetSubmatrix},
    };
    use std::str::FromStr;

    /// Ensure that setting entries works with large numbers.
    #[test]
    fn max_int_positive() {
        let mut matrix = MatZq::new(5, 10, u64::MAX);
        let value = Z::from(i64::MAX);
        matrix.set_entry(0, 0, value).unwrap();

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

        assert_eq!(Z::from(i64::MAX), entry);
    }

    /// Ensure that setting entries works with large numbers (larger than [`i64`]).
    #[test]
    fn large_positive() {
        let mut matrix = MatZq::new(5, 10, u64::MAX);
        let value = Z::from(u64::MAX - 1);
        matrix.set_entry(0, 0, value).unwrap();

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

        assert_eq!(u64::MAX - 1, entry);
    }

    /// Ensure that setting entries works with large numbers.
    #[test]
    fn max_int_negative() {
        let mut matrix = MatZq::new(5, 10, u64::MAX);
        let value = Z::from(-i64::MAX);
        matrix.set_entry(0, 0, value).unwrap();

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

        assert_eq!((u64::MAX as i128 - i64::MAX as i128) as u64, entry);
    }

    /// Ensure that setting entries works with large numbers (larger than [`i64`]).
    #[test]
    fn large_negative() {
        let mut matrix = MatZq::new(5, 10, u64::MAX);
        let value = Z::from(-i64::MAX - 1);
        matrix.set_entry(0, 0, value).unwrap();

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

        assert_eq!((u64::MAX as i128 - i64::MAX as i128) as u64 - 1, entry);
    }

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

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

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

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

    /// Ensure that setting entries works with different types.
    #[test]
    fn diff_types() {
        let mut matrix = MatZq::new(5, 10, 56);

        matrix.set_entry(0, 0, Z::default()).unwrap();
        matrix.set_entry(0, 0, Zq::from((12, 56))).unwrap();
        matrix.set_entry(0, 0, 3).unwrap();
        matrix.set_entry(0, 0, &Z::default()).unwrap();
        matrix.set_entry(0, 0, &Zq::from((12, 56))).unwrap();
    }

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

        matrix.set_entry(-1, -1, 9).unwrap();
        matrix.set_entry(-1, -2, 8).unwrap();
        matrix.set_entry(-3, -3, Zq::from((1, 10))).unwrap();

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

    /// Ensure that value is correctly reduced.
    #[test]
    fn set_entry_reduce() {
        let mut matrix = MatZq::new(5, 10, 3);
        matrix.set_entry(1, 1, Z::from(u64::MAX)).unwrap();

        let entry: Z = matrix.get_entry(1, 1).unwrap();

        assert_eq!(entry, Z::from(0));
    }

    /// Ensure that differing moduli result in an error.
    #[test]
    fn modulus_error() {
        let mut matrix = MatZq::new(5, 10, 3);
        assert!(matrix.set_entry(1, 1, Zq::from((2, 5))).is_err());
    }

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

        let cmp = MatZq::from_str("[[1, 0, 3],[4, -1, 6]] mod 11").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 = MatZq::from_str(&format!(
            "[[{}, 1, 3, 4],[{}, 4, {}, 5],[7, 6, 8, 9]] mod {}",
            i64::MIN,
            i64::MAX,
            i64::MAX,
            u64::MAX
        ))
        .unwrap();
        let mat_2 = MatZq::from_str(&format!(
            "[[1, {}],[{}, 0],[7, -1]] mod {}",
            i64::MIN,
            i64::MAX,
            u64::MAX
        ))
        .unwrap();
        let cmp = MatZq::from_str(&format!(
            "[[{}, 1, 3, 4],[0, 4, {}, 5],[-1, 6, 8, 9]] mod {}",
            i64::MIN,
            i64::MAX,
            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 = MatZq::from_str(&format!(
            "[[{}, 1, 3, 4],[{}, 4, {}, 5],[7, 6, 8, 9]] mod {}",
            i64::MIN,
            i64::MAX,
            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 = MatZq::new(5, 2, 17);
        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 = MatZq::new(5, 2, 17);
        let mat_2 = MatZq::new(2, 2, 17);

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

    /// Ensures that mismatching moduli result in an error
    #[test]
    fn column_mismatching_moduli() {
        let mut mat_1 = MatZq::new(3, 3, 19);
        let mat_2 = MatZq::new(3, 3, 17);

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

    /// Ensures that setting rows works fine for small entries
    #[test]
    fn row_small_entries() {
        let mut mat_1 = MatZq::from_str("[[1, 2, 3],[4, 5, 6]] mod 11").unwrap();
        let mat_2 = MatZq::from_str("[[0, -1, 2]] mod 11").unwrap();
        let cmp = MatZq::from_str("[[1, 2, 3],[0, -1, 2]] mod 11").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 = MatZq::from_str(&format!(
            "[[{}, 1, 3, 4],[{}, 4, {}, 5],[7, 6, 8, 9]] mod {}",
            i64::MIN,
            i64::MAX,
            i64::MAX,
            u64::MAX
        ))
        .unwrap();
        let mat_2 = MatZq::from_str(&format!(
            "[[0, 0, 0, 0],[{}, 0, {}, 0]] mod {}",
            i64::MIN,
            i64::MAX,
            u64::MAX
        ))
        .unwrap();
        let cmp = MatZq::from_str(&format!(
            "[[{}, 0, {}, 0],[{}, 4, {}, 5],[7, 6, 8, 9]] mod {}",
            i64::MIN,
            i64::MAX,
            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 = MatZq::from_str(&format!(
            "[[{}, 1, 3, 4],[{}, 4, {}, 5],[7, 6, 8, 9]] mod {}",
            i64::MIN,
            i64::MAX,
            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 = MatZq::new(5, 2, 17);
        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 = MatZq::new(3, 2, 17);
        let mat_2 = MatZq::new(3, 3, 17);

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

    /// Ensures that mismatching moduli result in an error
    #[test]
    fn row_mismatching_moduli() {
        let mut mat_1 = MatZq::new(3, 3, 19);
        let mat_2 = MatZq::new(3, 3, 17);

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

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

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

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

#[cfg(test)]
mod test_swaps {
    use super::MatZq;
    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 = MatZq::from_str("[[1, 2, 3],[4, 5, 6]] mod 7").unwrap();
        let cmp = MatZq::from_str("[[1, 5, 3],[4, 2, 6]] mod 7").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 = MatZq::from_str(&format!(
            "[[{}, 1, 3, 4],[{}, 4, {}, 5],[7, 6, 8, 9]] mod {}",
            i64::MIN,
            i64::MAX,
            i64::MAX,
            u64::MAX
        ))
        .unwrap();
        let cmp = MatZq::from_str(&format!(
            "[[{}, 1, 3, 4],[{}, 4, {}, 5],[7, 6, 8, 9]] mod {}",
            i64::MAX,
            i64::MAX,
            i64::MIN,
            u64::MAX
        ))
        .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 = MatZq::from_str(&format!(
            "[[{}, 1, 3, 4],[{}, 4, {}, 5],[7, 6, 8, 9]] mod {}",
            i64::MIN,
            i64::MAX,
            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 = MatZq::new(5, 2, 5);

        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());
    }

    /// Ensure that `swap_entries` can properly handle negative indexing.
    #[test]
    fn entries_negative_indexing() {
        let mut matrix = MatZq::identity(2, 2, 2);

        matrix.swap_entries(-2, -2, -2, -1).unwrap();
        assert_eq!("[[0, 1],[0, 1]] mod 2", matrix.to_string());
    }

    /// Ensures that swapping columns works fine for small entries
    #[test]
    fn columns_small_entries() {
        let mut matrix = MatZq::from_str("[[1, 2, 3],[4, 5, 6]] mod 17").unwrap();
        let cmp_vec_0 = MatZq::from_str("[[1],[4]] mod 17").unwrap();
        let cmp_vec_1 = MatZq::from_str("[[3],[6]] mod 17").unwrap();
        let cmp_vec_2 = MatZq::from_str("[[2],[5]] mod 17").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 = MatZq::from_str(&format!(
            "[[{}, 1, 3, 4],[{}, 4, {}, 5],[7, 6, 8, 9]] mod {}",
            i64::MIN,
            i64::MAX,
            i64::MAX,
            u64::MAX
        ))
        .unwrap();
        let cmp_vec_0 =
            MatZq::from_str(&format!("[[3],[{}],[8]] mod {}", i64::MAX, u64::MAX)).unwrap();
        let cmp_vec_1 = MatZq::from_str(&format!("[[1],[4],[6]] mod {}", u64::MAX)).unwrap();
        let cmp_vec_2 = MatZq::from_str(&format!(
            "[[{}],[{}],[7]] mod {}",
            i64::MIN,
            i64::MAX,
            u64::MAX
        ))
        .unwrap();
        let cmp_vec_3 = MatZq::from_str(&format!("[[4],[5],[9]] mod {}", u64::MAX)).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 = MatZq::from_str(&format!(
            "[[{}, 1, 3, 4],[{}, 4, {}, 5],[7, 6, 8, 9]] mod {}",
            i64::MIN,
            i64::MAX,
            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 = MatZq::new(5, 2, 5);

        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 = MatZq::from_str("[[1, 2],[3, 4]] mod 12").unwrap();
        let cmp_vec_0 = MatZq::from_str("[[3, 4]] mod 12").unwrap();
        let cmp_vec_1 = MatZq::from_str("[[1, 2]] mod 12").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 = MatZq::from_str(&format!(
            "[[{}, 1, 3, 4],[7, 6, 8, 9],[{}, 4, {}, 5]] mod {}",
            i64::MIN,
            i64::MAX,
            i64::MAX,
            u64::MAX
        ))
        .unwrap();
        let cmp_vec_0 = MatZq::from_str(&format!(
            "[[{}, 4, {}, 5]] mod {}",
            i64::MAX,
            i64::MAX,
            u64::MAX
        ))
        .unwrap();
        let cmp_vec_1 = MatZq::from_str(&format!("[[7, 6, 8, 9]] mod {}", u64::MAX)).unwrap();
        let cmp_vec_2 =
            MatZq::from_str(&format!("[[{}, 1, 3, 4]] mod {}", i64::MIN, u64::MAX)).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 = MatZq::from_str(&format!(
            "[[{}, 1, 3, 4],[{}, 4, {}, 5],[7, 6, 8, 9]] mod {}",
            i64::MIN,
            i64::MAX,
            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 = MatZq::new(2, 4, 5);

        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 = MatZq::identity(3, 3, 17);
        let mut matrix2 = MatZq::identity(3, 3, 17);

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

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

#[cfg(test)]
mod test_reverses {
    use super::MatZq;
    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 = MatZq::from_str("[[1, 2, 3],[4, 5, 6]] mod 7").unwrap();
        let cmp_vec_0 = MatZq::from_str("[[1],[4]] mod 7").unwrap();
        let cmp_vec_1 = MatZq::from_str("[[2],[5]] mod 7").unwrap();
        let cmp_vec_2 = MatZq::from_str("[[3],[6]] mod 7").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 = MatZq::from_str(&format!(
            "[[{}, 1, 3, 4],[{}, 4, {}, 5],[7, 6, 8, 9]] mod {}",
            i64::MIN,
            i64::MAX,
            i64::MAX,
            u64::MAX
        ))
        .unwrap();
        let cmp_vec_0 = MatZq::from_str(&format!(
            "[[{}],[{}],[7]] mod {}",
            i64::MIN,
            i64::MAX,
            u64::MAX
        ))
        .unwrap();
        let cmp_vec_1 = MatZq::from_str(&format!("[[1],[4],[6]] mod {}", u64::MAX)).unwrap();
        let cmp_vec_2 =
            MatZq::from_str(&format!("[[3],[{}],[8]] mod {}", i64::MAX, u64::MAX)).unwrap();
        let cmp_vec_3 = MatZq::from_str(&format!("[[4],[5],[9]] mod {}", u64::MAX)).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 = MatZq::from_str("[[1, 2],[3, 4]] mod 6").unwrap();
        let cmp_vec_0 = MatZq::from_str("[[1, 2]] mod 6").unwrap();
        let cmp_vec_1 = MatZq::from_str("[[3, 4]] mod 6").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 = MatZq::from_str(&format!(
            "[[{}, 1, 3, 4],[7, 6, 8, 9],[{}, 4, {}, 5]] mod {}",
            i64::MIN,
            i64::MAX,
            i64::MAX,
            u64::MAX
        ))
        .unwrap();
        let cmp_vec_0 =
            MatZq::from_str(&format!("[[{}, 1, 3, 4]] mod {}", i64::MIN, u64::MAX)).unwrap();
        let cmp_vec_1 = MatZq::from_str(&format!("[[7, 6, 8, 9]] mod {}", u64::MAX)).unwrap();
        let cmp_vec_2 = MatZq::from_str(&format!(
            "[[{}, 4, {}, 5]] mod {}",
            i64::MAX,
            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_change_modulus {
    use super::MatZq;
    use crate::integer_mod_q::Modulus;
    use std::str::FromStr;

    /// Ensures that the modulus is changed correctly.
    #[test]
    fn modulus_correct() {
        let mut matrix = MatZq::from_str("[[1, 2, 3],[4, 5, 6]] mod 7").unwrap();
        let modulus = Modulus::from(8);

        matrix.change_modulus(&modulus);

        assert_eq!("[[1, 2, 3],[4, 5, 6]] mod 8", matrix.to_string());
    }

    /// Ensures that the modulus is changed correctly, if the modulus is big.
    #[test]
    fn big_modulus_correct() {
        let mut matrix =
            MatZq::from_str(&format!("[[1, 2, 3],[4, 5, 6]] mod {}", i64::MAX)).unwrap();
        let modulus = Modulus::from(u64::MAX);

        matrix.change_modulus(&modulus);

        assert_eq!(
            format!("[[1, 2, 3],[4, 5, 6]] mod {}", u64::MAX),
            matrix.to_string()
        );
    }

    /// Ensures that the matrix is reduced correctly.
    #[test]
    fn reduced_correct() {
        let mut matrix = MatZq::from_str("[[1, 2, 3],[4, 5, 6]] mod 7").unwrap();
        let modulus = Modulus::from(2);

        matrix.change_modulus(&modulus);

        assert_eq!("[[1, 0, 1],[0, 1, 0]] mod 2", matrix.to_string());
    }
}

#[cfg(test)]
mod test_set_submatrix {
    use crate::{
        integer::MatZ,
        integer_mod_q::{MatZq, Modulus},
        traits::MatrixSetSubmatrix,
    };
    use std::str::FromStr;

    /// Ensure that the entire matrix can be set.
    #[test]
    fn entire_matrix() {
        let modulus = Modulus::from(u64::MAX);
        let mut mat = MatZq::from((&MatZ::sample_uniform(10, 10, -100, 100).unwrap(), &modulus));
        let identity = MatZq::identity(10, 10, &modulus);

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

        assert_eq!(identity, mat);
    }

    /// Ensure that matrix access out of bounds leads to an error.
    #[test]
    fn out_of_bounds() {
        let modulus = Modulus::from(u64::MAX);
        let mut mat = MatZq::identity(10, 10, &modulus);

        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 modulus = Modulus::from(u64::MAX);
        let mut mat = MatZq::identity(10, 10, &modulus);

        assert!(
            mat.set_submatrix(0, 0, &MatZq::identity(11, 11, &modulus), 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 modulus = Modulus::from(u64::MAX);
        let mut mat = MatZq::from((
            &MatZ::from_str(&format!("[[1, {}],[-{}, 0]]", u64::MAX, u64::MAX)).unwrap(),
            &modulus,
        ));
        let cmp_mat = MatZq::from((
            &MatZ::from_str(&format!("[[-{}, 0],[-{}, 0]]", u64::MAX, u64::MAX)).unwrap(),
            &modulus,
        ));

        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 modulus = Modulus::from(u64::MAX);
        let mut mat = MatZq::identity(10, 10, &modulus);

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

    /// Ensure that different moduli cause the set_submatrix to fail.
    #[test]
    fn different_moduli() {
        let modulus1 = Modulus::from(u64::MAX);
        let mut mat1 = MatZq::identity(10, 10, &modulus1);

        let modulus2 = Modulus::from(u64::MAX - 1);
        let mat2 = MatZq::identity(10, 10, &modulus2);

        assert!(mat1.set_submatrix(0, 0, &mat2.clone(), 0, 9, 0, 9).is_err());
    }
}