From 8dbccadb71edcd1569468fc18c6b7fac056f8a4d Mon Sep 17 00:00:00 2001 From: Karol Herbst Date: Mon, 8 May 2023 23:09:22 +0200 Subject: [PATCH] rusticl/util: add an Iterator to iterate over set bits in an integer Signed-off-by: Karol Herbst Reviewed-by: Nora Allen Part-of: --- src/gallium/frontends/rusticl/util/math.rs | 24 ++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/gallium/frontends/rusticl/util/math.rs b/src/gallium/frontends/rusticl/util/math.rs index f6e8d96e9ae..267c288c52c 100644 --- a/src/gallium/frontends/rusticl/util/math.rs +++ b/src/gallium/frontends/rusticl/util/math.rs @@ -33,3 +33,27 @@ where val + (a - tmp) } } + +pub struct SetBitIndices { + val: T, +} + +impl SetBitIndices { + pub fn from_msb(val: T) -> Self { + Self { val: val } + } +} + +impl Iterator for SetBitIndices { + type Item = u32; + + fn next(&mut self) -> Option { + if self.val == 0 { + None + } else { + let pos = u32::BITS - self.val.leading_zeros() - 1; + self.val ^= 1 << pos; + Some(pos) + } + } +}