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
use std::marker::PhantomData;
use ::BigInt;
use arithimpl::traits::ConvertFrom;
use serde::ser::Serialize;
use serde::de::Deserialize;
pub mod integral;
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EncodedCiphertext<T> {
#[serde(with = "::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 = packed << component_bitsize;
packed = packed + BigInt::from(*component);
}
packed
}
fn unpack<T>(mut packed_components: BigInt, component_bitsize: usize, component_count: usize) -> Vec<T>
where T: ConvertFrom<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::_from(&raw_component);
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) << 1*component_bitsize)
+ BigInt::from(3) * (BigInt::from(1) << 0*component_bitsize)
);
let unpacked: Vec<u64> = unpack(packed, component_bitsize, 3);
assert_eq!(unpacked, v);
}