Last active
July 21, 2023 08:59
-
-
Save AntonC9018/b6db331bf3ba0cdf34bf3ef0699aab20 to your computer and use it in GitHub Desktop.
Iterator of set bit indices that reinterprets the indices as the specified enum
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections; | |
using System.Diagnostics; | |
using System.Numerics; | |
using System.Runtime.CompilerServices; | |
// Enumerates the bits from highest to lowest | |
public struct SetBitIndicesIterator<T> : IEnumerator<T> | |
where T : struct, Enum | |
{ | |
static SetBitIndicesIterator() => | |
Debug.Assert(Enum.GetUnderlyingType(typeof(T)) == typeof(int)); | |
private uint _bits; | |
private int _current; | |
public SetBitIndicesIterator(uint bits) | |
{ | |
_bits = bits; | |
_current = default; | |
} | |
public bool MoveNext() | |
{ | |
if (_bits == 0) | |
return false; | |
_current = (sizeof(uint) * 8) - BitOperations.LeadingZeroCount(_bits) - 1; | |
_bits &= ~(1u << _current); | |
return true; | |
} | |
public readonly T Current | |
{ | |
get | |
{ | |
var c = _current; | |
return Unsafe.As<int, T>(ref c); | |
} | |
} | |
object IEnumerator.Current => Current; | |
public void Reset() | |
{ | |
throw new NotImplementedException(); | |
} | |
public void Dispose() | |
{ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment