arnaucube
arnaucube/poulpyPublic Self-hosted repository
poulpy/base2k/src/commons.rs
base2k/src/commons.rsRaw
 1pub trait Infos {
 2    /// Returns the ring degree of the polynomials.
 3    fn n(&self) -> usize;
 4
 5    /// Returns the base two logarithm of the ring dimension of the polynomials.
 6    fn log_n(&self) -> usize;
 7
 8    /// Returns the number of rows.
 9    fn rows(&self) -> usize;
10
11    /// Returns the number of polynomials in each row.
12    fn cols(&self) -> usize;
13
14    /// Returns the number of limbs per polynomial.
15    fn limbs(&self) -> usize;
16
17    /// Returns the total number of small polynomials.
18    fn poly_count(&self) -> usize;
19}
20
21pub trait VecZnxLayout: Infos {
22    type Scalar;
23
24    fn as_ptr(&self) -> *const Self::Scalar;
25    fn as_mut_ptr(&mut self) -> *mut Self::Scalar;
26
27    fn raw(&self) -> &[Self::Scalar] {
28        unsafe { std::slice::from_raw_parts(self.as_ptr(), self.n() * self.poly_count()) }
29    }
30
31    fn raw_mut(&mut self) -> &mut [Self::Scalar] {
32        unsafe { std::slice::from_raw_parts_mut(self.as_mut_ptr(), self.n() * self.poly_count()) }
33    }
34
35    fn at_ptr(&self, i: usize, j: usize) -> *const Self::Scalar {
36        #[cfg(debug_assertions)]
37        {
38            assert!(i < self.cols());
39            assert!(j < self.limbs());
40        }
41        let offset = self.n() * (j * self.cols() + i);
42        unsafe { self.as_ptr().add(offset) }
43    }
44
45    fn at_mut_ptr(&mut self, i: usize, j: usize) -> *mut Self::Scalar {
46        #[cfg(debug_assertions)]
47        {
48            assert!(i < self.cols());
49            assert!(j < self.limbs());
50        }
51        let offset = self.n() * (j * self.cols() + i);
52        unsafe { self.as_mut_ptr().add(offset) }
53    }
54
55    fn at_poly(&self, i: usize, j: usize) -> &[Self::Scalar] {
56        unsafe { std::slice::from_raw_parts(self.at_ptr(i, j), self.n()) }
57    }
58
59    fn at_poly_mut(&mut self, i: usize, j: usize) -> &mut [Self::Scalar] {
60        unsafe { std::slice::from_raw_parts_mut(self.at_mut_ptr(i, j), self.n()) }
61    }
62
63    fn at_limb(&self, j: usize) -> &[Self::Scalar] {
64        unsafe { std::slice::from_raw_parts(self.at_ptr(0, j), self.n() * self.cols()) }
65    }
66
67    fn at_limb_mut(&mut self, j: usize) -> &mut [Self::Scalar] {
68        unsafe { std::slice::from_raw_parts_mut(self.at_mut_ptr(0, j), self.n() * self.cols()) }
69    }
70}