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_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_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_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_tmp_bytes].
144    ///
145    /// The size of buf can be obtained with [VmpPMatOps::vmp_prepare_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_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_tmp_bytes(&self, rows: usize, cols: usize) -> usize {
377        unsafe { vmp::vmp_prepare_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 ptrs: Vec<*const i64> = a.iter().map(|v| v.data.as_ptr()).collect();
395        unsafe {
396            vmp::vmp_prepare_dblptr(
397                self.0,
398                b.data(),
399                ptrs.as_ptr(),
400                b.rows() as u64,
401                b.cols() as u64,
402                buf.as_mut_ptr(),
403            );
404        }
405    }
406
407    fn vmp_apply_dft_tmp_bytes(
408        &self,
409        c_limbs: usize,
410        a_limbs: usize,
411        rows: usize,
412        cols: usize,
413    ) -> usize {
414        unsafe {
415            vmp::vmp_apply_dft_tmp_bytes(
416                self.0,
417                c_limbs as u64,
418                a_limbs as u64,
419                rows as u64,
420                cols as u64,
421            ) as usize
422        }
423    }
424
425    fn vmp_apply_dft(&self, c: &mut VecZnxDft, a: &VecZnx, b: &VmpPMat, buf: &mut [u8]) {
426        unsafe {
427            vmp::vmp_apply_dft(
428                self.0,
429                c.0,
430                c.limbs() as u64,
431                a.as_ptr(),
432                a.limbs() as u64,
433                a.n() as u64,
434                b.data(),
435                b.rows() as u64,
436                b.cols() as u64,
437                buf.as_mut_ptr(),
438            )
439        }
440    }
441
442    fn vmp_apply_dft_to_dft_tmp_bytes(
443        &self,
444        c_limbs: usize,
445        a_limbs: usize,
446        rows: usize,
447        cols: usize,
448    ) -> usize {
449        unsafe {
450            vmp::vmp_apply_dft_to_dft_tmp_bytes(
451                self.0,
452                c_limbs as u64,
453                a_limbs as u64,
454                rows as u64,
455                cols as u64,
456            ) as usize
457        }
458    }
459
460    fn vmp_apply_dft_to_dft(&self, c: &mut VecZnxDft, a: &VecZnxDft, b: &VmpPMat, buf: &mut [u8]) {
461        unsafe {
462            vmp::vmp_apply_dft_to_dft(
463                self.0,
464                c.0,
465                c.limbs() as u64,
466                a.0,
467                a.limbs() as u64,
468                b.data(),
469                b.rows() as u64,
470                b.cols() as u64,
471                buf.as_mut_ptr(),
472            )
473        }
474    }
475
476    fn vmp_apply_dft_to_dft_inplace(&self, b: &mut VecZnxDft, a: &VmpPMat, buf: &mut [u8]) {
477        unsafe {
478            vmp::vmp_apply_dft_to_dft(
479                self.0,
480                b.0,
481                b.limbs() as u64,
482                b.0,
483                b.limbs() as u64,
484                a.data(),
485                a.rows() as u64,
486                a.cols() as u64,
487                buf.as_mut_ptr(),
488            )
489        }
490    }
491}
492
493/// A helper struture that stores a 3D matrix as a contiguous array.
494/// To be passed to [VmpPMatOps::vmp_prepare_contiguous].
495///
496/// rows: index of the i-th base2K power.
497/// cols: index of the j-th limb of the i-th row.
498/// n   : polynomial degree.
499///
500/// A [Matrix3D] can be seen as a vector of [VecZnx].
501pub struct Matrix3D<T> {
502    pub data: Vec<T>,
503    pub rows: usize,
504    pub cols: usize,
505    pub n: usize,
506}
507
508impl<T: Default + Clone + std::marker::Copy> Matrix3D<T> {
509    /// Allocates a new [Matrix3D] with the respective dimensions.
510    ///
511    /// # Arguments
512    ///
513    /// * `rows`: the number of rows of the matrix.
514    /// * `cols`: the number of cols of the matrix.
515    /// # `n`: the size of each entry of the matrix.
516    ///
517    /// # Example
518    /// ```
519    /// use base2k::Matrix3D;
520    ///
521    /// let rows = 5; // #decomp
522    /// let cols = 5; // #limbs
523    /// let n = 1024; // #coeffs
524    ///
525    /// let mut mat = Matrix3D::<i64>::new(rows, cols, n);
526    /// ```
527    pub fn new(rows: usize, cols: usize, n: usize) -> Self {
528        let size = rows * cols * n;
529        Self {
530            data: vec![T::default(); size],
531            rows,
532            cols,
533            n,
534        }
535    }
536
537    /// Returns a non-mutable reference to the entry (row, col) of the [Matrix3D].
538    /// The returned array is of size n.
539    ///
540    /// # Arguments
541    ///
542    /// * `row`: the index of the row.
543    /// * `col`: the index of the col.
544    ///
545    /// # Example
546    /// ```
547    /// use base2k::Matrix3D;
548    ///
549    /// let rows = 5; // #decomp
550    /// let cols = 5; // #limbs
551    /// let n = 1024; // #coeffs
552    ///
553    /// let mut mat = Matrix3D::<i64>::new(rows, cols, n);
554    ///
555    /// let elem: &[i64] = mat.at(4, 4); // size n
556    /// ```
557    pub fn at(&self, row: usize, col: usize) -> &[T] {
558        assert!(row < self.rows && col < self.cols);
559        let idx: usize = row * (self.n * self.cols) + col * self.n;
560        &self.data[idx..idx + self.n]
561    }
562
563    /// Returns a mutable reference of the array at the (row, col) entry of the [Matrix3D].
564    /// The returned array is of size n.
565    ///
566    /// # Arguments
567    ///
568    /// * `row`: the index of the row.
569    /// * `col`: the index of the col.
570    ///
571    /// # Example
572    /// ```
573    /// use base2k::Matrix3D;
574    ///
575    /// let rows = 5; // #decomp
576    /// let cols = 5; // #limbs
577    /// let n = 1024; // #coeffs
578    ///
579    /// let mut mat = Matrix3D::<i64>::new(rows, cols, n);
580    ///
581    /// let elem: &mut [i64] = mat.at_mut(4, 4); // size n
582    /// ```
583    pub fn at_mut(&mut self, row: usize, col: usize) -> &mut [T] {
584        assert!(row < self.rows && col < self.cols);
585        let idx: usize = row * (self.n * self.cols) + col * self.n;
586        &mut self.data[idx..idx + self.n]
587    }
588
589    /// Sets the entry \[row\] of the [Matrix3D].
590    /// Typicall this is used to assign a [VecZnx] to the i-th row
591    /// of the [Matrix3D].
592    ///
593    /// # Arguments
594    ///
595    /// * `row`: the index of the row.
596    /// * `a`: the data to encode onthe row.
597    ///
598    /// # Example
599    /// ```
600    /// use base2k::{Matrix3D, VecZnx};
601    ///
602    /// let rows = 5; // #decomp
603    /// let cols = 5; // #limbs
604    /// let n = 1024; // #coeffs
605    ///
606    /// let mut mat = Matrix3D::<i64>::new(rows, cols, n);
607    ///
608    /// let a: VecZnx = VecZnx::new(n, cols);
609    ///
610    /// mat.set_row(1, &a.data);
611    /// ```
612    pub fn set_row(&mut self, row: usize, a: &[T]) {
613        assert!(
614            row < self.rows,
615            "invalid argument row: row={} > self.rows={}",
616            row,
617            self.rows
618        );
619        let idx: usize = row * (self.n * self.cols);
620        let size: usize = min(a.len(), self.cols * self.n);
621        self.data[idx..idx + size].copy_from_slice(&a[..size]);
622    }
623}