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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
use crate::{ParseError, Uint};
use core::{
    ops::{
        BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Index, Not, Shl, ShlAssign,
        Shr, ShrAssign,
    },
    str::FromStr,
};

#[cfg(feature = "alloc")]
#[allow(unused_imports)]
use alloc::{borrow::Cow, vec::Vec};

/// A newtype wrapper around [`Uint`] that restricts operations to those
/// relevant for bit arrays.
#[derive(Clone, Copy, Default, Eq, PartialEq, Hash)]
#[cfg_attr(feature = "alloc", derive(Debug))]
pub struct Bits<const BITS: usize, const LIMBS: usize>(Uint<BITS, LIMBS>);

impl<const BITS: usize, const LIMBS: usize> From<Uint<BITS, LIMBS>> for Bits<BITS, LIMBS> {
    #[inline]
    fn from(value: Uint<BITS, LIMBS>) -> Self {
        Self(value)
    }
}

impl<const BITS: usize, const LIMBS: usize> From<Bits<BITS, LIMBS>> for Uint<BITS, LIMBS> {
    #[inline]
    fn from(value: Bits<BITS, LIMBS>) -> Self {
        value.0
    }
}

impl<const BITS: usize, const LIMBS: usize> FromStr for Bits<BITS, LIMBS> {
    type Err = <Uint<BITS, LIMBS> as FromStr>::Err;

    #[inline]
    fn from_str(src: &str) -> Result<Self, Self::Err> {
        src.parse().map(Self)
    }
}

impl<const BITS: usize, const LIMBS: usize> Bits<BITS, LIMBS> {
    /// The size of this integer type in 64-bit limbs.
    pub const LIMBS: usize = Uint::<BITS, LIMBS>::LIMBS;

    /// The size of this integer type in bits.
    pub const BITS: usize = Uint::<BITS, LIMBS>::BITS;

    /// The size of this integer type in bits.
    pub const BYTES: usize = Uint::<BITS, LIMBS>::BYTES;

    /// The value zero. This is the only value that exists in all [`Uint`]
    /// types.
    pub const ZERO: Self = Self(Uint::<BITS, LIMBS>::ZERO);

    /// Returns the inner [Uint].
    #[must_use]
    #[inline(always)]
    pub const fn into_inner(self) -> Uint<BITS, LIMBS> {
        self.0
    }

    /// Returns a reference to the inner [Uint].
    #[must_use]
    #[inline(always)]
    pub const fn as_uint(&self) -> &Uint<BITS, LIMBS> {
        &self.0
    }

    /// Returns a mutable reference to the inner [Uint].
    #[must_use]
    #[inline(always)]
    pub fn as_uint_mut(&mut self) -> &mut Uint<BITS, LIMBS> {
        &mut self.0
    }
}

macro_rules! forward_attributes {
    ($fnname:ident, $item:item $(,must_use: true)?) => {
        #[doc = concat!("See [`Uint::", stringify!($fnname),"`] for documentation.")]
        #[inline(always)]
        #[must_use]
        $item
    };
    ($fnname:ident, $item:item,must_use: false) => {
        #[doc = concat!("See [`Uint::", stringify!($fnname),"`] for documentation.")]
        #[inline(always)]
        $item
    };
}

// Limitations of declarative macro matching force us to break down on argument
// patterns.
macro_rules! forward {
    ($(fn $fnname:ident(self) -> $res:ty;)*) => {
        $(
            forward_attributes!(
                $fnname,
                pub fn $fnname(self) -> $res {
                    Uint::$fnname(self.0).into()
                }
            );
        )*
    };
    ($(fn $fnname:ident$(<$(const $generic_arg:ident: $generic_ty:ty),+>)?(&self) -> $res:ty;)*) => {
        $(
            forward_attributes!(
                $fnname,
                pub fn $fnname$(<$(const $generic_arg: $generic_ty),+>)?(&self) -> $res {
                    Uint::$fnname(&self.0).into()
                }
            );
        )*
    };
    ($(unsafe fn $fnname:ident(&mut self) -> $res:ty;)*) => {
        $(
            forward_attributes!(
                $fnname,
                pub unsafe fn $fnname(&mut self) -> $res {
                    Uint::$fnname(&mut self.0).into()
                }
            );
        )*
    };
    ($(fn $fnname:ident(self, $arg:ident: $arg_ty:ty) -> Option<Self>;)*) => {
        $(
            forward_attributes!(
                $fnname,
                pub fn $fnname(self, $arg: $arg_ty) -> Option<Self> {
                    Uint::$fnname(self.0, $arg).map(Bits::from)
                }
            );
        )*
    };
    ($(fn $fnname:ident(self, $arg:ident: $arg_ty:ty) -> (Self, bool);)*) => {
        $(
            forward_attributes!(
                $fnname,
                pub fn $fnname(self, $arg: $arg_ty) -> (Self, bool) {
                    let (value, flag) = Uint::$fnname(self.0, $arg);
                    (value.into(), flag)
                }
            );
        )*
    };
    ($(fn $fnname:ident(self, $arg:ident: $arg_ty:ty) -> $res:ty;)*) => {
        $(
            forward_attributes!(
                $fnname,
                pub fn $fnname(self, $arg: $arg_ty) -> $res {
                    Uint::$fnname(self.0, $arg).into()
                }
            );
        )*
    };
    ($(fn $fnname:ident$(<$(const $generic_arg:ident: $generic_ty:ty),+>)?($($arg:ident: $arg_ty:ty),+) -> Option<Self>;)*) => {
        $(
            forward_attributes!(
                $fnname,
                pub fn $fnname$(<$(const $generic_arg: $generic_ty),+>)?($($arg: $arg_ty),+) -> Option<Self> {
                    Uint::$fnname($($arg),+).map(Bits::from)
                }
            );
        )*
    };
    ($(fn $fnname:ident$(<$(const $generic_arg:ident: $generic_ty:ty),+>)?($($arg:ident: $arg_ty:ty),+) -> Result<Self, $err_ty:ty>;)*) => {
        $(
            forward_attributes!(
                $fnname,
                pub fn $fnname$(<$(const $generic_arg: $generic_ty),+>)?($($arg: $arg_ty),+) -> Result<Self, $err_ty> {
                    Uint::$fnname($($arg),+).map(Bits::from)
                },
                must_use: false
            );
        )*
    };
    ($(fn $fnname:ident$(<$(const $generic_arg:ident: $generic_ty:ty),+>)?($($arg:ident: $arg_ty:ty),+) -> $res:ty;)*) => {
        $(
            forward_attributes!(
                $fnname,
                pub fn $fnname$(<$(const $generic_arg: $generic_ty),+>)?($($arg: $arg_ty),+) -> $res {
                    Uint::$fnname($($arg),+).into()
                }
            );
        )*
    };
    ($(const fn $fnname:ident$(<$(const $generic_arg:ident: $generic_ty:ty),+>)?($($arg:ident: $arg_ty:ty),+) -> Self;)*) => {
        $(
            forward_attributes!(
                $fnname,
                pub const fn $fnname$(<$(const $generic_arg: $generic_ty),+>)?($($arg: $arg_ty),+) -> Self {
                    Bits(Uint::$fnname($($arg),+))
                }
            );
        )*
    };
    ($(const fn $fnname:ident$(<$(const $generic_arg:ident: $generic_ty:ty),+>)?(&self) -> $res_ty:ty;)*) => {
        $(
            forward_attributes!(
                $fnname,
                pub const fn $fnname$(<$(const $generic_arg: $generic_ty),+>)?(&self) -> $res_ty {
                    Uint::$fnname(&self.0)
                }
            );
        )*
    };
}

#[allow(clippy::missing_safety_doc, clippy::missing_errors_doc)]
impl<const BITS: usize, const LIMBS: usize> Bits<BITS, LIMBS> {
    forward! {
        fn reverse_bits(self) -> Self;
    }
    #[cfg(feature = "alloc")]
    forward! {
        fn as_le_bytes(&self) -> Cow<'_, [u8]>;
        fn to_be_bytes_vec(&self) -> Vec<u8>;
    }
    forward! {
        fn to_le_bytes<const BYTES: usize>(&self) -> [u8; BYTES];
        fn to_be_bytes<const BYTES: usize>(&self) -> [u8; BYTES];
        fn leading_zeros(&self) -> usize;
        fn leading_ones(&self) -> usize;
        fn trailing_zeros(&self) -> usize;
        fn trailing_ones(&self) -> usize;
    }
    forward! {
        unsafe fn as_limbs_mut(&mut self) -> &mut [u64; LIMBS];
    }
    forward! {
        fn checked_shl(self, rhs: usize) -> Option<Self>;
        fn checked_shr(self, rhs: usize) -> Option<Self>;
    }
    forward! {
        fn overflowing_shl(self, rhs: usize) -> (Self, bool);
        fn overflowing_shr(self, rhs: usize) -> (Self, bool);
    }
    forward! {
        fn wrapping_shl(self, rhs: usize) -> Self;
        fn wrapping_shr(self, rhs: usize) -> Self;
        fn rotate_left(self, rhs: usize) -> Self;
        fn rotate_right(self, rhs: usize) -> Self;
    }
    forward! {
        fn try_from_be_slice(bytes: &[u8]) -> Option<Self>;
        fn try_from_le_slice(bytes: &[u8]) -> Option<Self>;
    }
    forward! {
        fn from_str_radix(src: &str, radix: u64) -> Result<Self, ParseError>;
    }
    forward! {
        fn from_be_bytes<const BYTES: usize>(bytes: [u8; BYTES]) -> Self;
        fn from_le_bytes<const BYTES: usize>(bytes: [u8; BYTES]) -> Self;
    }
    forward! {
        const fn from_limbs(limbs: [u64; LIMBS]) -> Self;
    }
    forward! {
        const fn as_limbs(&self) -> &[u64; LIMBS];
    }
}

impl<const BITS: usize, const LIMBS: usize> Index<usize> for Bits<BITS, LIMBS> {
    type Output = bool;

    #[inline]
    fn index(&self, index: usize) -> &Self::Output {
        if self.0.bit(index) {
            &true
        } else {
            &false
        }
    }
}

impl<const BITS: usize, const LIMBS: usize> Not for Bits<BITS, LIMBS> {
    type Output = Self;

    #[inline]
    fn not(self) -> Self {
        self.0.not().into()
    }
}

impl<const BITS: usize, const LIMBS: usize> Not for &Bits<BITS, LIMBS> {
    type Output = Bits<BITS, LIMBS>;

    #[inline]
    fn not(self) -> Bits<BITS, LIMBS> {
        self.0.not().into()
    }
}

macro_rules! impl_bit_op {
    ($trait:ident, $fn:ident, $trait_assign:ident, $fn_assign:ident) => {
        impl<const BITS: usize, const LIMBS: usize> $trait_assign<Bits<BITS, LIMBS>>
            for Bits<BITS, LIMBS>
        {
            #[inline(always)]
            fn $fn_assign(&mut self, rhs: Bits<BITS, LIMBS>) {
                self.0.$fn_assign(&rhs.0);
            }
        }
        impl<const BITS: usize, const LIMBS: usize> $trait_assign<&Bits<BITS, LIMBS>>
            for Bits<BITS, LIMBS>
        {
            #[inline(always)]
            fn $fn_assign(&mut self, rhs: &Bits<BITS, LIMBS>) {
                self.0.$fn_assign(rhs.0);
            }
        }
        impl<const BITS: usize, const LIMBS: usize> $trait<Bits<BITS, LIMBS>>
            for Bits<BITS, LIMBS>
        {
            type Output = Bits<BITS, LIMBS>;

            #[inline(always)]
            fn $fn(mut self, rhs: Bits<BITS, LIMBS>) -> Self::Output {
                self.0.$fn_assign(rhs.0);
                self
            }
        }
        impl<const BITS: usize, const LIMBS: usize> $trait<&Bits<BITS, LIMBS>>
            for Bits<BITS, LIMBS>
        {
            type Output = Bits<BITS, LIMBS>;

            #[inline(always)]
            fn $fn(mut self, rhs: &Bits<BITS, LIMBS>) -> Self::Output {
                self.0.$fn_assign(rhs.0);
                self
            }
        }
        impl<const BITS: usize, const LIMBS: usize> $trait<Bits<BITS, LIMBS>>
            for &Bits<BITS, LIMBS>
        {
            type Output = Bits<BITS, LIMBS>;

            #[inline(always)]
            fn $fn(self, mut rhs: Bits<BITS, LIMBS>) -> Self::Output {
                rhs.0.$fn_assign(self.0);
                rhs
            }
        }
        impl<const BITS: usize, const LIMBS: usize> $trait<&Bits<BITS, LIMBS>>
            for &Bits<BITS, LIMBS>
        {
            type Output = Bits<BITS, LIMBS>;

            #[inline(always)]
            fn $fn(self, rhs: &Bits<BITS, LIMBS>) -> Self::Output {
                self.0.clone().$fn(rhs.0).into()
            }
        }
    };
}

impl_bit_op!(BitOr, bitor, BitOrAssign, bitor_assign);
impl_bit_op!(BitAnd, bitand, BitAndAssign, bitand_assign);
impl_bit_op!(BitXor, bitxor, BitXorAssign, bitxor_assign);

macro_rules! impl_shift {
    ($trait:ident, $fn:ident, $trait_assign:ident, $fn_assign:ident) => {
        impl<const BITS: usize, const LIMBS: usize> $trait_assign<usize> for Bits<BITS, LIMBS> {
            #[inline(always)]
            fn $fn_assign(&mut self, rhs: usize) {
                self.0.$fn_assign(rhs);
            }
        }

        impl<const BITS: usize, const LIMBS: usize> $trait_assign<&usize> for Bits<BITS, LIMBS> {
            #[inline(always)]
            fn $fn_assign(&mut self, rhs: &usize) {
                self.0.$fn_assign(rhs);
            }
        }

        impl<const BITS: usize, const LIMBS: usize> $trait<usize> for Bits<BITS, LIMBS> {
            type Output = Self;

            #[inline(always)]
            fn $fn(self, rhs: usize) -> Self {
                self.0.$fn(rhs).into()
            }
        }

        impl<const BITS: usize, const LIMBS: usize> $trait<usize> for &Bits<BITS, LIMBS> {
            type Output = Bits<BITS, LIMBS>;

            #[inline(always)]
            fn $fn(self, rhs: usize) -> Self::Output {
                self.0.$fn(rhs).into()
            }
        }

        impl<const BITS: usize, const LIMBS: usize> $trait<&usize> for Bits<BITS, LIMBS> {
            type Output = Self;

            #[inline(always)]
            fn $fn(self, rhs: &usize) -> Self {
                self.0.$fn(rhs).into()
            }
        }

        impl<const BITS: usize, const LIMBS: usize> $trait<&usize> for &Bits<BITS, LIMBS> {
            type Output = Bits<BITS, LIMBS>;

            #[inline(always)]
            fn $fn(self, rhs: &usize) -> Self::Output {
                self.0.$fn(rhs).into()
            }
        }
    };
}

impl_shift!(Shl, shl, ShlAssign, shl_assign);
impl_shift!(Shr, shr, ShrAssign, shr_assign);