Skip to main content

poulpy_core/layouts/
glwe_automorphism_key.rs

1use poulpy_hal::{
2    layouts::{Backend, Data, FillUniform, HostDataMut, HostDataRef, ReaderFrom, WriterTo},
3    source::Source,
4};
5
6use crate::{
7    DeclaredK,
8    layouts::{
9        Base2K, Degree, Dnum, Dsize, GGLWE, GGLWEAtViewMut, GGLWEAtViewRef, GGLWEBackendMut, GGLWEBackendRef, GGLWEInfos,
10        GGLWELayout, GGLWEToBackendMut, GGLWEToBackendRef, GLWE, GLWEInfos, GLWEViewMut, GLWEViewRef, LWEInfos, Rank,
11        TorusPrecision,
12    },
13};
14use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
15
16use std::fmt;
17
18/// Provides lookup of automorphism keys by Galois element and access
19/// to the shared layout information.
20pub trait GLWEAutomorphismKeyHelper<K, BE: Backend> {
21    /// Returns the automorphism key associated with the Galois element `k`, if present.
22    fn get_automorphism_key(&self, k: i64) -> Option<&K>;
23    /// Returns the [`GGLWELayout`] common to all stored automorphism keys.
24    fn automorphism_key_infos(&self) -> GGLWELayout;
25}
26
27/// Plain-data descriptor for a [`GLWEAutomorphismKey`] carrying only the
28/// layout parameters (no backing buffer).
29///
30/// Implements [`LWEInfos`], [`GLWEInfos`] and [`GGLWEInfos`] so it can
31/// be passed to any generic constructor that needs layout information.
32/// For an automorphism key `rank_in == rank_out`.
33#[derive(PartialEq, Eq, Copy, Clone, Debug)]
34pub struct GLWEAutomorphismKeyLayout {
35    pub n: Degree,
36    pub base2k: Base2K,
37    pub k: TorusPrecision,
38    pub rank: Rank,
39    pub dnum: Dnum,
40    pub dsize: Dsize,
41}
42
43impl DeclaredK for GLWEAutomorphismKeyLayout {
44    fn k(&self) -> TorusPrecision {
45        self.k
46    }
47}
48
49/// GLWE automorphism (Galois) key.
50///
51/// Wraps a [`GGLWE`] together with the Galois element index `p` that
52/// identifies which automorphism this key materialises.
53///
54/// `D: Data` is the backing storage type (e.g. `Vec<u8>`, `&[u8]`,
55/// `&mut [u8]`).
56#[derive(PartialEq, Eq, Clone)]
57pub struct GLWEAutomorphismKey<D: Data> {
58    pub(crate) key: GGLWE<D>,
59    pub(crate) p: i64,
60}
61
62/// Provides read access to the Galois element index `p`.
63pub trait GetGaloisElement {
64    /// Returns the Galois element index.
65    fn p(&self) -> i64;
66}
67
68/// Provides write access to the Galois element index `p`.
69pub trait SetGaloisElement {
70    /// Sets the Galois element index.
71    fn set_p(&mut self, p: i64);
72}
73
74impl<D: HostDataMut> SetGaloisElement for GLWEAutomorphismKey<D> {
75    fn set_p(&mut self, p: i64) {
76        self.p = p
77    }
78}
79
80impl<D: HostDataRef> GetGaloisElement for GLWEAutomorphismKey<D> {
81    fn p(&self) -> i64 {
82        self.p
83    }
84}
85
86impl<D: Data> GLWEAutomorphismKey<D> {
87    /// Returns the Galois element index `p`.
88    pub fn p(&self) -> i64 {
89        self.p
90    }
91}
92
93impl<D: Data> LWEInfos for GLWEAutomorphismKey<D> {
94    fn n(&self) -> Degree {
95        self.key.n()
96    }
97
98    fn base2k(&self) -> Base2K {
99        self.key.base2k()
100    }
101
102    fn size(&self) -> usize {
103        self.key.size()
104    }
105}
106
107impl<D: Data> GLWEInfos for GLWEAutomorphismKey<D> {
108    fn rank(&self) -> Rank {
109        self.rank_out()
110    }
111}
112
113impl<D: Data> GGLWEInfos for GLWEAutomorphismKey<D> {
114    fn rank_in(&self) -> Rank {
115        self.key.rank_in()
116    }
117
118    fn rank_out(&self) -> Rank {
119        self.key.rank_out()
120    }
121
122    fn dsize(&self) -> Dsize {
123        self.key.dsize()
124    }
125
126    fn dnum(&self) -> Dnum {
127        self.key.dnum()
128    }
129}
130
131impl LWEInfos for GLWEAutomorphismKeyLayout {
132    fn base2k(&self) -> Base2K {
133        self.base2k
134    }
135
136    fn n(&self) -> Degree {
137        self.n
138    }
139
140    fn size(&self) -> usize {
141        self.k.as_usize().div_ceil(self.base2k.as_usize())
142    }
143}
144
145impl GLWEInfos for GLWEAutomorphismKeyLayout {
146    fn rank(&self) -> Rank {
147        self.rank
148    }
149}
150
151impl GGLWEInfos for GLWEAutomorphismKeyLayout {
152    fn rank_in(&self) -> Rank {
153        self.rank
154    }
155
156    fn dsize(&self) -> Dsize {
157        self.dsize
158    }
159
160    fn rank_out(&self) -> Rank {
161        self.rank
162    }
163
164    fn dnum(&self) -> Dnum {
165        self.dnum
166    }
167}
168
169impl<D: HostDataRef> fmt::Debug for GLWEAutomorphismKey<D> {
170    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
171        write!(f, "{self}")
172    }
173}
174
175impl<D: HostDataMut> FillUniform for GLWEAutomorphismKey<D> {
176    fn fill_uniform(&mut self, log_bound: usize, source: &mut Source) {
177        self.key.fill_uniform(log_bound, source);
178    }
179}
180
181impl<D: HostDataRef> fmt::Display for GLWEAutomorphismKey<D> {
182    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
183        write!(f, "(AutomorphismKey: p={}) {}", self.p, self.key)
184    }
185}
186
187#[expect(
188    dead_code,
189    reason = "host-owned constructors are kept for serialization and host-only staging"
190)]
191impl GLWEAutomorphismKey<Vec<u8>> {
192    /// Allocates a new [`GLWEAutomorphismKey`] with the given parameters.
193    pub(crate) fn alloc_from_infos<A>(infos: &A) -> Self
194    where
195        A: GGLWEInfos,
196    {
197        Self::alloc(
198            infos.n(),
199            infos.base2k(),
200            infos.max_k(),
201            infos.rank(),
202            infos.dnum(),
203            infos.dsize(),
204        )
205    }
206
207    /// Allocates a new [`GLWEAutomorphismKey`] with the given parameters.
208    pub(crate) fn alloc(n: Degree, base2k: Base2K, k: TorusPrecision, rank: Rank, dnum: Dnum, dsize: Dsize) -> Self {
209        GLWEAutomorphismKey {
210            key: GGLWE::alloc(n, base2k, k, rank, rank, dnum, dsize),
211            p: 0,
212        }
213    }
214
215    /// Returns the byte count required for a [`GLWEAutomorphismKey`] with the given parameters.
216    pub fn bytes_of_from_infos<A>(infos: &A) -> usize
217    where
218        A: GGLWEInfos,
219    {
220        assert_eq!(
221            infos.rank_in(),
222            infos.rank_out(),
223            "rank_in != rank_out is not supported for AutomorphismKey"
224        );
225        Self::bytes_of(
226            infos.n(),
227            infos.base2k(),
228            infos.max_k(),
229            infos.rank(),
230            infos.dnum(),
231            infos.dsize(),
232        )
233    }
234
235    /// Returns the byte count required for a [`GLWEAutomorphismKey`] with the given parameters.
236    pub fn bytes_of(n: Degree, base2k: Base2K, k: TorusPrecision, rank: Rank, dnum: Dnum, dsize: Dsize) -> usize {
237        GGLWE::bytes_of(n, base2k, k, rank, rank, dnum, dsize)
238    }
239}
240
241impl_gglwe_to_backend_for_field!(GLWEAutomorphismKey<D>, key, GGLWE<D>);
242
243impl_gglwe_at_view_for_field!(GLWEAutomorphismKey<BE::OwnedBuf>; key);
244
245impl<D: Data> SetGaloisElement for &mut GLWEAutomorphismKey<D> {
246    fn set_p(&mut self, p: i64) {
247        self.p = p;
248    }
249}
250
251impl_glwe_host_at_for_field!(GLWEAutomorphismKey<D>; key);
252
253impl<D: HostDataMut> ReaderFrom for GLWEAutomorphismKey<D> {
254    /// Deserialises from little-endian binary format.
255    fn read_from<R: std::io::Read>(&mut self, reader: &mut R) -> std::io::Result<()> {
256        self.p = reader.read_u64::<LittleEndian>()? as i64;
257        self.key.read_from(reader)
258    }
259}
260
261impl<D: HostDataRef> WriterTo for GLWEAutomorphismKey<D> {
262    /// Serialises in little-endian binary format.
263    fn write_to<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
264        writer.write_u64::<LittleEndian>(self.p as u64)?;
265        self.key.write_to(writer)
266    }
267}