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
// Copyright © 2023 Marcel Luca Schmidt, Sven Moog
//
// 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/>.

//! Implementations to get information about a [`MatZq`] matrix.

use super::MatZq;
use crate::{
    integer::{MatZ, Z},
    integer_mod_q::{Modulus, Zq, fmpz_mod_helpers::length},
    traits::{MatrixDimensions, MatrixGetEntry, MatrixGetSubmatrix, MatrixSetEntry},
};
use flint_sys::{
    fmpz::{fmpz, fmpz_init_set},
    fmpz_mat::fmpz_mat_set,
    fmpz_mod_mat::{
        fmpz_mod_mat_entry, fmpz_mod_mat_init_set, fmpz_mod_mat_window_clear,
        fmpz_mod_mat_window_init,
    },
};
use std::mem::MaybeUninit;

impl MatZq {
    /// Creates a [`MatZ`] where each entry is a representative of the
    /// equivalence class of each entry from a [`MatZq`].
    ///
    /// The values in the output matrix are in the range of `[0, modulus)`.
    /// Use [`MatZq::get_representative_least_absolute_residue`] if they should be
    /// in the range `[-modulus/2, modulus/2]`.
    ///
    /// Returns the matrix as a [`MatZ`].
    ///
    /// # Examples
    /// ```
    /// use qfall_math::integer::MatZ;
    /// use qfall_math::integer_mod_q::MatZq;
    /// use std::str::FromStr;
    ///
    /// let mat_zq = MatZq::from_str("[[1, 2],[3, -1]] mod 5").unwrap();
    ///
    /// let mat_z = mat_zq.get_representative_least_nonnegative_residue();
    ///
    /// assert_eq!(mat_z.to_string(), "[[1, 2],[3, 4]]");
    /// ```
    pub fn get_representative_least_nonnegative_residue(&self) -> MatZ {
        let mut out = MatZ::new(self.get_num_rows(), self.get_num_columns());
        unsafe { fmpz_mat_set(&mut out.matrix, &self.matrix.mat[0]) };
        out
    }

    /// Creates a [`MatZ`] where each entry is a representative of the
    /// equivalence class of each entry from a [`MatZq`] with the
    /// representatives close to `0`.
    ///
    /// The values in the output matrix are in the range of `[-modulus/2, modulus/2]`.
    /// For even moduli, the positive representative is chosen for the element `modulus / 2`.
    /// Use [`MatZq::get_representative_least_nonnegative_residue`] if they should be
    /// in the range `[0, modulus)`.
    ///
    /// Returns an [`MatZ`] representation of the given matrix with
    /// representatives chosen close to `0`.
    ///
    /// # Examples
    /// ```
    /// use qfall_math::integer_mod_q::MatZq;
    /// use std::str::FromStr;
    ///
    /// let mat_zq_1 = MatZq::from_str("[[1,2],[3,4]] mod 5").unwrap();
    /// let mat_zq_2 = MatZq::from_str("[[1,2],[3,4]] mod 4").unwrap();
    ///
    /// let mat_z_1 = mat_zq_1.get_representative_least_absolute_residue();
    /// let mat_z_2 = mat_zq_2.get_representative_least_absolute_residue();
    ///
    /// assert_eq!(mat_z_1.to_string(), "[[1, 2],[-2, -1]]");
    /// assert_eq!(mat_z_2.to_string(), "[[1, 2],[-1, 0]]");
    /// ```
    pub fn get_representative_least_absolute_residue(&self) -> MatZ {
        let modulus: Z = Z::from(&self.modulus);
        let modulus_half = modulus.div_floor(2);

        let mut out = MatZ::new(self.get_num_rows(), self.get_num_columns());

        for row in 0..self.get_num_rows() {
            for column in 0..self.get_num_columns() {
                let entry: Z = unsafe { self.get_entry_unchecked(row, column) };

                // Not using Zq::distance for performance reasons.
                if entry > modulus_half {
                    unsafe { out.set_entry_unchecked(row, column, entry - &modulus) };
                } else {
                    unsafe { out.set_entry_unchecked(row, column, entry) };
                }
            }
        }

        out
    }

    /// Returns the modulus of the matrix as a [`Modulus`].
    ///
    /// # Examples
    /// ```
    /// use qfall_math::integer_mod_q::MatZq;
    ///
    /// let matrix = MatZq::new(5, 10, 7);
    /// let entry = matrix.get_mod();
    /// ```
    pub fn get_mod(&self) -> Modulus {
        self.modulus.clone()
    }
}

impl MatrixGetSubmatrix for MatZq {
    /// Returns a deep copy of the submatrix defined by the given parameters
    /// and does not check the provided dimensions.
    /// There is also a safe version of this function that checks the input.
    ///
    /// Parameters:
    /// `row_1`: the starting row of the submatrix
    /// `row_2`: the ending row of the submatrix
    /// `col_1`: the starting column of the submatrix
    /// `col_2`: the ending column of the submatrix
    ///
    /// Returns the submatrix from `(row_1, col_1)` to `(row_2, col_2)`(exclusively).
    ///
    /// # Examples
    /// ```
    /// use qfall_math::{integer_mod_q::MatZq, traits::MatrixGetSubmatrix};
    /// use std::str::FromStr;
    ///
    /// let mat = MatZq::identity(3, 3, 17);
    ///
    /// let sub_mat_1 = mat.get_submatrix(0, 2, 1, 1).unwrap();
    /// let sub_mat_2 = mat.get_submatrix(0, -1, 1, -2).unwrap();
    /// let sub_mat_3 = unsafe{mat.get_submatrix_unchecked(0, 3, 1, 2)};
    ///
    /// let e_2 = MatZq::from_str("[[0],[1],[0]] mod 17").unwrap();
    /// assert_eq!(e_2, sub_mat_1);
    /// assert_eq!(e_2, sub_mat_2);
    /// assert_eq!(e_2, sub_mat_3);
    /// ```
    ///
    /// # Safety
    /// To use this function safely, make sure that the selected submatrix is part
    /// of the matrix. If it is not, memory leaks, unexpected panics, etc. might
    /// occur.
    unsafe fn get_submatrix_unchecked(
        &self,
        row_1: i64,
        row_2: i64,
        col_1: i64,
        col_2: i64,
    ) -> Self {
        let mut window = MaybeUninit::uninit();
        // The memory for the elements of window is shared with self.
        unsafe {
            fmpz_mod_mat_window_init(
                window.as_mut_ptr(),
                &self.matrix,
                row_1,
                col_1,
                row_2,
                col_2,
            )
        };
        let mut window_copy = MaybeUninit::uninit();
        unsafe {
            // Deep clone of the content of the window
            fmpz_mod_mat_init_set(window_copy.as_mut_ptr(), window.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.as_mut_ptr());
        }
        MatZq {
            matrix: unsafe { window_copy.assume_init() },
            modulus: self.get_mod(),
        }
    }
}

impl MatZq {
    /// Efficiently collects all [`fmpz`]s in a [`MatZq`] without cloning them.
    ///
    /// Hence, the values on the returned [`Vec`] are intended for short-term use
    /// as the access to [`fmpz`] values could lead to memory leaks or modified values
    /// once the [`MatZq`] instance was modified or dropped.
    ///
    /// # Examples
    /// ```compile_fail
    /// use qfall_math::integer_mod_q::MatZq;
    /// use std::str::FromStr;
    ///
    /// let mat = MatZq::from_str("[[1, 2],[3, 4],[5, 6]] mod 3").unwrap();
    ///
    /// let fmpz_entries = mat.collect_entries();
    /// ```
    pub(crate) fn collect_entries(&self) -> Vec<fmpz> {
        let mut entries: Vec<fmpz> =
            Vec::with_capacity((self.get_num_rows() * self.get_num_columns()) as usize);

        for row in 0..self.get_num_rows() {
            for col in 0..self.get_num_columns() {
                // efficiently get entry without cloning the entry itself
                let entry = unsafe { *fmpz_mod_mat_entry(&self.matrix, row, col) };
                entries.push(entry);
            }
        }

        entries
    }

    /// Computes the lengths of a given vector of [`Z`] values
    /// considering the [`Modulus`] of `self`.
    ///
    /// # Examples
    /// ```compile_fail
    /// use qfall_math::integer_mod_q::MatZq;
    /// use std::str::FromStr;
    ///
    /// let mat = MatZq::from_str("[[1, 2],[3, 4]] mod 3").unwrap();
    ///
    /// let lengths = mat.collect_lengths();
    /// ```
    pub(crate) fn collect_lengths(&self) -> Vec<Z> {
        let entries_fmpz = self.collect_entries();

        let modulus_fmpz = self.matrix.mod_[0];
        let mut entry_lengths = Vec::with_capacity(entries_fmpz.len());
        for value in entries_fmpz {
            entry_lengths.push(length(&value, &modulus_fmpz));
        }

        entry_lengths
    }
}

impl MatrixDimensions for MatZq {
    /// Returns the number of rows of the matrix as a [`i64`].
    ///
    /// # Examples
    /// ```
    /// use qfall_math::integer_mod_q::MatZq;
    /// use qfall_math::traits::*;
    ///
    /// let matrix = MatZq::new(5, 6, 7);
    /// let rows = matrix.get_num_rows();
    /// ```
    fn get_num_rows(&self) -> i64 {
        self.matrix.mat[0].r
    }

    /// Returns the number of columns of the matrix as a [`i64`].
    ///
    /// # Examples
    /// ```
    /// use qfall_math::integer_mod_q::MatZq;
    /// use qfall_math::traits::*;
    ///
    /// let matrix = MatZq::new(5, 6, 7);
    /// let rows = matrix.get_num_columns();
    /// ```
    fn get_num_columns(&self) -> i64 {
        self.matrix.mat[0].c
    }
}

impl MatrixGetEntry<Z> for MatZq {
    /// Outputs the [`Z`] value of a specific matrix entry
    /// without checking whether it's 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
    ///
    /// Returns the [`Z`] value of the matrix at the position of the given
    /// row and column.
    ///
    /// # 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
    /// ```rust
    /// use qfall_math::integer_mod_q::MatZq;
    /// use qfall_math::traits::MatrixGetEntry;
    /// use qfall_math::integer::Z;
    /// use std::str::FromStr;
    ///
    /// let matrix = MatZq::from_str("[[1, 2, 3],[4, 5, 6],[7, 8, 9]] mod 10").unwrap();
    ///
    /// let entry_1 :Z = unsafe { matrix.get_entry_unchecked(0, 2) };
    /// let entry_2 :Z = unsafe { matrix.get_entry_unchecked(2, 1) };
    /// let entry_3 :Z = unsafe { matrix.get_entry_unchecked(2, 1) };
    ///
    /// assert_eq!(3, entry_1);
    /// assert_eq!(8, entry_2);
    /// assert_eq!(8, entry_3);
    /// ```
    unsafe fn get_entry_unchecked(&self, row: i64, column: i64) -> Z {
        let mut out = Z::default();
        let entry = unsafe { fmpz_mod_mat_entry(&self.matrix, row, column) };
        unsafe { fmpz_init_set(&mut out.value, entry) };

        out
    }
}

impl MatrixGetEntry<Zq> for MatZq {
    /// Outputs the [`Zq`] value of a specific matrix entry
    /// without checking whether it's 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
    ///
    /// Returns the [`Zq`] value of the matrix at the position of the given
    /// row and column.
    ///
    /// # 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
    /// ```rust
    /// use qfall_math::integer_mod_q::{MatZq, Zq};
    /// use qfall_math::traits::MatrixGetEntry;
    /// use std::str::FromStr;
    ///
    /// let matrix = MatZq::from_str("[[1, 2, 3],[4, 5, 6],[7, 8, 9]] mod 10").unwrap();
    ///
    /// assert_eq!(Zq::from((3, 10)), unsafe { matrix.get_entry_unchecked(0, 2) } );
    /// assert_eq!(Zq::from((8, 10)), unsafe { matrix.get_entry_unchecked(2, 1) } );
    /// assert_eq!(Zq::from((8, 10)), unsafe { matrix.get_entry_unchecked(2, 1) } );
    /// ```
    unsafe fn get_entry_unchecked(&self, row: i64, column: i64) -> Zq {
        let mut out = Zq::from((0, &self.modulus));
        let entry = unsafe { fmpz_mod_mat_entry(&self.matrix, row, column) };
        unsafe { fmpz_init_set(&mut out.value.value, entry) };

        out
    }
}

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

    /// Ensure that getting entries works on the edge.
    #[test]
    fn get_edges() {
        let matrix = MatZq::new(5, 10, u64::MAX);

        let entry_1: Z = matrix.get_entry(0, 0).unwrap();
        let entry_2: Z = matrix.get_entry(4, 9).unwrap();

        assert_eq!(0, entry_1);
        assert_eq!(0, entry_2);
    }

    /// Ensure that getting 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!(i64::MAX, entry);
    }

    /// Ensure that getting 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 getting 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 getting 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 matrix: MatZq = MatZq::new(5, 10, 7);

        assert!(MatrixGetEntry::<Z>::get_entry(&matrix, 5, 1).is_err());
        assert!(MatrixGetEntry::<Z>::get_entry(&matrix, -6, 1).is_err());
        assert!(MatrixGetEntry::<Zq>::get_entry(&matrix, 5, 1).is_err());
        assert!(MatrixGetEntry::<Zq>::get_entry(&matrix, -6, 1).is_err());
    }

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

        assert!(MatrixGetEntry::<Z>::get_entry(&matrix, 1, 10).is_err());
        assert!(MatrixGetEntry::<Z>::get_entry(&matrix, 1, -11).is_err());
        assert!(MatrixGetEntry::<Zq>::get_entry(&matrix, 1, 10).is_err());
        assert!(MatrixGetEntry::<Zq>::get_entry(&matrix, 1, -11).is_err());
    }

    /// Ensure that negative indices return the correct values.
    #[test]
    fn negative_indexing() {
        let matrix = MatZq::from_str("[[1, 2, 3],[4, 5, 6],[7, 8, 9]] mod 10").unwrap();

        let entry_1: Z = matrix.get_entry(-1, -1).unwrap();
        let entry_2: Z = matrix.get_entry(-1, -2).unwrap();
        let entry_3: Z = matrix.get_entry(-3, -3).unwrap();
        let entry_4: Zq = matrix.get_entry(-1, -1).unwrap();
        let entry_5: Zq = matrix.get_entry(-1, -2).unwrap();
        let entry_6: Zq = matrix.get_entry(-3, -3).unwrap();

        assert_eq!(9, entry_1);
        assert_eq!(8, entry_2);
        assert_eq!(1, entry_3);
        assert_eq!(Zq::from((9, 10)), entry_4);
        assert_eq!(Zq::from((8, 10)), entry_5);
        assert_eq!(Zq::from((1, 10)), entry_6);
    }

    /// Ensure that the entry is a deep copy and not just a clone of the reference.
    #[test]
    fn memory_test() {
        let mut matrix = MatZq::new(5, 10, u64::MAX);
        let value = Zq::from((u64::MAX - 1, u64::MAX));
        matrix.set_entry(1, 1, value).unwrap();
        let entry: Z = matrix.get_entry(1, 1).unwrap();
        matrix.set_entry(1, 1, Z::ONE).unwrap();

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

    /// Ensure that no memory leak occurs in get_entry with [`Z`](crate::integer::Z).
    #[test]
    fn get_entry_z_memory() {
        let mut matrix = MatZq::new(5, 10, u64::MAX);
        matrix.set_entry(1, 1, Z::from(u64::MAX - 3)).unwrap();
        let _: Z = matrix.get_entry(1, 1).unwrap();
        matrix.set_entry(2, 2, Z::from(u64::MAX - 10)).unwrap();

        let entry: Z = matrix.get_entry(1, 1).unwrap();
        let _z = Z::from(u64::MAX);

        assert_eq!(entry, Z::from(u64::MAX - 3));
    }

    /// Ensure that no memory leak occurs in get_entry with [`Zq`](crate::integer_mod_q::Zq).
    #[test]
    fn get_entry_zq_memory() {
        let mut matrix = MatZq::new(5, 10, u64::MAX);
        matrix.set_entry(1, 1, Z::from(u64::MAX - 3)).unwrap();
        let _: Zq = matrix.get_entry(1, 1).unwrap();
        matrix.set_entry(2, 2, Z::from(u64::MAX - 10)).unwrap();

        let entry: Z = matrix.get_entry(1, 1).unwrap();
        let _z = Z::from(u64::MAX);

        assert_eq!(entry, Z::from(u64::MAX - 3));
    }

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

        let _: Z = matrix.get_entry(0, 0).unwrap();
        let _: Zq = matrix.get_entry(0, 0).unwrap();
    }
}

#[cfg(test)]
mod test_get_num {
    use crate::{integer_mod_q::MatZq, traits::MatrixDimensions};

    /// Ensure that the getter for number of rows works correctly.
    #[test]
    fn num_rows() {
        let matrix = MatZq::new(5, 10, 7);

        assert_eq!(matrix.get_num_rows(), 5);
    }

    /// Ensure that the getter for number of columns works correctly.
    #[test]
    fn num_columns() {
        let matrix = MatZq::new(5, 10, 7);

        assert_eq!(matrix.get_num_columns(), 10);
    }
}

#[cfg(test)]
mod test_get_representative_least_nonnegative_residue {
    use crate::{
        integer::Z,
        integer_mod_q::MatZq,
        traits::{MatrixDimensions, MatrixGetEntry, MatrixSetEntry},
    };

    /// Test if the dimensions are taken over correctly
    #[test]
    fn dimensions() {
        let matzq = MatZq::new(15, 17, 13);

        let matz_1 = matzq.get_representative_least_nonnegative_residue();

        assert_eq!(15, matz_1.get_num_rows());
        assert_eq!(17, matz_1.get_num_columns());
    }

    /// Test if entries are taken over correctly
    #[test]
    fn entries_taken_over_correctly() {
        let mut matzq = MatZq::new(2, 2, u64::MAX);
        matzq.set_entry(0, 0, u64::MAX - 58).unwrap();
        matzq.set_entry(0, 1, -1).unwrap();

        let matz_1 = matzq.get_representative_least_nonnegative_residue();

        assert_eq!(Z::from(u64::MAX - 1), matz_1.get_entry(0, 1).unwrap());
        assert_eq!(Z::from(u64::MAX - 58), matz_1.get_entry(0, 0).unwrap());
    }
}

#[cfg(test)]
mod test_mod {
    use crate::integer_mod_q::{MatZq, Modulus};

    /// Ensure that the getter for modulus works correctly.
    #[test]
    fn get_mod() {
        let matrix = MatZq::new(5, 10, 7);

        assert_eq!(matrix.get_mod(), Modulus::from(7));
    }

    /// Ensure that the getter for modulus works with large numbers.
    #[test]
    fn get_mod_large() {
        let matrix = MatZq::new(5, 10, u64::MAX);

        assert_eq!(matrix.get_mod(), Modulus::from(u64::MAX));
    }

    /// Ensure that no memory leak occurs in get_mod.
    #[test]
    fn get_mod_memory() {
        let matrix = MatZq::new(5, 10, u64::MAX);
        let _ = matrix.get_mod();
        let _ = Modulus::from(u64::MAX - 1);

        let modulus = matrix.get_mod();

        assert_eq!(modulus, Modulus::from(u64::MAX));
    }
}

#[cfg(test)]
mod test_get_vec {
    use crate::{integer_mod_q::MatZq, traits::MatrixGetSubmatrix};
    use std::str::FromStr;

    /// Ensure that getting a row works
    #[test]
    fn get_row_works() {
        let matrix = MatZq::from_str(&format!(
            "[[0, 0, 0],[4, {}, {}]] mod {}",
            i64::MAX,
            i64::MIN,
            u64::MAX
        ))
        .unwrap();
        let row_1 = matrix.get_row(0).unwrap();
        let row_2 = matrix.get_row(1).unwrap();

        let cmp_1 = MatZq::from_str(&format!("[[0, 0, 0]] mod {}", u64::MAX)).unwrap();
        let cmp_2 = MatZq::from_str(&format!(
            "[[4, {}, {}]] mod {}",
            i64::MAX,
            i64::MIN,
            u64::MAX
        ))
        .unwrap();

        assert_eq!(cmp_1, row_1);
        assert_eq!(cmp_2, row_2);
    }

    /// Ensure that getting a row with a negative index works
    #[test]
    fn get_row_negative_indexing_works() {
        let matrix = MatZq::from_str(&format!(
            "[[0, 0, 0],[42, {}, {}]] mod {}",
            i64::MAX,
            u64::MAX - 1,
            u64::MAX
        ))
        .unwrap();
        let row_1 = matrix.get_row(-2).unwrap();
        let row_2 = matrix.get_row(-1).unwrap();

        let cmp_1 = MatZq::from_str(&format!("[[0, 0, 0]] mod {}", u64::MAX)).unwrap();
        let cmp_2 = MatZq::from_str(&format!(
            "[[42, {}, {}]] mod {}",
            i64::MAX,
            u64::MAX - 1,
            u64::MAX
        ))
        .unwrap();

        assert_eq!(cmp_1, row_1);
        assert_eq!(cmp_2, row_2);
    }

    /// Ensure that getting a column works
    #[test]
    fn get_column_works() {
        let matrix = MatZq::from_str(&format!(
            "[[1, 0, 3],[{}, 0, 5],[{}, 0, 7]] mod {}",
            i64::MAX,
            i64::MIN,
            u64::MAX
        ))
        .unwrap();
        let column_1 = matrix.get_column(0).unwrap();
        let column_2 = matrix.get_column(1).unwrap();
        let column_3 = matrix.get_column(2).unwrap();

        let cmp_1 = MatZq::from_str(&format!(
            "[[1],[{}],[{}]] mod {}",
            i64::MAX,
            i64::MIN,
            u64::MAX
        ))
        .unwrap();
        let cmp_2 = MatZq::from_str(&format!("[[0],[0],[0]] mod {}", u64::MAX)).unwrap();
        let cmp_3 = MatZq::from_str(&format!("[[3],[5],[7]] mod {}", u64::MAX)).unwrap();

        assert_eq!(cmp_1, column_1);
        assert_eq!(cmp_2, column_2);
        assert_eq!(cmp_3, column_3);
    }

    /// Ensure that getting a column with a negative index works
    #[test]
    fn get_column_negative_indexing_works() {
        let matrix = MatZq::from_str(&format!(
            "[[42, 0, 42],[{}, 0, 17],[{}, 0, 42]] mod {}",
            i64::MAX,
            u64::MAX - 1,
            u64::MAX
        ))
        .unwrap();
        let column_1 = matrix.get_column(-3).unwrap();
        let column_2 = matrix.get_column(-2).unwrap();
        let column_3 = matrix.get_column(-1).unwrap();

        let cmp_1 = MatZq::from_str(&format!(
            "[[42],[{}],[{}]] mod {}",
            i64::MAX,
            u64::MAX - 1,
            u64::MAX
        ))
        .unwrap();
        let cmp_2 = MatZq::from_str(&format!("[[0],[0],[0]] mod {}", u64::MAX)).unwrap();
        let cmp_3 = MatZq::from_str(&format!("[[42],[17],[42]] mod {}", u64::MAX)).unwrap();

        assert_eq!(cmp_1, column_1);
        assert_eq!(cmp_2, column_2);
        assert_eq!(cmp_3, column_3);
    }

    /// Ensure that wrong row and column dimensions yields an error
    #[test]
    fn wrong_dim_error() {
        let matrix = MatZq::from_str(&format!(
            "[[1, 2, 3],[{}, 4, 5],[{}, 6, 7]] mod {}",
            i64::MAX,
            i64::MIN,
            u64::MAX
        ))
        .unwrap();
        let row_1 = matrix.get_row(-4);
        let row_2 = matrix.get_row(4);
        let column_1 = matrix.get_column(-4);
        let column_2 = matrix.get_column(4);

        assert!(row_1.is_err());
        assert!(row_2.is_err());
        assert!(column_1.is_err());
        assert!(column_2.is_err());
    }
}

#[cfg(test)]
mod test_get_submatrix {
    use crate::{
        integer::Z,
        integer_mod_q::MatZq,
        traits::{MatrixDimensions, MatrixGetSubmatrix},
    };
    use std::str::FromStr;

    /// Ensures that getting the entire matrix as a submatrix works.
    #[test]
    fn entire_matrix() {
        let mat = MatZq::identity(5, 5, i64::MAX);

        let sub_mat = mat.get_submatrix(0, 4, 0, 4).unwrap();

        assert_eq!(mat, sub_mat);
    }

    /// Ensures that a single matrix entry can be retrieved.
    #[test]
    fn matrix_single_entry() {
        let mat = MatZq::identity(5, 5, i64::MAX);

        let sub_mat = mat.get_submatrix(0, 0, 0, 0).unwrap();

        let cmp_mat = MatZq::identity(1, 1, i64::MAX);
        assert_eq!(cmp_mat, sub_mat);
    }

    /// Ensures that the dimensions of the submatrix are correct.
    #[test]
    fn correct_dimensions() {
        let mat = MatZq::identity(100, 100, i64::MAX);

        let sub_mat = mat.get_submatrix(1, 37, 0, 29).unwrap();

        assert_eq!(37, sub_mat.get_num_rows());
        assert_eq!(30, sub_mat.get_num_columns());
    }

    /// Ensures that a submatrix can be correctly retrieved for a matrix with large
    /// entries.
    #[test]
    fn large_entries() {
        let mat = MatZq::from_str(&format!(
            "[[{}, 2, 3],[1, {}, 3]] mod {}",
            u64::MAX,
            i64::MIN,
            u128::MAX
        ))
        .unwrap();

        let sub_mat = mat.get_submatrix(0, 1, 0, 1).unwrap();

        let cmp_mat = MatZq::from_str(&format!(
            "[[{}, 2],[1, {}]] mod {}",
            u64::MAX,
            i64::MIN,
            u128::MAX
        ))
        .unwrap();
        assert_eq!(cmp_mat, sub_mat);
    }

    /// Ensures that an error is returned if coordinates are addressed that are not
    /// within the matrix.
    #[test]
    fn invalid_coordinates() {
        let mat = MatZq::identity(10, 10, u64::MAX);

        assert!(mat.get_submatrix(0, 0, 0, 10).is_err());
        assert!(mat.get_submatrix(0, 10, 0, 0).is_err());
        assert!(mat.get_submatrix(0, 0, -11, 0).is_err());
        assert!(mat.get_submatrix(-11, 0, 0, 0).is_err());
    }

    /// Ensure that negative indices return the correct submatrix.
    #[test]
    fn negative_indexing() {
        let matrix = MatZq::identity(3, 3, u64::MAX);

        assert_eq!(matrix, matrix.get_submatrix(0, -1, 0, -1).unwrap());
        assert_eq!(matrix, matrix.get_submatrix(-3, -1, -3, -1).unwrap());
        assert_eq!(
            matrix.get_row(0).unwrap(),
            matrix.get_submatrix(0, -3, -3, -1).unwrap()
        );
    }

    /// Ensures that the function panics if no columns of the matrix are addressed.
    #[test]
    #[should_panic]
    fn no_columns() {
        let mat = MatZq::identity(10, 10, u64::MAX);

        let _ = mat.get_submatrix(0, 0, 6, 5);
    }

    /// Ensures that the function panics if no rows of the matrix are addressed.
    #[test]
    #[should_panic]
    fn no_rows() {
        let mat = MatZq::identity(10, 10, u64::MAX);

        let _ = mat.get_submatrix(5, 4, 0, 0);
    }

    /// Ensure that the submatrix function can be called with several types.
    #[test]
    fn availability() {
        let mat = MatZq::identity(10, 10, u64::MAX);

        let _ = mat.get_submatrix(0_i8, 0_i8, 0_i8, 0_i8);
        let _ = mat.get_submatrix(0_i16, 0_i16, 0_i16, 0_i16);
        let _ = mat.get_submatrix(0_i32, 0_i32, 0_i32, 0_i32);
        let _ = mat.get_submatrix(0_i64, 0_i64, 0_i64, 0_i64);
        let _ = mat.get_submatrix(0_u8, 0_u8, 0_u8, 0_u8);
        let _ = mat.get_submatrix(0_u16, 0_i16, 0_u16, 0_u16);
        let _ = mat.get_submatrix(0_u32, 0_i32, 0_u32, 0_u32);
        let _ = mat.get_submatrix(0_u64, 0_i64, 0_u64, 0_u64);
        let _ = mat.get_submatrix(&Z::ZERO, &Z::ZERO, &Z::ZERO, &Z::ZERO);
    }
}

#[cfg(test)]
mod test_collect_entries {
    use super::MatZq;
    use std::str::FromStr;

    /// Ensures that all entries from the matrices are actually collected in the vector.
    #[test]
    fn all_entries_collected() {
        let mat_1 = MatZq::from_str(&format!(
            "[[1, 2],[{}, {}],[3, 4]] mod {}",
            i64::MAX,
            i64::MIN,
            u64::MAX
        ))
        .unwrap();
        let mat_2 = MatZq::from_str("[[-1, 2]] mod 2").unwrap();

        let entries_1 = mat_1.collect_entries();
        let entries_2 = mat_2.collect_entries();

        assert_eq!(entries_1.len(), 6);
        assert_eq!(entries_1[0].0, 1);
        assert_eq!(entries_1[1].0, 2);
        assert!(entries_1[2].0 >= 2_i64.pow(62));
        assert!(entries_1[3].0 >= 2_i64.pow(62));
        assert_eq!(entries_1[4].0, 3);
        assert_eq!(entries_1[5].0, 4);

        assert_eq!(entries_2.len(), 2);
        assert_eq!(entries_2[0].0, 1);
        assert_eq!(entries_2[1].0, 0);
    }
}

#[cfg(test)]
mod test_collect_lengths {
    use super::{MatZq, Z};
    use std::str::FromStr;

    /// Ensures that the lengths of the matrices are collected correctly.
    #[test]
    fn lengths_correctly_computed() {
        let mat_1 = MatZq::from_str(&format!(
            "[[1, 2],[{}, {}],[3, 4]] mod {}",
            i64::MAX - 2,
            i64::MIN,
            i64::MAX - 1
        ))
        .unwrap();
        let mat_2 = MatZq::from_str("[[-1, 2]] mod 2").unwrap();

        let lengths_1 = mat_1.collect_lengths();
        let lengths_2 = mat_2.collect_lengths();

        assert_eq!(lengths_1.len(), 6);
        assert_eq!(lengths_1[0], Z::ONE);
        assert_eq!(lengths_1[1], Z::from(2));
        assert_eq!(lengths_1[2], Z::ONE);
        assert_eq!(lengths_1[3], Z::from(2));
        assert_eq!(lengths_1[4], Z::from(3));
        assert_eq!(lengths_1[5], Z::from(4));

        assert_eq!(lengths_2.len(), 2);
        assert_eq!(lengths_2[0], Z::ONE);
        assert_eq!(lengths_2[1], Z::ZERO);
    }
}

#[cfg(test)]
mod test_get_representative_least_absolute_residue {
    use super::*;
    use std::str::FromStr;

    /// Test with a large modulus.
    #[test]
    fn large_modulus() {
        let mat_zq = MatZq::from_str(&format!("[[1,2],[-1,-2]] mod {}", u64::MAX)).unwrap();

        let mat_z = mat_zq.get_representative_least_absolute_residue();

        let mat_cmp = MatZ::from_str("[[1,2],[-1,-2]]").unwrap();
        assert_eq!(mat_z.to_string(), mat_cmp.to_string());
    }

    /// Test with even modulus.
    #[test]
    fn even_modulus() {
        let mat_zq = MatZq::from_str("[[0,1,2,3,4,5,6,7,8,9,10]] mod 10").unwrap();

        let mat_z = mat_zq.get_representative_least_absolute_residue();

        let mat_cmp = MatZ::from_str("[[0,1,2,3,4,5,-4,-3,-2,-1,0]]").unwrap();
        assert_eq!(mat_z.to_string(), mat_cmp.to_string());
    }

    /// Test with uneven modulus.
    #[test]
    fn uneven_modulus() {
        let mat_zq = MatZq::from_str("[[0,1,2,3,4,5,6,7,8,9,10,11]] mod 11").unwrap();

        let mat_z = mat_zq.get_representative_least_absolute_residue();

        let mat_cmp = MatZ::from_str("[[0,1,2,3,4,5,-5,-4,-3,-2,-1,0]]").unwrap();
        assert_eq!(mat_z.to_string(), mat_cmp.to_string());
    }
}