Plasma Engine  2.0
Loading...
Searching...
No Matches
BitIterator.h
1#pragma once
2
3#include <Foundation/Math/Math.h>
4
7template <typename T, typename = std::void_t<>>
9template <typename T>
10struct plBitIteratorStorage<T, std::enable_if_t<sizeof(T) <= 4>>
11{
12 using Type = plUInt32;
13};
14template <typename T>
15struct plBitIteratorStorage<T, std::enable_if_t<sizeof(T) >= 5>>
16{
17 using Type = plUInt64;
18};
19
25template <typename DataType, bool ReturnsIndex = true, typename ReturnType = DataType, typename StorageType = typename plBitIteratorStorage<DataType>::Type>
27{
28 using iterator_category = std::forward_iterator_tag;
29 using value_type = DataType;
30 static_assert(sizeof(DataType) <= 8);
31
32 // Invalid iterator (end)
33 PL_ALWAYS_INLINE plBitIterator() = default;
34
35 // Start iterator.
36 PL_ALWAYS_INLINE explicit plBitIterator(DataType data)
37 {
38 m_uiMask = static_cast<StorageType>(data);
39 }
40
41 PL_ALWAYS_INLINE bool IsValid() const
42 {
43 return m_uiMask != 0;
44 }
45
46 PL_ALWAYS_INLINE ReturnType Value() const
47 {
48 if constexpr (ReturnsIndex)
49 {
50 return static_cast<ReturnType>(plMath::FirstBitLow(m_uiMask));
51 }
52 else
53 {
54 return static_cast<ReturnType>(PL_BIT(plMath::FirstBitLow(m_uiMask)));
55 }
56 }
57
58 PL_ALWAYS_INLINE void Next()
59 {
60 // Clear the lowest set bit. Why this works: https://www.geeksforgeeks.org/turn-off-the-rightmost-set-bit/
61 m_uiMask = m_uiMask & (m_uiMask - 1);
62 }
63
64 PL_ALWAYS_INLINE bool operator==(const plBitIterator& other) const
65 {
66 return m_uiMask == other.m_uiMask;
67 }
68
69 PL_ALWAYS_INLINE bool operator!=(const plBitIterator& other) const
70 {
71 return m_uiMask != other.m_uiMask;
72 }
73
74 PL_ALWAYS_INLINE ReturnType operator*() const
75 {
76 return Value();
77 }
78
79 PL_ALWAYS_INLINE void operator++()
80 {
81 Next();
82 }
83
84 StorageType m_uiMask = 0;
85};
PL_ALWAYS_INLINE plUInt32 FirstBitLow(plUInt32 value)
Returns the index of the least significant bit set.
Definition Math_inl.h:70
Definition BitIterator.h:27
Definition BitIterator.h:8