From c9ba7ba19353c9cf55dec668b2b059c267d1b0ea Mon Sep 17 00:00:00 2001 From: Chris Robinson Date: Sat, 8 Jun 2019 23:33:59 -0700 Subject: Add a bitfield class for indexed, auto-sized flags --- common/albyte.h | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) (limited to 'common/albyte.h') diff --git a/common/albyte.h b/common/albyte.h index d1459e96..8257560e 100644 --- a/common/albyte.h +++ b/common/albyte.h @@ -1,6 +1,8 @@ #ifndef AL_BYTE_H #define AL_BYTE_H +#include +#include #include namespace al { @@ -63,6 +65,29 @@ AL_DECL_OP(^) #undef AL_DECL_OP +template +class bitfield { + static constexpr size_t bits_per_byte{std::numeric_limits::digits}; + static constexpr size_t NumElems{(N+bits_per_byte-1) / bits_per_byte}; + + byte vals[NumElems]{}; + +public: + void set(size_t b) noexcept { vals[b/bits_per_byte] |= 1 << (b%bits_per_byte); } + void unset(size_t b) noexcept { vals[b/bits_per_byte] &= ~(1 << (b%bits_per_byte)); } + bool get(size_t b) const noexcept + { return (vals[b/bits_per_byte] & (1 << (b%bits_per_byte))) != byte{}; } + + template 0)> + void set(size_t b, Args ...args) noexcept + { + set(b); + /* Trick for calling set() on each element of the parameter pack. */ + using CharArray = char[sizeof...(Args)]; + (void)(CharArray{ (set(args),'\0')... }); + } +}; + #undef REQUIRES } // namespace al -- cgit v1.2.3