arnaucube
arnaucube/poulpyPublic Self-hosted repository
poulpy/base2k/src/vmp.rs
base2k/src/vmp.rsRaw
  1use crate::ffi::vmp;
  2use crate::{Infos, Module, VecZnx, VecZnxDft};
  3use std::cmp::min;
  4
  5/// Vector Matrix Product Prepared Matrix: a vector of [VecZnx],
  6/// stored as a 3D matrix in the DFT domain in a single contiguous array.
  7/// Each row of the [VmpPMat] can be seen as a [VecZnxDft].
  8///
  9/// The backend array of [VmpPMat] is allocate in C,
 10/// and thus must be manually freed.
 11///
 12/// [VmpPMat] is used to permform a vector matrix product between a [VecZnx] and a [VmpPMat].
 13/// See the trait [VmpPMatOps] for additional information.
 14pub struct VmpPMat {
 15    /// The pointer to the C memory.
 16    pub data: *mut vmp::vmp_pmat_t,
 17    /// The number of [VecZnxDft].
 18    pub rows: usize,
 19    /// The number of limbs in each [VecZnxDft].      
 20    pub cols: usize,
 21    /// The ring degree of each [VecZnxDft].      
 22    pub n: usize,
 23}
 24
 25impl VmpPMat {
 26    /// Returns the pointer to the [vmp_pmat_t].
 27    pub fn data(&self) -> *mut vmp::vmp_pmat_t {
 28        self.data
 29    }
 30
 31    /// Returns a copy of the backend array at index (i, j) of the [VmpPMat].
 32    /// When using [`crate::FFT64`] as backend, `T` should be [f64].
 33    /// When using [`crate::NTT120`] as backend, `T` should be [i64].
 34    ///
 35    /// # Arguments
 36    ///
 37    /// * `row`: row index (i).
 38    /// * `col`: col index (j).
 39    pub fn at<T: Default + Copy>(&self, row: usize, col: usize) -> Vec<T> {
 40        let mut res: Vec<T> = vec![T::default(); self.n];
 41
 42        if self.n < 8 {
 43            res.copy_from_slice(
 44                &self.get_backend_array::<T>()[(row + col * self.rows()) * self.n()
 45                    ..(row + col * self.rows()) * (self.n() + 1)],
 46            );
 47        } else {
 48            (0..self.n >> 3).for_each(|blk| {
 49                res[blk * 8..(blk + 1) * 8].copy_from_slice(&self.get_array(row, col, blk)[..8]);
 50            });
 51        }
 52
 53        res
 54    }
 55
 56    /// When using [`crate::FFT64`] as backend, `T` should be [f64].
 57    /// When using [`crate::NTT120`] as backend, `T` should be [i64].
 58    fn get_array<T>(&self, row: usize, col: usize, blk: usize) -> &[T] {
 59        let nrows: usize = self.rows();
 60        let ncols: usize = self.cols();
 61        if col == (ncols - 1) && (ncols & 1 == 1) {
 62            &self.get_backend_array::<T>()[blk * nrows * ncols * 8 + col * nrows * 8 + row * 8..]
 63        } else {
 64            &self.get_backend_array::<T>()[blk * nrows * ncols * 8
 65                + (col / 2) * (2 * nrows) * 8
 66                + row * 2 * 8
 67                + (col % 2) * 8..]
 68        }
 69    }
 70
 71    /// Returns a non-mutable reference of `T` of the entire contiguous array of the [VmpPMat].
 72    /// When using [`crate::FFT64`] as backend, `T` should be [f64].
 73    /// When using [`crate::NTT120`] as backend, `T` should be [i64].
 74    /// The length of the returned array is rows * cols * n.
 75    pub fn get_backend_array<T>(&self) -> &[T] {
 76        let ptr: *const T = self.data as *const T;
 77        let len: usize = (self.rows() * self.cols() * self.n() * 8) / std::mem::size_of::<T>();
 78        unsafe { &std::slice::from_raw_parts(ptr, len) }
 79    }
 80}
 81
 82/// This trait implements methods for vector matrix product,
 83/// that is, multiplying a [VecZnx] with a [VmpPMat].
 84pub trait VmpPMatOps {
 85    /// Allocates a new [VmpPMat] with the given number of rows and columns.
 86    ///
 87    /// # Arguments
 88    ///
 89    /// * `rows`: number of rows (number of [VecZnxDft]).
 90    /// * `cols`: number of cols (number of limbs of each [VecZnxDft]).
 91    fn new_vmp_pmat(&self, rows: usize, cols: usize) -> VmpPMat;
 92
 93    /// Returns the number of bytes needed as scratch space for [VmpPMatOps::vmp_prepare_contiguous].
 94    ///
 95    /// # Arguments
 96    ///
 97    /// * `rows`: number of rows of the [VmpPMat] used in [VmpPMatOps::vmp_prepare_contiguous].
 98    /// * `cols`: number of cols of the [VmpPMat] used in [VmpPMatOps::vmp_prepare_contiguous].
 99    fn vmp_prepare_contiguous_tmp_bytes(&self, rows: usize, cols: usize) -> usize;
100
101    /// Prepares a [VmpPMat] from a contiguous array of [i64].
102    /// The helper struct [Matrix3D] can be used to contruct and populate
103    /// the appropriate contiguous array.
104    ///
105    /// # Arguments
106    ///
107    /// * `b`: [VmpPMat] on which the values are encoded.
108    /// * `a`: the contiguous array of [i64] of the 3D matrix to encode on the [VmpPMat].
109    /// * `buf`: scratch space, the size of buf can be obtained with [VmpPMatOps::vmp_prepare_contiguous_tmp_bytes].
110    ///
111    /// # Example
112    /// ```
113    /// use base2k::{Module, Matrix3D, VmpPMat, VmpPMatOps, FFT64, Free};
114    /// use std::cmp::min;
115    ///
116    /// let n: usize = 1024;
117    /// let module = Module::new::<FFT64>(n);
118    /// let rows = 5;
119    /// let cols = 6;
120    ///
121    /// let mut b_mat: Matrix3D<i64> = Matrix3D::new(rows, cols, n);
122    ///
123    /// // Populates the i-th row of b_math with X^1 * 2^(i * log_w) (here log_w is undefined)
124    /// (0..min(rows, cols)).for_each(|i| {
125    ///    b_mat.at_mut(i, i)[1] = 1 as i64;
126    /// });
127    ///
128    /// let mut buf: Vec<u8> = vec![u8::default(); module.vmp_prepare_contiguous_tmp_bytes(rows, cols)];
129    ///
130    /// let mut vmp_pmat: VmpPMat = module.new_vmp_pmat(rows, cols);
131    /// module.vmp_prepare_contiguous(&mut vmp_pmat, &b_mat.data, &mut buf);
132    ///
133    /// vmp_pmat.free() // don't forget to free the memory once vmp_pmat is not needed anymore.
134    /// ```
135    fn vmp_prepare_contiguous(&self, b: &mut VmpPMat, a: &[i64], buf: &mut [u8]);
136
137    /// Prepares a [VmpPMat] from a vector of [VecZnx].
138    ///
139    /// # Arguments
140    ///
141    /// * `b`: [VmpPMat] on which the values are encoded.
142    /// * `a`: the vector of [VecZnx] to encode on the [VmpPMat].
143    /// * `buf`: scratch space, the size of buf can be obtained with [VmpPMatOps::vmp_prepare_contiguous_tmp_bytes].
144    ///
145    /// The size of buf can be obtained with [VmpPMatOps::vmp_prepare_contiguous_tmp_bytes].
146    ///
147    /// # Example
148    /// ```
149    /// use base2k::{Module, FFT64, Matrix3D, VmpPMat, VmpPMatOps, VecZnx, VecZnxOps, Free};
150    /// use std::cmp::min;
151    ///
152    /// let n: usize = 1024;
153    /// let module: Module = Module::new::<FFT64>(n);
154    /// let rows: usize = 5;
155    /// let cols: usize = 6;
156    ///
157    /// let mut vecznx: Vec<VecZnx>= Vec::new();
158    /// (0..rows).for_each(|_|{
159    ///     vecznx.push(module.new_vec_znx(cols));
160    /// });
161    ///
162    /// let mut buf: Vec<u8> = vec![u8::default(); module.vmp_prepare_contiguous_tmp_bytes(rows, cols)];
163    ///
164    /// let mut vmp_pmat: VmpPMat = module.new_vmp_pmat(rows, cols);
165    /// module.vmp_prepare_dblptr(&mut vmp_pmat, &vecznx, &mut buf);
166    ///
167    /// vmp_pmat.free();
168    /// module.free();
169    /// ```
170    fn vmp_prepare_dblptr(&self, b: &mut VmpPMat, a: &Vec<VecZnx>, buf: &mut [u8]);
171
172    /// Returns the size of the stratch space necessary for [VmpPMatOps::vmp_apply_dft].
173    ///
174    /// # Arguments
175    ///
176    /// * `c_limbs`: number of limbs of the output [VecZnxDft].
177    /// * `a_limbs`: number of limbs of the input [VecZnx].
178    /// * `rows`: number of rows of the input [VmpPMat].
179    /// * `cols`: number of cols of the input [VmpPMat].
180    fn vmp_apply_dft_tmp_bytes(
181        &self,
182        c_limbs: usize,
183        a_limbs: usize,
184        rows: usize,
185        cols: usize,
186    ) -> usize;
187
188    /// Applies the vector matrix product [VecZnxDft] x [VmpPMat].
189    ///
190    /// A vector matrix product is equivalent to a sum of [crate::SvpPPolOps::svp_apply_dft]
191    /// where each [crate::Scalar] is a limb of the input [VecZnxDft] (equivalent to an [crate::SvpPPol])
192    /// and each vector a [VecZnxDft] (row) of the [VmpPMat].
193    ///
194    /// As such, given an input [VecZnx] of `i` limbs and a [VmpPMat] of `i` rows and
195    /// `j` cols, the output is a [VecZnx] of `j` limbs.
196    ///
197    /// If there is a mismatch between the dimensions the largest valid ones are used.
198    ///
199    /// ```text
200    /// |a b c d| x |e f g| = (a * |e f g| + b * |h i j| + c * |k l m|) = |n o p|
201    ///             |h i j|
202    ///             |k l m|
203    /// ```
204    /// where each element is a [VecZnxDft].
205    ///
206    /// # Arguments
207    ///
208    /// * `c`: the output of the vector matrix product, as a [VecZnxDft].
209    /// * `a`: the left operand [VecZnx] of the vector matrix product.
210    /// * `b`: the right operand [VmpPMat] of the vector matrix product.
211    /// * `buf`: scratch space, the size can be obtained with [VmpPMatOps::vmp_apply_dft_tmp_bytes].
212    ///
213    /// # Example
214    /// ```
215    /// use base2k::{Module, VecZnx, VecZnxOps, VecZnxDft, VmpPMat, VmpPMatOps, FFT64, Free};
216    ///
217    /// let n = 1024;
218    ///
219    /// let module: Module = Module::new::<FFT64>(n);
220    /// let limbs: usize = 5;
221    ///
222    /// let rows: usize = limbs;
223    /// let cols: usize = limbs + 1;
224    /// let c_limbs: usize = cols;
225    /// let a_limbs: usize = limbs;
226    /// let tmp_bytes: usize = module.vmp_apply_dft_tmp_bytes(c_limbs, a_limbs, rows, cols);
227    ///
228    /// let mut buf: Vec<u8> = vec![0; tmp_bytes];
229    /// let mut vmp_pmat: VmpPMat = module.new_vmp_pmat(rows, cols);
230    ///
231    /// let a: VecZnx = module.new_vec_znx(limbs);
232    /// let mut c_dft: VecZnxDft = module.new_vec_znx_dft(cols);
233    /// module.vmp_apply_dft(&mut c_dft, &a, &vmp_pmat, &mut buf);
234    ///
235    /// c_dft.free();
236    /// vmp_pmat.free();
237    /// module.free();
238    /// ```
239    fn vmp_apply_dft(&self, c: &mut VecZnxDft, a: &VecZnx, b: &VmpPMat, buf: &mut [u8]);
240
241    /// Returns the size of the stratch space necessary for [VmpPMatOps::vmp_apply_dft_to_dft].
242    ///
243    /// # Arguments
244    ///
245    /// * `c_limbs`: number of limbs of the output [VecZnxDft].
246    /// * `a_limbs`: number of limbs of the input [VecZnxDft].
247    /// * `rows`: number of rows of the input [VmpPMat].
248    /// * `cols`: number of cols of the input [VmpPMat].
249    fn vmp_apply_dft_to_dft_tmp_bytes(
250        &self,
251        c_limbs: usize,
252        a_limbs: usize,
253        rows: usize,
254        cols: usize,
255    ) -> usize;
256
257    /// Applies the vector matrix product [VecZnxDft] x [VmpPMat].
258    /// The size of `buf` is given by [VmpPMatOps::vmp_apply_dft_to_dft_tmp_bytes].
259    ///
260    /// A vector matrix product is equivalent to a sum of [crate::SvpPPolOps::svp_apply_dft]
261    /// where each [crate::Scalar] is a limb of the input [VecZnxDft] (equivalent to an [crate::SvpPPol])
262    /// and each vector a [VecZnxDft] (row) of the [VmpPMat].
263    ///
264    /// As such, given an input [VecZnx] of `i` limbs and a [VmpPMat] of `i` rows and
265    /// `j` cols, the output is a [VecZnx] of `j` limbs.
266    ///
267    /// If there is a mismatch between the dimensions the largest valid ones are used.
268    ///
269    /// ```text
270    /// |a b c d| x |e f g| = (a * |e f g| + b * |h i j| + c * |k l m|) = |n o p|
271    ///             |h i j|
272    ///             |k l m|
273    /// ```
274    /// where each element is a [VecZnxDft].
275    ///
276    /// # Arguments
277    ///
278    /// * `c`: the output of the vector matrix product, as a [VecZnxDft].
279    /// * `a`: the left operand [VecZnxDft] of the vector matrix product.
280    /// * `b`: the right operand [VmpPMat] of the vector matrix product.
281    /// * `buf`: scratch space, the size can be obtained with [VmpPMatOps::vmp_apply_dft_to_dft_tmp_bytes].
282    ///
283    /// # Example
284    /// ```
285    /// use base2k::{Module, VecZnx, VecZnxDft, VmpPMat, VmpPMatOps, FFT64, Free};
286    ///
287    /// let n = 1024;
288    ///
289    /// let module: Module = Module::new::<FFT64>(n);
290    /// let limbs: usize = 5;
291    ///
292    /// let rows: usize = limbs;
293    /// let cols: usize = limbs + 1;
294    /// let c_limbs: usize = cols;
295    /// let a_limbs: usize = limbs;
296    /// let tmp_bytes: usize = module.vmp_apply_dft_to_dft_tmp_bytes(c_limbs, a_limbs, rows, cols);
297    ///
298    /// let mut buf: Vec<u8> = vec![0; tmp_bytes];
299    /// let mut vmp_pmat: VmpPMat = module.new_vmp_pmat(rows, cols);
300    ///
301    /// let a_dft: VecZnxDft = module.new_vec_znx_dft(limbs);
302    /// let mut c_dft: VecZnxDft = module.new_vec_znx_dft(cols);
303    /// module.vmp_apply_dft_to_dft(&mut c_dft, &a_dft, &vmp_pmat, &mut buf);
304    ///
305    /// a_dft.free();
306    /// c_dft.free();
307    /// vmp_pmat.free();
308    /// module.free();
309    /// ```
310    fn vmp_apply_dft_to_dft(&self, c: &mut VecZnxDft, a: &VecZnxDft, b: &VmpPMat, buf: &mut [u8]);
311
312    /// Applies the vector matrix product [VecZnxDft] x [VmpPMat] in place.
313    /// The size of `buf` is given by [VmpPMatOps::vmp_apply_dft_to_dft_tmp_bytes].
314    ///
315    /// A vector matrix product is equivalent to a sum of [crate::SvpPPolOps::svp_apply_dft]
316    /// where each [crate::Scalar] is a limb of the input [VecZnxDft] (equivalent to an [crate::SvpPPol])
317    /// and each vector a [VecZnxDft] (row) of the [VmpPMat].
318    ///
319    /// As such, given an input [VecZnx] of `i` limbs and a [VmpPMat] of `i` rows and
320    /// `j` cols, the output is a [VecZnx] of `j` limbs.
321    ///
322    /// If there is a mismatch between the dimensions the largest valid ones are used.
323    ///
324    /// ```text
325    /// |a b c d| x |e f g| = (a * |e f g| + b * |h i j| + c * |k l m|) = |n o p|
326    ///             |h i j|
327    ///             |k l m|
328    /// ```
329    /// where each element is a [VecZnxDft].
330    ///
331    /// # Arguments
332    ///
333    /// * `b`: the input and output of the vector matrix product, as a [VecZnxDft].
334    /// * `a`: the right operand [VmpPMat] of the vector matrix product.
335    /// * `buf`: scratch space, the size can be obtained with [VmpPMatOps::vmp_apply_dft_to_dft_tmp_bytes].
336    ///
337    /// # Example
338    /// ```
339    /// use base2k::{Module, VecZnx, VecZnxOps, VecZnxDft, VmpPMat, VmpPMatOps, FFT64, Free};
340    ///
341    /// let n = 1024;
342    ///
343    /// let module: Module = Module::new::<FFT64>(n);
344    /// let limbs: usize = 5;
345    ///
346    /// let rows: usize = limbs;
347    /// let cols: usize = limbs + 1;
348    /// let tmp_bytes: usize = module.vmp_apply_dft_to_dft_tmp_bytes(limbs, limbs, rows, cols);
349    ///
350    /// let mut buf: Vec<u8> = vec![0; tmp_bytes];
351    /// let a: VecZnx = module.new_vec_znx(limbs);
352    /// let mut vmp_pmat: VmpPMat = module.new_vmp_pmat(rows, cols);
353    ///
354    /// let mut c_dft: VecZnxDft = module.new_vec_znx_dft(limbs);
355    /// module.vmp_apply_dft_to_dft_inplace(&mut c_dft, &vmp_pmat, &mut buf);
356    ///
357    /// c_dft.free();
358    /// vmp_pmat.free();
359    /// module.free();
360    /// ```
361    fn vmp_apply_dft_to_dft_inplace(&self, b: &mut VecZnxDft, a: &VmpPMat, buf: &mut [u8]);
362}
363
364impl VmpPMatOps for Module {
365    fn new_vmp_pmat(&self, rows: usize, cols: usize) -> VmpPMat {
366        unsafe {
367            VmpPMat {
368                data: vmp::new_vmp_pmat(self.0, rows as u64, cols as u64),
369                rows,
370                cols,
371                n: self.n(),
372            }
373        }
374    }
375
376    fn vmp_prepare_contiguous_tmp_bytes(&self, rows: usize, cols: usize) -> usize {
377        unsafe { vmp::vmp_prepare_contiguous_tmp_bytes(self.0, rows as u64, cols as u64) as usize }
378    }
379
380    fn vmp_prepare_contiguous(&self, b: &mut VmpPMat, a: &[i64], buf: &mut [u8]) {
381        unsafe {
382            vmp::vmp_prepare_contiguous(
383                self.0,
384                b.data(),
385                a.as_ptr(),
386                b.rows() as u64,
387                b.cols() as u64,
388                buf.as_mut_ptr(),
389            );
390        }
391    }
392
393    fn vmp_prepare_dblptr(&self, b: &mut VmpPMat, a: &Vec<VecZnx>, buf: &mut [u8]) {
394        let rows: usize = b.rows();
395        let cols: usize = b.cols();
396
397        let mut mat: Matrix3D<i64> = Matrix3D::<i64>::new(rows, cols, self.n());
398
399        (0..min(rows, a.len())).for_each(|i| {
400            mat.set_row(i, &a[i].data);
401        });
402
403        self.vmp_prepare_contiguous(b, &mat.data, buf);
404
405        /*
406        NOT IMPLEMENTED IN SPQLIOS
407        let mut ptrs: Vec<*const i64> = a.iter().map(|v| v.data.as_ptr()).collect();
408        unsafe {
409            vmp_prepare_dblptr(
410                self.0,
411                b.data(),
412                ptrs.as_mut_ptr(),
413                b.rows() as u64,
414                b.cols() as u64,
415                buf.as_mut_ptr(),
416            );
417        }
418        */
419    }
420
421    fn vmp_apply_dft_tmp_bytes(
422        &self,
423        c_limbs: usize,
424        a_limbs: usize,
425        rows: usize,
426        cols: usize,
427    ) -> usize {
428        unsafe {
429            vmp::vmp_apply_dft_tmp_bytes(
430                self.0,
431                c_limbs as u64,
432                a_limbs as u64,
433                rows as u64,
434                cols as u64,
435            ) as usize
436        }
437    }
438
439    fn vmp_apply_dft(&self, c: &mut VecZnxDft, a: &VecZnx, b: &VmpPMat, buf: &mut [u8]) {
440        unsafe {
441            vmp::vmp_apply_dft(
442                self.0,
443                c.0,
444                c.limbs() as u64,
445                a.as_ptr(),
446                a.limbs() as u64,
447                a.n() as u64,
448                b.data(),
449                b.rows() as u64,
450                b.cols() as u64,
451                buf.as_mut_ptr(),
452            )
453        }
454    }
455
456    fn vmp_apply_dft_to_dft_tmp_bytes(
457        &self,
458        c_limbs: usize,
459        a_limbs: usize,
460        rows: usize,
461        cols: usize,
462    ) -> usize {
463        unsafe {
464            vmp::vmp_apply_dft_to_dft_tmp_bytes(
465                self.0,
466                c_limbs as u64,
467                a_limbs as u64,
468                rows as u64,
469                cols as u64,
470            ) as usize
471        }
472    }
473
474    fn vmp_apply_dft_to_dft(&self, c: &mut VecZnxDft, a: &VecZnxDft, b: &VmpPMat, buf: &mut [u8]) {
475        unsafe {
476            vmp::vmp_apply_dft_to_dft(
477                self.0,
478                c.0,
479                c.limbs() as u64,
480                a.0,
481                a.limbs() as u64,
482                b.data(),
483                b.rows() as u64,
484                b.cols() as u64,
485                buf.as_mut_ptr(),
486            )
487        }
488    }
489
490    fn vmp_apply_dft_to_dft_inplace(&self, b: &mut VecZnxDft, a: &VmpPMat, buf: &mut [u8]) {
491        unsafe {
492            vmp::vmp_apply_dft_to_dft(
493                self.0,
494                b.0,
495                b.limbs() as u64,
496                b.0,
497                b.limbs() as u64,
498                a.data(),
499                a.rows() as u64,
500                a.cols() as u64,
501                buf.as_mut_ptr(),
502            )
503        }
504    }
505}
506
507/// A helper struture that stores a 3D matrix as a contiguous array.
508/// To be passed to [VmpPMatOps::vmp_prepare_contiguous].
509///
510/// rows: index of the i-th base2K power.
511/// cols: index of the j-th limb of the i-th row.
512/// n   : polynomial degree.
513///
514/// A [Matrix3D] can be seen as a vector of [VecZnx].
515pub struct Matrix3D<T> {
516    pub data: Vec<T>,
517    pub rows: usize,
518    pub cols: usize,
519    pub n: usize,
520}
521
522impl<T: Default + Clone + std::marker::Copy> Matrix3D<T> {
523    /// Allocates a new [Matrix3D] with the respective dimensions.
524    ///
525    /// # Arguments
526    ///
527    /// * `rows`: the number of rows of the matrix.
528    /// * `cols`: the number of cols of the matrix.
529    /// # `n`: the size of each entry of the matrix.
530    ///
531    /// # Example
532    /// ```
533    /// use base2k::Matrix3D;
534    ///
535    /// let rows = 5; // #decomp
536    /// let cols = 5; // #limbs
537    /// let n = 1024; // #coeffs
538    ///
539    /// let mut mat = Matrix3D::<i64>::new(rows, cols, n);
540    /// ```
541    pub fn new(rows: usize, cols: usize, n: usize) -> Self {
542        let size = rows * cols * n;
543        Self {
544            data: vec![T::default(); size],
545            rows,
546            cols,
547            n,
548        }
549    }
550
551    /// Returns a non-mutable reference to the entry (row, col) of the [Matrix3D].
552    /// The returned array is of size n.
553    ///
554    /// # Arguments
555    ///
556    /// * `row`: the index of the row.
557    /// * `col`: the index of the col.
558    ///
559    /// # Example
560    /// ```
561    /// use base2k::Matrix3D;
562    ///
563    /// let rows = 5; // #decomp
564    /// let cols = 5; // #limbs
565    /// let n = 1024; // #coeffs
566    ///
567    /// let mut mat = Matrix3D::<i64>::new(rows, cols, n);
568    ///
569    /// let elem: &[i64] = mat.at(4, 4); // size n
570    /// ```
571    pub fn at(&self, row: usize, col: usize) -> &[T] {
572        assert!(row < self.rows && col < self.cols);
573        let idx: usize = row * (self.n * self.cols) + col * self.n;
574        &self.data[idx..idx + self.n]
575    }
576
577    /// Returns a mutable reference of the array at the (row, col) entry of the [Matrix3D].
578    /// The returned array is of size n.
579    ///
580    /// # Arguments
581    ///
582    /// * `row`: the index of the row.
583    /// * `col`: the index of the col.
584    ///
585    /// # Example
586    /// ```
587    /// use base2k::Matrix3D;
588    ///
589    /// let rows = 5; // #decomp
590    /// let cols = 5; // #limbs
591    /// let n = 1024; // #coeffs
592    ///
593    /// let mut mat = Matrix3D::<i64>::new(rows, cols, n);
594    ///
595    /// let elem: &mut [i64] = mat.at_mut(4, 4); // size n
596    /// ```
597    pub fn at_mut(&mut self, row: usize, col: usize) -> &mut [T] {
598        assert!(row < self.rows && col < self.cols);
599        let idx: usize = row * (self.n * self.cols) + col * self.n;
600        &mut self.data[idx..idx + self.n]
601    }
602
603    /// Sets the entry \[row\] of the [Matrix3D].
604    /// Typicall this is used to assign a [VecZnx] to the i-th row
605    /// of the [Matrix3D].
606    ///
607    /// # Arguments
608    ///
609    /// * `row`: the index of the row.
610    /// * `a`: the data to encode onthe row.
611    ///
612    /// # Example
613    /// ```
614    /// use base2k::{Matrix3D, VecZnx};
615    ///
616    /// let rows = 5; // #decomp
617    /// let cols = 5; // #limbs
618    /// let n = 1024; // #coeffs
619    ///
620    /// let mut mat = Matrix3D::<i64>::new(rows, cols, n);
621    ///
622    /// let a: VecZnx = VecZnx::new(n, cols);
623    ///
624    /// mat.set_row(1, &a.data);
625    /// ```
626    pub fn set_row(&mut self, row: usize, a: &[T]) {
627        assert!(
628            row < self.rows,
629            "invalid argument row: row={} > self.rows={}",
630            row,
631            self.rows
632        );
633        let idx: usize = row * (self.n * self.cols);
634        let size: usize = min(a.len(), self.cols * self.n);
635        self.data[idx..idx + size].copy_from_slice(&a[..size]);
636    }
637}