Skip to content

Commit 62d6447

Browse files
committed
add from_bits_small
1 parent a5ec166 commit 62d6447

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

src/lib.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,39 @@ impl SmolBitSet {
103103
res
104104
}
105105

106+
/// Creates a new [`SmolBitSet`] from the provided array of `bits` without any heap allocation.
107+
///
108+
/// # Panics
109+
///
110+
/// Panics if any bit index in `bits` is larger than or equal to `usize::BITS`.
111+
///
112+
/// # Examples
113+
///
114+
/// ```
115+
/// use smolbitset::SmolBitSet;
116+
///
117+
/// const sbs: SmolBitSet = SmolBitSet::from_bits_small([0, 4, 1, 6]);
118+
/// assert_eq!(sbs, SmolBitSet::from(0b0101_0011u8));
119+
/// ```
120+
#[must_use]
121+
pub const fn from_bits_small<const N: usize>(bits: [usize; N]) -> Self {
122+
let mut res = 0;
123+
let mut i = 0;
124+
125+
while i < N {
126+
let b = bits[i];
127+
assert!(
128+
b < usize::BITS as usize,
129+
"bit index out of range for small bitset"
130+
);
131+
132+
res |= 1 << b;
133+
i += 1;
134+
}
135+
136+
Self::new_small(res)
137+
}
138+
106139
/// Creates a new [`SmolBitSet`] from the provided slice of `bits`.
107140
///
108141
/// # Examples

0 commit comments

Comments
 (0)