darkfi_sdk/crypto/constants/
util.rs

1/* This file is part of DarkFi (https://dark.fi)
2 *
3 * Copyright (C) 2020-2025 Dyne.org foundation
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU Affero General Public License as
7 * published by the Free Software Foundation, either version 3 of the
8 * License, or (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU Affero General Public License for more details.
14 *
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17 */
18
19/// Takes in an FnMut closure and returns a constant-length array with elements of
20/// type `Output`.
21pub fn gen_const_array<Output: Copy + Default, const LEN: usize>(
22    closure: impl FnMut(usize) -> Output,
23) -> [Output; LEN] {
24    gen_const_array_with_default(Default::default(), closure)
25}
26
27pub(crate) fn gen_const_array_with_default<Output: Copy, const LEN: usize>(
28    default_value: Output,
29    closure: impl FnMut(usize) -> Output,
30) -> [Output; LEN] {
31    let mut ret: [Output; LEN] = [default_value; LEN];
32    for (bit, val) in ret.iter_mut().zip((0..LEN).map(closure)) {
33        *bit = val;
34    }
35    ret
36}
37
38/// The sequence of bits representing a u64 in little-endian order.
39///
40/// # Panics
41///
42/// Panics if the expected length of the sequence `NUM_BITS` exceeds
43/// 64.
44pub fn i2lebsp<const NUM_BITS: usize>(int: u64) -> [bool; NUM_BITS] {
45    assert!(NUM_BITS <= 64);
46    gen_const_array(|mask: usize| (int & (1 << mask)) != 0)
47}