Skip to content

Instantly share code, notes, and snippets.

@AntonC9018
Last active July 21, 2023 08:59
Show Gist options
  • Save AntonC9018/b6db331bf3ba0cdf34bf3ef0699aab20 to your computer and use it in GitHub Desktop.
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
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