rusticl/util: add an Iterator to iterate over set bits in an integer

Signed-off-by: Karol Herbst <git@karolherbst.de>
Reviewed-by: Nora Allen <blackcatgames@protonmail.com>
Part-of: <https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/22893>
This commit is contained in:
Karol Herbst
2023-05-08 23:09:22 +02:00
committed by Marge Bot
parent b5f8ddee58
commit 8dbccadb71

View File

@@ -33,3 +33,27 @@ where
val + (a - tmp)
}
}
pub struct SetBitIndices<T> {
val: T,
}
impl<T> SetBitIndices<T> {
pub fn from_msb(val: T) -> Self {
Self { val: val }
}
}
impl Iterator for SetBitIndices<u32> {
type Item = u32;
fn next(&mut self) -> Option<Self::Item> {
if self.val == 0 {
None
} else {
let pos = u32::BITS - self.val.leading_zeros() - 1;
self.val ^= 1 << pos;
Some(pos)
}
}
}