Skip to main content

crypto_bigint/uint/ref_type/
bits.rs

1use super::UintRef;
2use crate::{Choice, Limb, bitlen, traits::BitOps, word};
3
4impl UintRef {
5    /// Get the precision of this number in bits.
6    #[inline(always)]
7    #[must_use]
8    pub const fn bits_precision(&self) -> u32 {
9        bitlen::from_limbs(self.limbs.len())
10    }
11
12    /// Get the value of the bit at position `index`, as a truthy or falsy [`Choice`].
13    /// Returns the falsy value for indices out of range.
14    #[inline(always)]
15    #[allow(clippy::cast_possible_truncation)]
16    #[must_use]
17    pub const fn bit(&self, index: u32) -> Choice {
18        let limb_num = index >> Limb::LOG2_BITS;
19        let index_in_limb = index & (Limb::BITS - 1);
20        let index_mask = 1 << index_in_limb;
21
22        let mut result = 0;
23        let mut i = 0;
24        while i < self.limbs.len() {
25            let is_right_limb = Choice::from_u32_eq(i as u32, limb_num);
26            result |= word::select(0, self.limbs[i].0, is_right_limb);
27            i += 1;
28        }
29
30        word::choice_from_lsb((result & index_mask) >> index_in_limb)
31    }
32
33    /// Returns `true` if the bit at position `index` is set, `false` for an unset bit
34    /// or for indices out of range.
35    ///
36    /// # Remarks
37    /// This operation is variable time with respect to `index` only.
38    #[inline(always)]
39    #[must_use]
40    #[allow(clippy::integer_division_remainder_used, reason = "vartime")]
41    pub const fn bit_vartime(&self, index: u32) -> bool {
42        let limb_num = (index / Limb::BITS) as usize;
43        let index_in_limb = index % Limb::BITS;
44        if limb_num >= self.limbs.len() {
45            false
46        } else {
47            (self.limbs[limb_num].0 >> index_in_limb) & 1 == 1
48        }
49    }
50
51    /// Deprecated alias for [`Self::bit_width`].
52    #[deprecated(since = "0.7.11", note = "please use `bit_width` instead")]
53    #[inline]
54    #[must_use]
55    pub const fn bits(&self) -> u32 {
56        self.bit_width()
57    }
58
59    /// Returns the minimum number of bits required to represent `self`.
60    ///
61    /// Returns zero if `self` is zero.
62    ///
63    /// Use [`UintRef::bits_precision`] to get the total capacity of this integer.
64    #[inline(always)]
65    #[must_use]
66    pub const fn bit_width(&self) -> u32 {
67        self.bits_precision() - self.leading_zeros()
68    }
69
70    /// Deprecated alias for [`Self::bit_width_vartime`].
71    #[deprecated(since = "0.7.11", note = "please use `bit_width_vartime` instead")]
72    #[inline]
73    #[must_use]
74    pub const fn bits_vartime(&self) -> u32 {
75        self.bit_width_vartime()
76    }
77
78    /// Returns the minimum number of bits required to represent `self`, in variable time
79    /// with respect to `self`.
80    ///
81    /// Returns zero if `self` is zero.
82    #[inline(always)]
83    #[allow(clippy::cast_possible_truncation)]
84    #[must_use]
85    pub const fn bit_width_vartime(&self) -> u32 {
86        let mut i = self.limbs.len() - 1;
87        while i > 0 && self.limbs[i].0 == 0 {
88            i -= 1;
89        }
90
91        let limb = self.limbs[i];
92        Limb::BITS * (i as u32 + 1) - limb.leading_zeros()
93    }
94
95    /// Sets the bit at `index` to 0 or 1 depending on the value of `bit_value`.
96    #[inline(always)]
97    #[allow(clippy::cast_possible_truncation)]
98    pub const fn set_bit(&mut self, index: u32, bit_value: Choice) {
99        let limb_num = index >> Limb::LOG2_BITS;
100        let index_in_limb = index & (Limb::BITS - 1);
101        let index_mask = 1 << index_in_limb;
102
103        let mut i = 0;
104        while i < self.limbs.len() {
105            let is_right_limb = Choice::from_u32_eq(i as u32, limb_num);
106            let old_limb = self.limbs[i].0;
107            let new_limb = word::select(old_limb & !index_mask, old_limb | index_mask, bit_value);
108            self.limbs[i] = Limb(word::select(old_limb, new_limb, is_right_limb));
109            i += 1;
110        }
111    }
112
113    /// Sets the bit at `index` to 0 or 1 depending on the value of `bit_value`, in variable-time
114    /// with respect to `index`.
115    #[inline(always)]
116    #[track_caller]
117    #[allow(clippy::integer_division_remainder_used, reason = "vartime")]
118    pub const fn set_bit_vartime(&mut self, index: u32, bit_value: bool) {
119        let limb_num = (index / Limb::BITS) as usize;
120        let index_in_limb = index % Limb::BITS;
121        if bit_value {
122            self.limbs[limb_num].0 |= 1 << index_in_limb;
123        } else {
124            self.limbs[limb_num].0 &= !(1 << index_in_limb);
125        }
126    }
127
128    /// Calculate the number of leading zeros in the binary representation of this number.
129    #[must_use]
130    pub const fn leading_zeros(&self) -> u32 {
131        let mut count = 0;
132        let mut i = self.limbs.len();
133        let mut nonzero_limb_not_encountered = Choice::TRUE;
134        while i > 0 {
135            i -= 1;
136            let l = self.limbs[i];
137            let z = l.leading_zeros();
138            count += nonzero_limb_not_encountered.select_u32(0, z);
139            nonzero_limb_not_encountered =
140                nonzero_limb_not_encountered.and(word::choice_from_nz(l.0).not());
141        }
142
143        count
144    }
145
146    /// Calculate the number of trailing zeros in the binary representation of this number.
147    #[inline(always)]
148    #[must_use]
149    pub const fn trailing_zeros(&self) -> u32 {
150        let mut count = 0;
151        let mut i = 0;
152        let mut nonzero_limb_not_encountered = Choice::TRUE;
153        while i < self.limbs.len() {
154            let l = self.limbs[i];
155            let z = l.trailing_zeros();
156            count += nonzero_limb_not_encountered.select_u32(0, z);
157            nonzero_limb_not_encountered =
158                nonzero_limb_not_encountered.and(word::choice_from_nz(l.0).not());
159            i += 1;
160        }
161
162        count
163    }
164
165    /// Calculate the number of trailing zeros in the binary representation of this number, in
166    /// variable-time with respect to `self`.
167    #[inline(always)]
168    #[must_use]
169    pub const fn trailing_zeros_vartime(&self) -> u32 {
170        let mut count = 0;
171        let mut i = 0;
172        while i < self.limbs.len() {
173            let l = self.limbs[i];
174            let z = l.trailing_zeros();
175            count += z;
176            if z != Limb::BITS {
177                break;
178            }
179            i += 1;
180        }
181
182        count
183    }
184
185    /// Calculate the number of trailing ones in the binary representation of this number.
186    #[inline(always)]
187    #[must_use]
188    pub const fn trailing_ones(&self) -> u32 {
189        let mut count = 0;
190        let mut i = 0;
191        let mut nonmax_limb_not_encountered = Choice::TRUE;
192        while i < self.limbs.len() {
193            let l = self.limbs[i];
194            let z = l.trailing_ones();
195            count += nonmax_limb_not_encountered.select_u32(0, z);
196            nonmax_limb_not_encountered =
197                nonmax_limb_not_encountered.and(word::choice_from_eq(l.0, Limb::MAX.0));
198            i += 1;
199        }
200
201        count
202    }
203
204    /// Calculate the number of trailing ones in the binary representation of this number, in
205    /// variable-time with respect to `self`.
206    #[inline(always)]
207    #[must_use]
208    pub const fn trailing_ones_vartime(&self) -> u32 {
209        let mut count = 0;
210        let mut i = 0;
211        while i < self.limbs.len() {
212            let l = self.limbs[i];
213            let z = l.trailing_ones();
214            count += z;
215            if z != Limb::BITS {
216                break;
217            }
218            i += 1;
219        }
220
221        count
222    }
223
224    /// Clear all bits at or above a given bit position.
225    #[allow(clippy::cast_possible_truncation)]
226    pub const fn restrict_bits(&mut self, len: u32) {
227        let limb = len >> Limb::LOG2_BITS;
228        let limb_mask = Limb((1 << (len & (Limb::BITS - 1))) - 1);
229        let mut i = 0;
230        let mut clear = Choice::FALSE;
231        while i < self.nlimbs() {
232            let apply = Choice::from_u32_eq(i as u32, limb);
233            self.limbs[i] = self.limbs[i].bitand(Limb::select(
234                Limb(word::choice_to_mask(clear.not())),
235                limb_mask,
236                apply,
237            ));
238            clear = clear.or(apply);
239            i += 1;
240        }
241    }
242}
243
244impl BitOps for UintRef {
245    #[inline(always)]
246    fn bits_precision(&self) -> u32 {
247        self.bits_precision()
248    }
249
250    #[inline(always)]
251    fn bytes_precision(&self) -> usize {
252        self.limbs.len() * Limb::BYTES
253    }
254
255    fn leading_zeros(&self) -> u32 {
256        self.leading_zeros()
257    }
258
259    fn bit(&self, index: u32) -> Choice {
260        self.bit(index)
261    }
262
263    fn set_bit(&mut self, index: u32, bit_value: Choice) {
264        self.set_bit(index, bit_value);
265    }
266
267    fn trailing_zeros(&self) -> u32 {
268        self.trailing_zeros()
269    }
270
271    fn trailing_ones(&self) -> u32 {
272        self.trailing_ones()
273    }
274
275    fn bit_vartime(&self, index: u32) -> bool {
276        self.bit_vartime(index)
277    }
278
279    fn bits_vartime(&self) -> u32 {
280        self.bit_width_vartime()
281    }
282
283    fn set_bit_vartime(&mut self, index: u32, bit_value: bool) {
284        self.set_bit_vartime(index, bit_value);
285    }
286
287    fn trailing_zeros_vartime(&self) -> u32 {
288        self.trailing_zeros_vartime()
289    }
290
291    fn trailing_ones_vartime(&self) -> u32 {
292        self.trailing_ones_vartime()
293    }
294}
295
296#[cfg(test)]
297mod tests {
298    use super::UintRef;
299    use crate::{BitOps, Limb};
300
301    #[test]
302    fn bitops_bytes_precision_counts_bytes_not_limbs() {
303        let limbs = [Limb::ZERO; 2];
304        assert_eq!(UintRef::new(&limbs).bytes_precision(), 2 * Limb::BYTES);
305    }
306}