1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
use std::convert::TryFrom;
use std::marker::PhantomData;
use curv::arithmetic::traits::*;
use serde::{Deserialize, Serialize};
pub mod integral;
use crate::BigInt;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EncodedCiphertext<T> {
#[serde(with = "crate::serialize::bigint")]
raw: BigInt,
components: usize,
_phantom: PhantomData<T>,
}
fn pack<T>(components: &[T], component_bitsize: usize) -> BigInt
where
BigInt: From<T>,
T: Copy,
{
let mut packed = BigInt::from(components[0]);
for component in &components[1..] {
packed <<= component_bitsize;
packed += BigInt::from(*component);
}
packed
}
fn unpack<T>(
mut packed_components: BigInt,
component_bitsize: usize,
component_count: usize,
) -> Vec<T>
where
for<'a> T: TryFrom<&'a BigInt>,
{
let mask = BigInt::one() << component_bitsize;
let mut components: Vec<T> = vec![];
for _ in 0..component_count {
let raw_component = &packed_components % &mask; let component =
T::try_from(&raw_component).unwrap_or_else(|_| panic!("conversion from bigint failed"));
components.push(component);
packed_components = &packed_components >> component_bitsize;
}
components.reverse();
components
}
#[test]
fn test_pack() {
let v: Vec<u64> = vec![1, 2, 3];
let component_bitsize = 64;
let packed = pack(&*v, component_bitsize);
assert_eq!(
packed,
BigInt::from(1) * (BigInt::from(1) << (2 * component_bitsize))
+ BigInt::from(2) * (BigInt::from(1) << component_bitsize)
+ BigInt::from(3) * (BigInt::from(1))
);
let unpacked: Vec<u64> = unpack(packed, component_bitsize, 3);
assert_eq!(unpacked, v);
}