Skip to main content

simple_bfv/
plaintext.rs

1//Code for plaintext
2use simple_ring::Polynomial;
3use crate::BFV;
4
5#[derive(Clone)]
6pub struct BFVPlaintext {
7    pub plain: Polynomial,
8    pub len: usize,
9}
10
11impl BFVPlaintext {
12    pub fn empty(bfv: &BFV) -> Self { //Function that, given the cipher (BFV) creates and empty Plaintext ( Plaintext = [0, 0, 0, 0, ... , 0] )
13        Self { 
14            plain: Polynomial::zeros(bfv.params.n),
15            len: 0, //We define the len of datas to 0, because the plaintext is empty.
16        }
17    }
18
19    pub fn push(mut self, to_push: &str) -> Self { //Method to push datas into a plaintext
20
21        let encoded: Vec<u64> = to_push.as_bytes().iter().map(|&b| b as u64).collect(); //First, we encode the datas into a Vec of u64s
22
23        let remaining = self.plain.coeffs.len() - self.len; //We calculate the remaining coeffs we can write
24
25        let len_to_write = encoded.len().min(remaining); 
26
27        for i in 0..len_to_write { //We write the empty coefficients with pushed ones
28            self.plain.coeffs[self.len + i] = encoded[i];
29        }
30
31        self.len += len_to_write; //We finally update the len of the plaintext
32        self
33    }
34
35    pub fn new(text: &str, bfv: &BFV) -> Self { //Function that creates a plaintext, given a text in ASCII or UTF-8
36        let n = bfv.params.n;
37
38        let mut coeffs: Vec<u64> = vec![0; n]; //We create an empty vector
39
40        let bytes = text.as_bytes(); //We turn the text into bytes.
41
42        let len_to_write = bytes.len().min(n); //We deduce the len to write
43
44        for i in 0..len_to_write { //We write the coeffs
45            coeffs[i] = bytes[i] as u64;
46        }
47
48        Self {
49            plain: Polynomial::new(coeffs), //We finally create the Plaintext
50            len: len_to_write, 
51        }
52    }
53
54    pub fn new_from_coeffs(coeffs: Vec<u64>, bfv: &BFV) -> Self { //Function to create a plaintext, but directly from a Vec of u64s, not from a String
55        Self { plain: Polynomial::new(coeffs), len: bfv.params.n }
56    }
57
58    pub fn decode(&self) -> String { //Method to decode a plaintext
59        let vec = self.plain.coeffs.to_vec();
60        let vec: Vec<u8> = vec.iter().map(|&b| b as u8).collect();
61        str::from_utf8(&vec).unwrap().to_string()
62    }   
63    
64}