poulpy/poulpy-core/src/layouts/lwe_pt.rs
poulpy-core/src/layouts/lwe_pt.rsRaw
1use std::fmt;
2
3use poulpy_hal::layouts::{Backend, Data, DataMut, DataRef, Module, Zn, ZnToMut, ZnToRef, ZnxInfos};
4
5use crate::layouts::{Base2K, Degree, LWEInfos, TorusPrecision};
6
7#[derive(PartialEq, Eq, Copy, Clone, Debug)]
8pub struct LWEPlaintextLayout {
9 k: TorusPrecision,
10 base2k: Base2K,
11}
12
13impl LWEInfos for LWEPlaintextLayout {
14 fn base2k(&self) -> Base2K {
15 self.base2k
16 }
17
18 fn k(&self) -> TorusPrecision {
19 self.k
20 }
21
22 fn n(&self) -> Degree {
23 Degree(0)
24 }
25
26 fn size(&self) -> usize {
27 self.k.0.div_ceil(self.base2k.0) as usize
28 }
29}
30
31pub struct LWEPlaintext<D: Data> {
32 pub(crate) data: Zn<D>,
33 pub(crate) k: TorusPrecision,
34 pub(crate) base2k: Base2K,
35}
36
37impl<D: Data> LWEInfos for LWEPlaintext<D> {
38 fn base2k(&self) -> Base2K {
39 self.base2k
40 }
41
42 fn k(&self) -> TorusPrecision {
43 self.k
44 }
45
46 fn n(&self) -> Degree {
47 Degree(self.data.n() as u32 - 1)
48 }
49
50 fn size(&self) -> usize {
51 self.data.size()
52 }
53}
54
55pub trait LWEPlaintextAlloc {
56 fn alloc_lwe_plaintext(&self, base2k: Base2K, k: TorusPrecision) -> LWEPlaintext<Vec<u8>> {
57 LWEPlaintext {
58 data: Zn::alloc(1, 1, k.0.div_ceil(base2k.0) as usize),
59 k,
60 base2k,
61 }
62 }
63
64 fn alloc_lwe_plaintext_from_infos<A>(&self, infos: &A) -> LWEPlaintext<Vec<u8>>
65 where
66 A: LWEInfos,
67 {
68 self.alloc_lwe_plaintext(infos.base2k(), infos.k())
69 }
70}
71
72impl<B: Backend> LWEPlaintextAlloc for Module<B> {}
73
74impl LWEPlaintext<Vec<u8>> {
75 pub fn alloc_from_infos<A, M>(module: &M, infos: &A) -> Self
76 where
77 A: LWEInfos,
78 M: LWEPlaintextAlloc,
79 {
80 module.alloc_lwe_plaintext_from_infos(infos)
81 }
82
83 pub fn alloc<M>(module: &M, base2k: Base2K, k: TorusPrecision) -> Self
84 where
85 M: LWEPlaintextAlloc,
86 {
87 module.alloc_lwe_plaintext(base2k, k)
88 }
89}
90
91impl<D: DataRef> fmt::Display for LWEPlaintext<D> {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 write!(
94 f,
95 "LWEPlaintext: base2k={} k={}: {}",
96 self.base2k().0,
97 self.k().0,
98 self.data
99 )
100 }
101}
102
103pub trait LWEPlaintextToRef {
104 #[allow(dead_code)]
105 fn to_ref(&self) -> LWEPlaintext<&[u8]>;
106}
107
108impl<D: DataRef> LWEPlaintextToRef for LWEPlaintext<D> {
109 fn to_ref(&self) -> LWEPlaintext<&[u8]> {
110 LWEPlaintext {
111 data: self.data.to_ref(),
112 base2k: self.base2k,
113 k: self.k,
114 }
115 }
116}
117
118pub trait LWEPlaintextToMut {
119 #[allow(dead_code)]
120 fn to_mut(&mut self) -> LWEPlaintext<&mut [u8]>;
121}
122
123impl<D: DataMut> LWEPlaintextToMut for LWEPlaintext<D> {
124 fn to_mut(&mut self) -> LWEPlaintext<&mut [u8]> {
125 LWEPlaintext {
126 data: self.data.to_mut(),
127 base2k: self.base2k,
128 k: self.k,
129 }
130 }
131}
132
133impl<D: DataMut> LWEPlaintext<D> {
134 pub fn data_mut(&mut self) -> &mut Zn<D> {
135 &mut self.data
136 }
137}