21 #ifndef __CPP11OM_BITFIELD_H__
22 #define __CPP11OM_BITFIELD_H__
42 static_assert(Offset + Bits <= (
int)
sizeof(T) * 8,
"Member exceeds bitfield boundaries");
43 static_assert(Bits < (
int)
sizeof(T) * 8,
"Can't fill entire bitfield with one member");
45 static constexpr T Maximum = (T(1) << Bits) - 1;
46 static constexpr T Mask = Maximum << Offset;
47 T maximum()
const {
return Maximum; }
48 T one()
const {
return T(1) << Offset; }
50 operator T()
const {
return (value >> Offset) & Maximum; }
54 value = (value & ~Mask) | (v << Offset);
59 assert(T(*
this) + v <= Maximum);
65 assert(T(*
this) >= v);
91 template <
typename T,
int BaseOffset,
int BitsPerItem,
int NumItems>
class BitFieldArray {
95 static_assert(BaseOffset + BitsPerItem * NumItems <= (
int)
sizeof(T) * 8,
"Array exceeds bitfield boundaries");
96 static_assert(BitsPerItem < (
int)
sizeof(T) * 8,
"Can't fill entire bitfield with one array element");
98 static const T Maximum = (T(1) << BitsPerItem) - 1;
99 T maximum()
const {
return Maximum; }
100 int numItems()
const {
return NumItems; }
111 T mask()
const {
return Maximum << offset; }
113 operator T()
const {
return (value >> offset) & Maximum; }
116 assert(v <= Maximum);
117 value = (value & ~mask()) | (v << offset);
122 assert(T(*
this) + v <= Maximum);
123 value += v << offset;
128 assert(T(*
this) >= v);
129 value -= v << offset;
133 Element& operator++() {
return *
this += 1; }
139 Element& operator--() {
return *
this -= 1; }
148 assert(i >= 0 && i < NumItems);
149 return Element(value, BaseOffset + BitsPerItem * i);
152 const Element operator[](
int i)
const {
153 assert(i >= 0 && i < NumItems);
154 return Element(value, BaseOffset + BitsPerItem * i);
164 #define BEGIN_BF_DECL(typeName, T) \
169 typeName(T v = 0) { backing.val = v; } \
170 typeName& operator=(T v) { \
174 operator T&() { return backing.val; } \
175 operator T() const { return backing.val; } \
176 using StorageType = T;
178 #define BF_FIELD(memberName, offset, bits) util::BitFieldMember<StorageType, offset, bits> memberName;
180 #define BF_ARRAY(memberName, offset, bits, numItems) util::BitFieldArray<StorageType, offset, bits, numItems> memberName;
182 #define END_BF_DECL() }
array of bit field elements