1use std::sync::Arc;
4
5use super::{traits::TryConvertFrom, Context, Poly};
6use crate::{proto::rq::Rq, Error};
7use fhe_traits::{DeserializeWithContext, Serialize};
8use prost::Message;
9
10impl Serialize for Poly {
11 fn to_bytes(&self) -> Vec<u8> {
12 Rq::from(self).encode_to_vec()
13 }
14}
15
16impl DeserializeWithContext for Poly {
17 type Error = Error;
18 type Context = Context;
19
20 fn from_bytes(bytes: &[u8], ctx: &Arc<Context>) -> Result<Self, Self::Error> {
21 let rq: Rq = Message::decode(bytes).map_err(|e| Error::Serialization(e.to_string()))?;
22 Poly::try_convert_from(&rq, ctx, false, None)
23 }
24}
25
26#[cfg(test)]
27mod tests {
28 use std::{error::Error, sync::Arc};
29
30 use fhe_traits::{DeserializeWithContext, Serialize};
31 use rand::rng;
32
33 use crate::rq::{Context, Poly, Representation};
34
35 const Q: &[u64; 3] = &[
36 4611686018282684417,
37 4611686018326724609,
38 4611686018309947393,
39 ];
40
41 #[test]
42 fn serialize() -> Result<(), Box<dyn Error>> {
43 let mut rng = rng();
44
45 for qi in Q {
46 let ctx = Arc::new(Context::new(&[*qi], 16)?);
47 let p = Poly::random(&ctx, Representation::PowerBasis, &mut rng);
48 assert_eq!(p, Poly::from_bytes(&p.to_bytes(), &ctx)?);
49 let p = Poly::random(&ctx, Representation::Ntt, &mut rng);
50 assert_eq!(p, Poly::from_bytes(&p.to_bytes(), &ctx)?);
51 let p = Poly::random(&ctx, Representation::NttShoup, &mut rng);
52 assert_eq!(p, Poly::from_bytes(&p.to_bytes(), &ctx)?);
53 }
54
55 let ctx = Arc::new(Context::new(Q, 16)?);
56 let p = Poly::random(&ctx, Representation::PowerBasis, &mut rng);
57 assert_eq!(p, Poly::from_bytes(&p.to_bytes(), &ctx)?);
58 let p = Poly::random(&ctx, Representation::Ntt, &mut rng);
59 assert_eq!(p, Poly::from_bytes(&p.to_bytes(), &ctx)?);
60 let p = Poly::random(&ctx, Representation::NttShoup, &mut rng);
61 assert_eq!(p, Poly::from_bytes(&p.to_bytes(), &ctx)?);
62
63 Ok(())
64 }
65}