-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathSerialization.cpp
119 lines (92 loc) · 2.48 KB
/
Serialization.cpp
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
#include "Serialization.h"
void Export(ofstream &out, const ZZ &val) {
uint32_t nBytes = NumBytes(val);
out.write((char *) &nBytes, sizeof(uint32_t));
bool neg = (val < 0);
out.write((char *) &neg, sizeof(bool));
unsigned char data[nBytes];
BytesFromZZ(data, val, nBytes);
out.write((char *) data, nBytes);
}
void Import(ifstream &in, ZZ &val) {
uint32_t nBytes;
in.read((char *) &nBytes, sizeof(uint32_t));
bool neg;
in.read((char *) &neg, sizeof(bool));
unsigned char data[nBytes];
in.read((char *) data, nBytes);
ZZFromBytes(val, data, nBytes);
if (neg) val *= -1;
}
void Export(ofstream &out, const ZZX &poly) {
int32_t degree = deg(poly);
out.write((char *) °ree, sizeof(int32_t));
for (int i = 0; i <= degree; i++) {
Export(out, poly.rep[i]);
}
}
void Import(ifstream &in, ZZX &poly) {
poly = ZZX::zero();
int32_t degree;
in.read((char *) °ree, sizeof(int32_t));
if (degree == -1) {
return;
}
poly.SetMaxLength(degree + 1);
for (int i = 0; i <= degree; i++) {
ZZ coeff;
Import(in, coeff);
SetCoeff(poly, i, coeff);
}
}
void Export(ofstream &out, const DoubleCRT &poly) {
IndexMap<vec_long> map = poly.getMap();
uint32_t size = map.getIndexSet().card();
Export(out, size);
for (long i = map.first(); i <= map.last(); i = map.next(i)) {
Export(out, i);
Export(out, map[i]);
}
}
void Import(ifstream &in, DoubleCRT &poly) {
IndexMap<vec_long> map;
uint32_t size;
Import(in, size);
for (unsigned i = 0; i < size; i++) {
long key;
Import(in, key);
map.insert(key);
Import(in, map[key]);
}
poly.setMap(map);
}
void Export(ofstream &out, const vec_long &vec) {
uint32_t len = vec.length();
Export(out, len);
for (int i = 0; i < vec.length(); i++) {
Export(out, vec[i]);
}
}
void Import(ifstream &in, vec_long &vec) {
uint32_t size;
Import(in, size);
vec.SetLength(size);
for (uint32_t i = 0; i < size; i++) {
Import(in, vec[i]);
}
}
void Export(ofstream &out, const CiphertextPart &part) {
Export(out, part.poly);
}
void Import(ifstream &in, CiphertextPart &part) {
Import(in, part.poly);
}
void Export(ofstream &out, const Ciphertext &ctxt) {
Ciphertext copy = ctxt;
copy.ScaleDown();
Export(out, copy.parts);
}
void Import(ifstream &in, Ciphertext &ctxt) {
ctxt.Clear();
Import(in, ctxt.parts);
}