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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
use super::*;
use std::fmt;
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct BitSharing8(pub(super) u8);
impl LocalOperation for BitSharing8 {}
impl fmt::Debug for BitSharing8 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_fmt(format_args!("<{:08b}> [{}]", self.0, self.reconstruct().0))
}
}
impl Add for BitSharing8 {
type Output = Self;
#[allow(clippy::suspicious_arithmetic_impl)]
fn add(self, other: Self) -> Self::Output {
Self(self.0 ^ other.0)
}
}
impl Sub for BitSharing8 {
type Output = Self;
#[allow(clippy::suspicious_arithmetic_impl)]
fn sub(self, other: Self) -> Self::Output {
Self(self.0 ^ other.0)
}
}
impl Mul for BitSharing8 {
type Output = Self;
#[allow(clippy::suspicious_arithmetic_impl)]
fn mul(self, other: Self) -> Self::Output {
Self(self.0 & other.0)
}
}
impl RingElement for BitSharing8 {
const ONE: Self = Self(0xff);
const ZERO: Self = Self(0x00);
}
impl RingModule<BitScalar> for BitSharing8 {
const DIMENSION: usize = 8;
#[inline(always)]
fn action(&self, s: BitScalar) -> Self {
debug_assert!(s.0 < 2, "scalar is not bit");
BitSharing8(s.0 * self.0)
}
fn get(&self, i: usize) -> BitScalar {
debug_assert!(i < 8);
let i = 7 - i;
BitScalar((self.0 >> i) & 1)
}
fn set(&mut self, i: usize, s: BitScalar) {
debug_assert!(i < 8);
let i = 7 - i;
self.0 &= !(1 << i);
self.0 |= s.0 << i;
}
}
impl Serializable for BitSharing8 {
fn serialize<W: io::Write>(&self, w: &mut W) -> io::Result<()> {
w.write_all(&self.0.to_le_bytes())
}
}
impl Sharing<BitScalar> for BitSharing8 {
fn reconstruct(&self) -> BitScalar {
BitScalar((self.0.count_ones() & 1) as u8)
}
}
#[cfg(test)]
#[cfg(not(debug_assertions))]
mod benchmark {
use super::*;
use rand::thread_rng;
use rand::Rng;
use test::{black_box, Bencher};
#[bench]
fn bench_gf2p8_reconstruct(b: &mut Bencher) {
let mut rng = thread_rng();
let v: [BitSharing8; 4] = [
BitSharing8(rng.gen()),
BitSharing8(rng.gen()),
BitSharing8(rng.gen()),
BitSharing8(rng.gen()),
];
b.iter(|| {
black_box({
let mut s: BitScalar = BitScalar::ZERO;
for i in 0..1_000_000 {
s = s + v[i % 4].reconstruct();
}
s
})
});
}
#[bench]
fn bench_gf2p8_action(b: &mut Bencher) {
let mut rng = thread_rng();
let v = BitSharing8(rng.gen());
let s = BitScalar(rng.gen::<u8>() & 1);
b.iter(|| {
black_box(for _ in 0..1_000_000 {
black_box(v.action(s));
})
});
}
}