phantom-zone/src/decomposer.rs
src/decomposer.rsRaw
1use itertools::Itertools;
2use num_traits::{AsPrimitive, One, PrimInt, ToPrimitive, WrappingSub, Zero};
3use std::{fmt::Debug, marker::PhantomData, ops::Rem};
4
5use crate::backend::{ArithmeticOps, ModularOpsU64};
6
7fn gadget_vector<T: PrimInt>(logq: usize, logb: usize, d: usize) -> Vec<T> {
8 let d_ideal = (logq as f64 / logb as f64).ceil().to_usize().unwrap();
9 let ignored_limbs = d_ideal - d;
10 (ignored_limbs..ignored_limbs + d)
11 .into_iter()
12 .map(|i| T::one() << (logb * i))
13 .collect_vec()
14}
15
16pub trait Decomposer {
17 type Element;
18 //FIXME(Jay): there's no reason why it returns a vec instead of an iterator
19 fn decompose(&self, v: &Self::Element) -> Vec<Self::Element>;
20 fn d(&self) -> usize;
21}
22
23// TODO(Jay): Shouldn't Decompose also return corresponding gadget vector ?
24pub struct DefaultDecomposer<T> {
25 q: T,
26 logq: usize,
27 logb: usize,
28 d: usize,
29 ignore_bits: usize,
30 ignore_limbs: usize,
31}
32
33pub trait NumInfo {
34 const BITS: u32;
35}
36
37impl NumInfo for u64 {
38 const BITS: u32 = u64::BITS;
39}
40impl NumInfo for u32 {
41 const BITS: u32 = u32::BITS;
42}
43impl NumInfo for u128 {
44 const BITS: u32 = u128::BITS;
45}
46
47impl<T: PrimInt + NumInfo + Debug> DefaultDecomposer<T> {
48 pub fn new(q: T, logb: usize, d: usize) -> DefaultDecomposer<T> {
49 // if q is power of 2, then `BITS - leading_zeros` outputs logq + 1.
50 let logq = if q & (q - T::one()) == T::zero() {
51 (T::BITS - q.leading_zeros() - 1) as usize
52 } else {
53 (T::BITS - q.leading_zeros()) as usize
54 };
55
56 let d_ideal = (logq as f64 / logb as f64).ceil().to_usize().unwrap();
57 let ignore_limbs = (d_ideal - d);
58 let ignore_bits = (d_ideal - d) * logb;
59
60 DefaultDecomposer {
61 q,
62 logq,
63 logb,
64 d,
65 ignore_bits,
66 ignore_limbs,
67 }
68 }
69
70 fn recompose<Op>(&self, limbs: &[T], modq_op: &Op) -> T
71 where
72 Op: ArithmeticOps<Element = T>,
73 {
74 let mut value = T::zero();
75 for i in 0..self.d {
76 value = modq_op.add(
77 &value,
78 &(modq_op.mul(
79 &limbs[i],
80 &(T::one() << (self.logb * (i + self.ignore_limbs))),
81 )),
82 )
83 }
84 value
85 }
86
87 pub(crate) fn gadget_vector(&self) -> Vec<T> {
88 return gadget_vector(self.logq, self.logb, self.d);
89 }
90}
91
92impl<T: PrimInt + WrappingSub + Debug> Decomposer for DefaultDecomposer<T> {
93 type Element = T;
94 fn decompose(&self, value: &T) -> Vec<T> {
95 let mut value = round_value(*value, self.ignore_bits);
96
97 let q = self.q;
98 // if value >= (q >> 1) {
99 // value = value.wrapping_sub(&q);
100 // }
101
102 let logb = self.logb;
103 let b = T::one() << logb; // base
104 let b_by2 = T::one() << (logb - 1);
105 // let neg_b_by2_modq = q - b_by2;
106 let full_mask = (T::one() << logb) - T::one();
107 // let half_mask = b_by2 - T::one();
108 let mut carry = T::zero();
109 let mut out = Vec::<T>::with_capacity(self.d);
110 for i in 0..self.d {
111 let mut limb = ((value >> (logb * i)) & full_mask) + carry;
112 carry = T::zero();
113 if limb >= b_by2 {
114 limb = (q + limb) - b;
115 carry = T::one();
116 }
117
118 // carry = ((q + g - limb) % q) >> logb;
119
120 // carry = limb & b_by2;
121 // limb = (q + limb) - (carry << 1);
122 // if limb > q {
123 // limb = limb - q;
124 // }
125 out.push(limb);
126
127 // carry = carry >> (logb - 1);
128 }
129
130 out[self.d - 1] = out[self.d - 1] + (carry << logb);
131 if out[self.d - 1] > q {
132 out[self.d - 1] = out[self.d - 1] - q;
133 }
134
135 return out;
136 }
137
138 fn d(&self) -> usize {
139 self.d
140 }
141}
142
143fn round_value<T: PrimInt>(value: T, ignore_bits: usize) -> T {
144 if ignore_bits == 0 {
145 return value;
146 }
147
148 let ignored_msb = (value & ((T::one() << ignore_bits) - T::one())) >> (ignore_bits - 1);
149 (value >> ignore_bits) + ignored_msb
150}
151
152#[cfg(test)]
153mod tests {
154 use rand::{thread_rng, Rng};
155
156 use crate::{
157 backend::{ModInit, ModularOpsU64},
158 decomposer::round_value,
159 utils::generate_prime,
160 };
161
162 use super::{Decomposer, DefaultDecomposer};
163
164 #[test]
165 fn decomposition_works() {
166 let logq = 55;
167 let logb = 9;
168 let d = 6;
169
170 let mut rng = thread_rng();
171
172 // q is prime of bits logq and i is true, other q = 1<<logq
173 // FIXME: Test fails when q is prime, albeit the difference is minute
174 for i in [true, false] {
175 let q = if i {
176 generate_prime(logq, 1 << 4, 1u64 << logq).unwrap()
177 } else {
178 1u64 << logq
179 };
180 let decomposer = DefaultDecomposer::new(q, logb, d);
181 let modq_op = ModularOpsU64::new(q);
182 for _ in 0..1000 {
183 let value = rng.gen_range(0..q);
184 let limbs = decomposer.decompose(&value);
185 let value_back = decomposer.recompose(&limbs, &modq_op);
186 let rounded_value =
187 round_value(value, decomposer.ignore_bits) << decomposer.ignore_bits;
188 // dbg!(&limbs, q);
189 assert_eq!(
190 rounded_value, value_back,
191 "Expected {rounded_value} got {value_back} for q={q}"
192 );
193 }
194 }
195 }
196}