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

//! Definitions of traits implemented and used in this crate.
//!
//! This module contains basic traits for this library. These include
//! specific traits for matrices and polynomials.

use crate::{
    error::MathError,
    utils::index::{evaluate_index, evaluate_index_for_vector, evaluate_indices_for_matrix},
};
use flint_sys::fmpz::fmpz;
use std::fmt::Display;

/// Is implemented by every type where a base-check might be needed.
/// This also includes every type of matrix, because it allows for geneceric implementations.
/// Per default, a basecheck simply returs that the bases match and no error is returned.
pub trait CompareBase<T = Self> {
    /// Compares the base elements of the objects and returns true if they match
    /// and an operation between the two provided types is possible.
    ///
    /// Parameters:
    /// - `other`: The other object whose base is compared to `self`
    ///
    /// Returns true if the bases match and false otherwise.
    /// The default implementation just returns true.
    #[allow(unused_variables)]
    fn compare_base(&self, other: &T) -> bool {
        true
    }

    /// Calls an error that gives small explanation how the base elements differ.
    /// This function only calls the error and does not check if the two actually differ.
    ///
    /// Parameters:
    /// - `other`: The other object whose base is compared to `self`
    ///
    /// Returns a MathError, typically [MathError::MismatchingModulus].
    /// The default implementation just returns `None`.
    #[allow(unused_variables)]
    fn call_compare_base_error(&self, other: &T) -> Option<MathError> {
        None
    }
}

/// Is implemented by polynomials to evaluate them for a certain input.
pub trait Evaluate<T, U> {
    /// Evaluates the object, e.g. polynomial or a matrix of polynomials,
    /// for a given input value.
    ///
    /// Parameters:
    /// - `value`: the value with which to evaluate the object.
    ///
    /// Returns the evaluation of the object.
    fn evaluate(&self, value: T) -> U;
}

/// Is implemented by polynomials to get a coefficient.
pub trait GetCoefficient<T> {
    /// Returns a coefficient of the given object, e.g. a polynomial,
    /// for a given index.
    ///
    /// Parameters:
    /// - `index`: the index of the coefficient
    ///
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type
    ///   [`OutOfBounds`](MathError::OutOfBounds) if either the index is negative
    ///   or does not fit into an [`i64`].
    /// - Returns a [`MathError`] of type
    ///   [`MismatchingModulus`](MathError::MismatchingModulus) if the base types are
    ///   not compatible. This can only happen if the base types themselves can mismatch.
    fn get_coeff(&self, index: impl TryInto<i64> + Display) -> Result<T, MathError> {
        let index = evaluate_index(index)?;
        Ok(unsafe { self.get_coeff_unchecked(index) })
    }

    /// Returns a coefficient of the given object, e.g. a polynomial,
    /// for a given index.
    ///
    /// Parameters:
    /// - `index`: the index of the coefficient
    ///
    /// Returns the coefficient of the polynomial.
    ///
    /// # Safety
    /// To use this function safely, make sure that the selected index
    /// is greater or equal than `0`.
    unsafe fn get_coeff_unchecked(&self, index: i64) -> T;
}

/// Is implemented by polynomials to set a coefficient.
pub trait SetCoefficient<T>
where
    Self: CompareBase<T>,
{
    /// Sets coefficient of the object, e.g. polynomial,
    /// for a given input value and a index.
    ///
    /// Parameters:
    /// - `index`: the coefficient to be set.
    /// - `value`: the value the coefficient is set to.
    ///
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type
    ///   [`OutOfBounds`](MathError::OutOfBounds) if either the index is negative
    ///   or does not fit into an [`i64`].
    /// - Returns a [`MathError`] of type [`MismatchingModulus`](MathError::MismatchingModulus) if the base types are
    ///   not compatible. This can only happen if the base types themselves can mismatch.
    fn set_coeff(&mut self, index: impl TryInto<i64> + Display, value: T) -> Result<(), MathError> {
        let index = evaluate_index(index)?;
        if !self.compare_base(&value) {
            return Err(self.call_compare_base_error(&value).unwrap());
        }
        unsafe {
            self.set_coeff_unchecked(index, value);
        }
        Ok(())
    }

    /// Sets coefficient of the object, e.g. polynomial,
    /// for a given input value and a index.
    ///
    /// Parameters:
    /// - `index`: the coefficient to be set.
    /// - `value`: the value the coefficient is set to.
    ///
    /// # Safety
    /// To use this function safely, make sure that the selected index
    /// is greater or equal than `0` and that the provided value has
    /// the same base so that they have a matching base.
    unsafe fn set_coeff_unchecked(&mut self, index: i64, value: T);
}

/// Is implemented by matrices to get the number of rows and number of columns of the matrix.
pub trait MatrixDimensions {
    /// Returns the number of rows of a matrix.
    fn get_num_rows(&self) -> i64;

    /// Returns the number of columns of a matrix.
    fn get_num_columns(&self) -> i64;
}

/// Is implemented by matrices to get entries.
pub trait MatrixGetEntry<T>
where
    Self: MatrixDimensions + Sized,
    T: std::clone::Clone,
{
    /// Returns the value of a specific matrix entry.
    ///
    /// Parameters:
    /// - `row`: specifies the row in which the entry is located.
    /// - `column`: specifies the column in which the entry is located.
    ///
    /// Negative indices can be used to index from the back, e.g., `-1` for
    /// the last element.
    ///
    /// Errors can occur if the provided indices are not within the dimensions of the provided matrices,
    /// the bases of the matrix and value are not compatible, e.g. different modulus.
    ///
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type [`MathError::OutOfBounds`]
    ///   if `row` or `column` do not define an entry in the mtrix
    /// - Returns a [`MathError`] of type [`MathError::MismatchingModulus`]
    ///   if the moduli are different.
    fn get_entry(
        &self,
        row: impl TryInto<i64> + Display,
        column: impl TryInto<i64> + Display,
    ) -> Result<T, MathError> {
        let (row, column) = evaluate_indices_for_matrix(self, row, column)?;
        Ok(unsafe { self.get_entry_unchecked(row, column) })
    }

    /// Returns the value of a specific matrix entry
    /// without performing any checks, e.g. checking whether the entry 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.
    ///
    /// # 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.
    unsafe fn get_entry_unchecked(&self, row: i64, column: i64) -> T;

    /// Outputs a [`Vec<Vec<T>>`] containing all entries of the matrix s.t.
    /// any entry in row `i` and column `j` can be accessed via `entries[i][j]`
    /// if `entries = matrix.get_entries`.
    ///
    /// # Examples
    /// ```
    /// use qfall_math::{integer::{MatZ, Z}, traits::*};
    /// let matrix = MatZ::sample_uniform(3, 3, 0, 16).unwrap();
    ///
    /// let entries = matrix.get_entries();
    /// let mut added_entries = Z::default();
    /// for row in entries {
    ///     for entry in row {
    ///         added_entries += entry;
    ///     }
    /// }
    /// ```
    fn get_entries(&self) -> Vec<Vec<T>> {
        let mut entries =
            vec![Vec::with_capacity(self.get_num_columns() as usize); self.get_num_rows() as usize];

        for i in 0..self.get_num_rows() {
            for j in 0..self.get_num_columns() {
                let entry = unsafe { self.get_entry_unchecked(i, j) };
                entries[i as usize].push(entry);
            }
        }

        entries
    }

    /// Outputs a [`Vec<T>`] containing all entries of the matrix in a row-wise order, i.e.
    /// a matrix `[[2, 3, 4],[5, 6, 7]]` can be accessed via this function in this order `[2, 3, 4, 5, 6, 7]`.
    ///
    /// # Examples
    /// ```
    /// use qfall_math::{integer::{MatZ, Z}, traits::*};
    /// let matrix = MatZ::sample_uniform(3, 3, 0, 16).unwrap();
    ///
    /// let entries = matrix.get_entries_rowwise();
    /// let mut added_entries = Z::default();
    /// for entry in entries {
    ///     added_entries += entry;
    /// }
    /// ```
    fn get_entries_rowwise(&self) -> Vec<T> {
        let mut entries =
            Vec::with_capacity((self.get_num_rows() * self.get_num_columns()) as usize);

        for i in 0..self.get_num_rows() {
            for j in 0..self.get_num_columns() {
                let entry = unsafe { self.get_entry_unchecked(i, j) };
                entries.push(entry);
            }
        }

        entries
    }

    /// Outputs a [`Vec<T>`] containing all entries of the matrix in a column-wise order, i.e.
    /// a matrix `[[2, 3, 4],[5, 6, 7]]` can be accessed via this function in this order `[2, 5, 3, 6, 4, 7]`.
    ///
    /// # Examples
    /// ```
    /// use qfall_math::{integer::{MatZ, Z}, traits::*};
    /// let matrix = MatZ::sample_uniform(3, 3, 0, 16).unwrap();
    ///
    /// let entries = matrix.get_entries_columnwise();
    /// let mut added_entries = Z::default();
    /// for entry in entries {
    ///     added_entries += entry;
    /// }
    /// ```
    fn get_entries_columnwise(&self) -> Vec<T> {
        let mut entries =
            Vec::with_capacity((self.get_num_rows() * self.get_num_columns()) as usize);

        for j in 0..self.get_num_columns() {
            for i in 0..self.get_num_rows() {
                let entry = unsafe { self.get_entry_unchecked(i, j) };
                entries.push(entry);
            }
        }

        entries
    }
}

/// Is implemented by Matrices to get submatrices such as rows, columns, etc.
pub trait MatrixGetSubmatrix
where
    Self: Sized + MatrixDimensions,
{
    /// Outputs the row vector of the specified row.
    ///
    /// Parameters:
    /// - `row`: specifies the row of the matrix to return
    ///
    /// Negative indices can be used to index from the back, e.g., `-1` for
    /// the last element.
    ///
    /// Returns a row vector of the matrix at the position of the given
    /// `row` or an error if specified row is not part of the matrix.
    ///
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type [`OutOfBounds`](MathError::OutOfBounds)
    ///   if specified row is not part of the matrix.
    fn get_row(&self, row: impl TryInto<i64> + Display + Clone) -> Result<Self, MathError> {
        let row = evaluate_index_for_vector(row, self.get_num_rows())?;
        Ok(unsafe { self.get_row_unchecked(row) })
    }

    /// Outputs the row vector of the specified row.
    ///
    /// Parameters:
    /// - `row`: specifies the row of the matrix to return
    ///
    /// Returns a row vector of the matrix at the position of the given
    /// `row`.
    ///
    /// # Safety
    /// To use this function safely, make sure that the selected row is part
    /// of the matrix. If it is not, memory leaks, unexpected panics, etc. might
    /// occur.
    unsafe fn get_row_unchecked(&self, row: i64) -> Self {
        unsafe { self.get_submatrix_unchecked(row, row + 1, 0, self.get_num_columns()) }
    }

    /// Outputs the column vector of the specified column.
    ///
    /// Parameters:
    /// - `column`: specifies the column of the matrix to return
    ///
    /// Negative indices can be used to index from the back, e.g., `-1` for
    /// the last element.
    ///
    /// Returns a column vector of the matrix at the position of the given
    /// `column` or an error if specified column is not part of the matrix.
    ///
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type [`OutOfBounds`](MathError::OutOfBounds)
    ///   if specified column is not part of the matrix.
    fn get_column(&self, column: impl TryInto<i64> + Display + Clone) -> Result<Self, MathError> {
        let column = evaluate_index_for_vector(column, self.get_num_columns())?;
        Ok(unsafe { self.get_column_unchecked(column) })
    }

    /// Outputs the column vector of the specified column.
    ///
    /// Parameters:
    /// - `column`: specifies the row of the matrix to return
    ///
    /// Returns a column vector of the matrix at the position of the given
    /// `column`.
    ///
    /// # Safety
    /// To use this function safely, make sure that the selected column is part
    /// of the matrix. If it is not, memory leaks, unexpected panics, etc. might
    /// occur.
    unsafe fn get_column_unchecked(&self, column: i64) -> Self {
        unsafe { self.get_submatrix_unchecked(0, self.get_num_rows(), column, column + 1) }
    }

    /// Returns a deep copy of the submatrix defined by the given parameters.
    /// All entries starting from `(row_1, col_1)` to `(row_2, col_2)`(inclusively) are collected in
    /// a new matrix.
    /// Note that `row_1 >= row_2` and `col_1 >= col_2` must hold after converting negative indices.
    /// Otherwise the function will panic.
    ///
    /// Parameters:
    /// `row_1`: the starting row of the specified submatrix
    /// `row_2`: the ending row of the specified submatrix
    /// `col_1`: the starting column of the specified submatrix
    /// `col_2`: the ending column of the specified submatrix
    ///
    /// Negative indices can be used to index from the back, e.g., `-1` for
    /// the last element.
    ///
    /// Returns the submatrix from `(row_1, col_1)` to `(row_2, col_2)`(inclusively)
    /// or an error if any provided row or column is larger than the matrix.
    ///
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type [`MathError::OutOfBounds`]
    ///   if any provided row or column is larger than the matrix.
    ///
    /// # Panics ...
    /// - if `col_1 > col_2` or `row_1 > row_2`.
    fn get_submatrix(
        &self,
        row_1: impl TryInto<i64> + Display,
        row_2: impl TryInto<i64> + Display,
        col_1: impl TryInto<i64> + Display,
        col_2: impl TryInto<i64> + Display,
    ) -> Result<Self, MathError> {
        let (row_1, col_1) = evaluate_indices_for_matrix(self, row_1, col_1)?;
        let (row_2, col_2) = evaluate_indices_for_matrix(self, row_2, col_2)?;

        assert!(
            row_2 >= row_1,
            "The number of rows must be positive, i.e. row_2 ({row_2}) must be greater or equal row_1 ({row_1})"
        );

        assert!(
            col_2 >= col_1,
            "The number of columns must be positive, i.e. col_2 ({col_2}) must be greater or equal col_1 ({col_1})"
        );

        // increase both values to have an inclusive capturing of the matrix entries
        let (row_2, col_2) = (row_2 + 1, col_2 + 1);
        Ok(unsafe { self.get_submatrix_unchecked(row_1, row_2, col_1, col_2) })
    }

    /// 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).
    ///
    /// # 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;

    /// Outputs a [`Vec`] containing all rows of the matrix in order.
    /// Use this function for simple iteration over the rows of the matrix.
    ///
    /// # Example
    /// ```
    /// use qfall_math::{integer::MatZ, traits::MatrixGetSubmatrix};
    /// let matrix = MatZ::sample_uniform(3, 3, 0, 16).unwrap();
    ///
    /// let mut added_rows = MatZ::new(1, 3);
    /// for row in matrix.get_rows() {
    ///     added_rows = added_rows + row;
    /// }
    /// ```
    ///
    /// If an index is required, use `.iter().enumerate()`, e.g. in this case.
    /// ```
    /// use qfall_math::{integer::MatZ, traits::*};
    /// let mut matrix = MatZ::sample_uniform(3, 3, 0, 16).unwrap();
    ///
    /// let mut added_rows = MatZ::new(1, 3);
    /// for (i, row) in matrix.get_rows().iter().enumerate() {
    ///     added_rows = added_rows + row;
    ///     matrix.set_row(i, &added_rows, 0).unwrap();
    /// }
    /// ```
    fn get_rows(&self) -> Vec<Self> {
        let mut rows = Vec::with_capacity(self.get_num_rows() as usize);

        for i in 0..self.get_num_rows() {
            let entry = unsafe { self.get_row_unchecked(i) };
            rows.push(entry);
        }

        rows
    }

    /// Outputs a [`Vec`] containing all columns of the matrix in order.
    /// Use this function for simple iteration over the columns of the matrix.
    ///
    /// # Example
    /// ```
    /// use qfall_math::{integer::MatZ, traits::MatrixGetSubmatrix};
    /// let matrix = MatZ::sample_uniform(3, 3, 0, 16).unwrap();
    ///
    /// let mut added_columns = MatZ::new(3, 1);
    /// for column in matrix.get_columns() {
    ///     added_columns = added_columns + column;
    /// }
    /// ```
    ///
    /// If an index is required, use `.iter().enumerate()`, e.g. in this case.
    /// ```
    /// use qfall_math::{integer::MatZ, traits::*};
    /// let mut matrix = MatZ::sample_uniform(3, 3, 0, 16).unwrap();
    ///
    /// let mut added_columns = MatZ::new(3, 1);
    /// for (i, column) in matrix.get_columns().iter().enumerate() {
    ///     added_columns = added_columns + column;
    ///     matrix.set_column(i, &added_columns, 0).unwrap();
    /// }
    /// ```
    fn get_columns(&self) -> Vec<Self> {
        let mut columns = Vec::with_capacity(self.get_num_columns() as usize);

        for i in 0..self.get_num_columns() {
            let entry = unsafe { self.get_column_unchecked(i) };
            columns.push(entry);
        }

        columns
    }
}

/// Is implemented by matrices to set entries.
pub trait MatrixSetEntry<T>
where
    Self: CompareBase<T> + MatrixDimensions + Sized,
{
    /// Sets the value of a specific matrix entry according to a given value.
    ///
    /// 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, but after conversion they must be within the matrix dimensions.
    ///
    /// Errors can occur if the provided indices are not within the dimensions of the provided matrices,
    /// the bases of the matrix and value are not compatible, e.g. different modulus.
    ///
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type [`MathError::OutOfBounds`]
    ///   if `row` or `column` do not define an entry in the mtrix
    /// - Returns a [`MathError`] of type [`MathError::MismatchingModulus`]
    ///   if the moduli are different.
    fn set_entry(
        &mut self,
        row: impl TryInto<i64> + Display,
        column: impl TryInto<i64> + Display,
        value: T,
    ) -> Result<(), MathError> {
        if !self.compare_base(&value) {
            return Err(self.call_compare_base_error(&value).unwrap());
        }
        let (row, column) = evaluate_indices_for_matrix(self, row, column)?;
        unsafe {
            self.set_entry_unchecked(row, column, value);
        }
        Ok(())
    }

    /// Sets the value of a specific matrix entry according to a given value
    /// without performing any checks, e.g. checking whether the entry is
    /// part of the matrix or if the moduli of the matrices match.
    ///
    /// 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.
    unsafe fn set_entry_unchecked(&mut self, row: i64, column: i64, value: T);
}

/// Is implemented by matrices to set more than a single entry of the matrix.
pub trait MatrixSetSubmatrix
where
    Self: Sized + MatrixDimensions + CompareBase,
{
    /// Sets a row of the given matrix to the provided row of `other`.
    ///
    /// Parameters:
    /// - `row_0`: specifies the row of `self` that should be modified
    /// - `other`: specifies the matrix providing the row replacing the row in `self`
    /// - `row_1`: specifies the row of `other` providing
    ///   the values replacing the original row in `self`
    ///
    /// Negative indices can be used to index from the back, e.g., `-1` for
    /// the last element, but after conversion they must be within the matrix dimensions.
    ///
    /// 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 its matrix
    /// or if the number of columns differs.
    ///
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type [`MathError::OutOfBounds`]
    ///   if the provided row index is not defined within the margins of the matrix.
    /// - Returns a [`MathError`] of type [`MismatchingMatrixDimension`](MathError::MismatchingMatrixDimension)
    ///   if the number of columns of `self` and `other` differ.
    /// - Returns a [`MathError`] of type [`MismatchingModulus`](MathError::MismatchingModulus) if the base types are
    ///   not compatible. This can only happen if the base types themselves can mismatch.
    fn set_row(
        &mut self,
        row_0: impl TryInto<i64> + Display,
        other: &Self,
        row_1: impl TryInto<i64> + Display,
    ) -> Result<(), MathError> {
        if !self.compare_base(other) {
            return Err(self.call_compare_base_error(other).unwrap());
        }

        let num_cols_0 = self.get_num_columns();
        let num_cols_1 = other.get_num_columns();
        if num_cols_0 != num_cols_1 {
            return Err(MathError::MismatchingMatrixDimension(format!(
                "as set_row was called on two matrices with different number of rows/columns {num_cols_0} and {num_cols_1}",
            )));
        }

        let row_0 = evaluate_index_for_vector(row_0, self.get_num_rows())?;
        let row_1 = evaluate_index_for_vector(row_1, other.get_num_rows())?;

        unsafe {
            self.set_row_unchecked(row_0, other, row_1);
        }

        Ok(())
    }
    /// Sets a row of the given matrix to the provided row of `other`.
    ///
    /// Parameters:
    /// - `row_0`: specifies the row of `self` that should be modified
    /// - `other`: specifies the matrix providing the row replacing the row in `self`
    /// - `row_1`: specifies the row of `other` providing
    ///   the values replacing the original row in `self`
    ///
    /// # Safety
    /// To use this function safely, make sure that the selected rows are part
    /// of the matrices, the columns are of the same length and the base types are the same.
    /// If not, memory leaks, unexpected panics, etc. might occur.
    unsafe fn set_row_unchecked(&mut self, row_0: i64, other: &Self, row_1: i64) {
        unsafe {
            self.set_submatrix_unchecked(
                row_0,
                0,
                row_0 + 1,
                self.get_num_columns(),
                other,
                row_1,
                0,
                row_1 + 1,
                other.get_num_columns(),
            );
        }
    }

    /// Sets a column of the given matrix to the provided column of `other`.
    ///
    /// Parameters:
    /// - `col_0`: specifies the column of `self` that should be modified
    /// - `other`: specifies the matrix providing the column replacing the column in `self`
    /// - `col_1`: specifies the column of `other` providing
    ///   the values replacing the original column in `self`
    ///
    /// Negative indices can be used to index from the back, e.g., `-1` for
    /// the last element, but after conversion they must be within the matrix dimensions.
    ///
    /// 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 its matrix
    /// or if the number of rows differs.
    ///
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type [`MathError::OutOfBounds`]
    ///   if the provided column index is not defined within the margins of the matrix.
    /// - Returns a [`MathError`] of type [`MismatchingMatrixDimension`](MathError::MismatchingMatrixDimension)
    ///   if the number of rows of `self` and `other` differ.
    /// - Returns a [`MathError`] of type [`MismatchingModulus`](MathError::MismatchingModulus) if the base types are
    ///   not compatible. This can only happen if the base types themselves can mismatch.
    fn set_column(
        &mut self,
        col_0: impl TryInto<i64> + Display,
        other: &Self,
        col_1: impl TryInto<i64> + Display,
    ) -> Result<(), MathError> {
        if !self.compare_base(other) {
            return Err(self.call_compare_base_error(other).unwrap());
        }

        let num_rows_0 = self.get_num_rows();
        let num_rows_1 = other.get_num_rows();
        if num_rows_0 != num_rows_1 {
            return Err(MathError::MismatchingMatrixDimension(format!(
                "as set_row was called on two matrices with different number of rows/columns {num_rows_0} and {num_rows_1}",
            )));
        }

        let col_0 = evaluate_index_for_vector(col_0, self.get_num_columns())?;
        let col_1 = evaluate_index_for_vector(col_1, other.get_num_columns())?;

        unsafe {
            self.set_column_unchecked(col_0, other, col_1);
        }

        Ok(())
    }

    /// Sets a column of the given matrix to the provided column of `other`.
    ///
    /// Parameters:
    /// - `col_0`: specifies the column of `self` that should be modified
    /// - `other`: specifies the matrix providing the column replacing the column in `self`
    /// - `col_1`: specifies the column of `other` providing
    ///   the values replacing the original column in `self`
    ///
    /// # Safety
    /// To use this function safely, make sure that the selected columns are part
    /// of the matrices, the columns are of the same length and the base types are the same.
    /// If not, memory leaks, unexpected panics, etc. might occur.
    unsafe fn set_column_unchecked(&mut self, col_0: i64, other: &Self, col_1: i64) {
        unsafe {
            self.set_submatrix_unchecked(
                0,
                col_0,
                self.get_num_rows(),
                col_0 + 1,
                other,
                0,
                col_1,
                self.get_num_rows(),
                col_1 + 1,
            );
        }
    }

    /// Sets the matrix entries in `self` to entries defined in `other`.
    /// The entries in `self` starting from `(row_self_start, col_self_start)` 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)` (inclusively).
    /// The original matrix must have sufficiently many entries to contain the defined submatrix.
    ///
    /// 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
    ///
    /// Negative indices can be used to index from the back, e.g., `-1` for
    /// the last element, but after conversion they must be within the matrix dimensions.
    ///
    /// Sets the submatrix of `self`, starting from the specified starting row and column
    /// to the submatrix defined in `other` by the provided indices (inclusively).
    /// Errors can occur if the provided indices are not within the dimensions of the provided matrices,
    /// the bases of the matrices are not compatible, e.g. different modulus or if the `self` can not
    /// contain the specified submatrix from `other`.
    ///
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type [`MathError::OutOfBounds`]
    ///   if any provided row or column is larger than the matrix or if entries of `self` would have to be
    ///   set that are not within `self`.
    /// - Returns a [`MathError`] of type [`MismatchingModulus`](MathError::MismatchingModulus) if the base types are
    ///   not compatible. This can only happen if the base types themselves can mismatch.
    ///
    /// # Panics ...
    /// - if `row_other_start > row_other_end` or `col_other_start > col_other_end`.
    #[allow(clippy::too_many_arguments)]
    fn set_submatrix(
        &mut self,
        row_self_start: impl TryInto<i64> + Display,
        col_self_start: impl TryInto<i64> + Display,
        other: &Self,
        row_other_start: impl TryInto<i64> + Display,
        col_other_start: impl TryInto<i64> + Display,
        row_other_end: impl TryInto<i64> + Display,
        col_other_end: impl TryInto<i64> + Display,
    ) -> Result<(), MathError> {
        if !self.compare_base(other) {
            return Err(self.call_compare_base_error(other).unwrap());
        }

        let (row_self_start, col_self_start) =
            evaluate_indices_for_matrix(self, row_self_start, col_self_start)?;
        let (row_other_start, col_other_start) =
            evaluate_indices_for_matrix(other, row_other_start, col_other_start)?;
        let (row_other_end, col_other_end) =
            evaluate_indices_for_matrix(other, row_other_end, col_other_end)?;

        assert!(
            row_other_end >= row_other_start,
            "The number of rows must be positive, i.e. row_other_end ({row_other_end}) must be greater or equal row_other_start ({row_other_start})"
        );

        assert!(
            col_other_end >= col_other_start,
            "The number of columns must be positive, i.e. col_other_end ({col_other_end}) must be greater or equal col_other_start ({col_other_start})"
        );

        // increase both values to have an inclusive capturing of the matrix entries
        let nr_rows = row_other_end - row_other_start;
        let nr_cols = col_other_end - col_other_start;
        // check if all entries that have to be set are contained in `self`
        let row_self_end =
            evaluate_index_for_vector(row_self_start + nr_rows, self.get_num_rows())?;
        let col_self_end =
            evaluate_index_for_vector(col_self_start + nr_cols, self.get_num_columns())?;
        let (row_other_end, col_other_end) = (row_other_end + 1, col_other_end + 1);
        let (row_self_end, col_self_end) = (row_self_end + 1, col_self_end + 1);

        unsafe {
            self.set_submatrix_unchecked(
                row_self_start,
                col_self_start,
                row_self_end,
                col_self_end,
                other,
                row_other_start,
                col_other_start,
                row_other_end,
                col_other_end,
            );
        }

        Ok(())
    }

    /// 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
    ///
    /// # 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.
    #[allow(clippy::too_many_arguments)]
    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,
    );
}

pub trait MatrixSwaps {
    /// 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
    ///
    /// 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.
    ///
    /// # 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>;

    /// 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
    ///
    /// 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.
    ///
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type [`OutOfBounds`](MathError::OutOfBounds)
    ///   if one of the given rows is not in the matrix.
    fn swap_rows(
        &mut self,
        row_0: impl TryInto<i64> + Display,
        row_1: impl TryInto<i64> + Display,
    ) -> Result<(), MathError>;

    /// 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
    ///
    /// 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.
    ///
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type [`OutOfBounds`](MathError::OutOfBounds)
    ///   if one of the given columns is not in the matrix.
    fn swap_columns(
        &mut self,
        col_0: impl TryInto<i64> + Display,
        col_1: impl TryInto<i64> + Display,
    ) -> Result<(), MathError>;
}

/// Is implemented by matrices to compute the tensor product.
pub trait Tensor {
    /// Computes the tensor product of `self` with `other`
    ///
    /// Parameters:
    /// - `other`: the value with which the tensor product is computed.
    ///
    /// Returns the tensor product
    fn tensor_product(&self, other: &Self) -> Self;
}

/// Is implemented by matrices to concatenate them.
pub trait Concatenate {
    type Output;

    /// Concatenates `self` with `other` vertically.
    ///
    /// Parameters:
    /// - `other`: the other matrix to concatenate with `self`
    ///
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type
    ///   [`MismatchingMatrixDimension`](MathError::MismatchingMatrixDimension)
    ///   if the matrices can not be concatenated due to mismatching dimensions
    fn concat_vertical(self, other: Self) -> Result<Self::Output, MathError>;

    /// Concatenates `self` with `other` horizontally.
    ///
    /// Parameters:
    /// - `other`: the other matrix to concatenate with `self`
    ///
    /// # Errors and Failures
    /// - Returns a [`MathError`] of type
    ///   [`MismatchingMatrixDimension`](MathError::MismatchingMatrixDimension)
    ///   if the matrices can not be concatenated due to mismatching dimensions
    fn concat_horizontal(self, other: Self) -> Result<Self::Output, MathError>;
}

/// Is implemented by basic types to calculate distances.
pub trait Distance<T = Self> {
    type Output;

    /// Computes the absolute distance between two values.
    ///
    /// Parameters:
    /// - `other`: specifies the value whose distance is calculated to `self`
    ///
    /// Returns the absolute difference, i.e. distance between the two given values
    /// as a new instance.
    fn distance(&self, other: T) -> Self::Output;
}

/// Is implemented by [`Z`](crate::integer::Z) instances to compute the `lcm`.
pub trait Lcm<T = Self> {
    type Output;

    /// Outputs the least common multiple (lcm) of the two given values
    /// with `lcm(a, 0) = 0`.
    ///
    /// Parameters:
    /// - `other`: specifies one of the values of which the `lcm` is computed
    ///
    /// Returns the least common multiple of `self` and `other` as a new value.
    fn lcm(&self, other: T) -> Self::Output;
}

/// Is implemented by basic types to raise a value to the power of another.
pub trait Pow<T> {
    type Output;

    /// Raises the value of `self` to the power of an `exp`.
    ///
    /// Parameters:
    /// - `exp`: specifies the exponent to which the value is raised
    ///
    /// Returns the value of `self` powered by `exp` as a new `Output` instance.
    fn pow(&self, exp: T) -> Result<Self::Output, MathError>;
}

/// Is implemented by [`Z`](crate::integer::Z) instances to calculate the `gcd`
pub trait Gcd<T = Self> {
    type Output;

    /// Outputs the greatest common divisor (gcd) of the two given values
    /// with `gcd(a, 0) = |a|`.
    ///
    /// Parameters:
    /// - `other`: specifies one of the values of which the gcd is computed
    ///
    /// Returns the greatest common divisor of `self` and `other`.
    fn gcd(&self, other: T) -> Self::Output;
}

/// Is implemented by [`Z`](crate::integer::Z) instances to calculate the
/// extended `gcd`
pub trait Xgcd<T = Self> {
    type Output;

    /// Outputs the extended greatest common divisor (xgcd) of the two given values,
    /// i.e. a triple `(gcd(a, b), x, y)`, where `a*x + b*y = gcd(a, b)*`.
    ///
    /// Parameters:
    /// - `other`: specifies one of the values of which the gcd is computed
    ///
    /// Returns a triple `(gcd(a, b), x, y)` containing the greatest common divisor,
    /// `x`, and `y` s.t. `gcd(a, b) = a*x + b*y`.
    fn xgcd(&self, other: T) -> Self::Output;
}

/// This is a trait to abstract Integers.
///
/// It is implemented by [`Z`](crate::integer::Z), [`Zq`](crate::integer_mod_q::Zq),
/// [`Modulus`](crate::integer_mod_q::Modulus),
/// and rust's 8, 16, 32, and 64 bit signed and unsigned integers.
/// The implementations exist for their owned and borrowed variants.
///
/// # Safety
/// Handling [`fmpz`] directly requires thinking about memory issues.
/// Read the documentation of the functions carefully before you use them.
pub(crate) unsafe trait AsInteger {
    /// Returns an [`fmpz`] representing the value.
    /// Data about the original object might not be contained in the return value.
    /// For example, [`Zq`](crate::integer_mod_q::Zq)'s return value does not
    /// contain Information about the modulus.
    ///
    /// # Safety
    /// The caller has to ensure that the returned [`fmpz`] is cleared properly.
    /// This is not happening automatically.
    /// Not clearing the [`fmpz`] is a memory leak.
    unsafe fn into_fmpz(self) -> fmpz;

    /// Returns a reference to an internal [`fmpz`] that represents the value.
    /// If the data type does not contain an [`fmpz`] completely [`None`] is returned.
    ///
    /// It is intended to be used when a read only [`fmpz`] reference is required
    /// for a Flint function call.
    /// If the data type does not contain an [`fmpz`], [`into_fmpz`](AsInteger::into_fmpz)
    /// can be used instead.
    fn get_fmpz_ref(&self) -> Option<&fmpz> {
        None
    }
}

/// Is implemented by polynomials to receive a matrix representation of their coefficients.
pub trait IntoCoefficientEmbedding<T> {
    /// Returns a canonical coefficient embedding of the value,
    /// e.g. a matrix representation of the coefficients of a polynomial.
    ///
    /// Parameters:
    /// - `size`: determines the length of the object in which the coefficients are
    ///   embedded, e.g. length of the vector
    fn into_coefficient_embedding(self, size: impl Into<i64>) -> T;
}

/// Is implemented by polynomials to reverse the coefficient embedding.
pub trait FromCoefficientEmbedding<T> {
    /// Reverses the coefficient embedding, e.g. takes as input a vector and
    /// returns a polynomial.
    ///
    /// Parameters:
    /// - `embedding`: the coefficient embedding
    fn from_coefficient_embedding(embedding: T) -> Self;
}