use std::marker::PhantomData; use crate::{ alloc_aligned, hal::{ api::{DataView, DataViewMut, ZnxInfos}, layouts::{Backend, Data, DataMut, DataRef, ReaderFrom, WriterTo}, }, }; #[derive(PartialEq, Eq)] pub struct SvpPPol { data: D, n: usize, cols: usize, _phantom: PhantomData, } impl ZnxInfos for SvpPPol { fn cols(&self) -> usize { self.cols } fn rows(&self) -> usize { 1 } fn n(&self) -> usize { self.n } fn size(&self) -> usize { 1 } } impl DataView for SvpPPol { type D = D; fn data(&self) -> &Self::D { &self.data } } impl DataViewMut for SvpPPol { fn data_mut(&mut self) -> &mut Self::D { &mut self.data } } pub trait SvpPPolBytesOf { fn bytes_of(n: usize, cols: usize) -> usize; } impl>, B: Backend> SvpPPol where SvpPPol: SvpPPolBytesOf, { pub(crate) fn alloc(n: usize, cols: usize) -> Self { let data: Vec = alloc_aligned::(Self::bytes_of(n, cols)); Self { data: data.into(), n, cols, _phantom: PhantomData, } } pub(crate) fn from_bytes(n: usize, cols: usize, bytes: impl Into>) -> Self { let data: Vec = bytes.into(); assert!(data.len() == Self::bytes_of(n, cols)); Self { data: data.into(), n, cols, _phantom: PhantomData, } } } pub type SvpPPolOwned = SvpPPol, B>; pub trait SvpPPolToRef { fn to_ref(&self) -> SvpPPol<&[u8], B>; } impl SvpPPolToRef for SvpPPol { fn to_ref(&self) -> SvpPPol<&[u8], B> { SvpPPol { data: self.data.as_ref(), n: self.n, cols: self.cols, _phantom: PhantomData, } } } pub trait SvpPPolToMut { fn to_mut(&mut self) -> SvpPPol<&mut [u8], B>; } impl SvpPPolToMut for SvpPPol { fn to_mut(&mut self) -> SvpPPol<&mut [u8], B> { SvpPPol { data: self.data.as_mut(), n: self.n, cols: self.cols, _phantom: PhantomData, } } } impl SvpPPol { pub(crate) fn from_data(data: D, n: usize, cols: usize) -> Self { Self { data, n, cols, _phantom: PhantomData, } } } use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; impl ReaderFrom for SvpPPol { fn read_from(&mut self, reader: &mut R) -> std::io::Result<()> { self.n = reader.read_u64::()? as usize; self.cols = reader.read_u64::()? as usize; let len: usize = reader.read_u64::()? as usize; let buf: &mut [u8] = self.data.as_mut(); if buf.len() != len { return Err(std::io::Error::new( std::io::ErrorKind::UnexpectedEof, format!("self.data.len()={} != read len={}", buf.len(), len), )); } reader.read_exact(&mut buf[..len])?; Ok(()) } } impl WriterTo for SvpPPol { fn write_to(&self, writer: &mut W) -> std::io::Result<()> { writer.write_u64::(self.n as u64)?; writer.write_u64::(self.cols as u64)?; let buf: &[u8] = self.data.as_ref(); writer.write_u64::(buf.len() as u64)?; writer.write_all(buf)?; Ok(()) } }