[2bb4a01] | 1 | //
|
---|
| 2 | // Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
|
---|
| 3 | //
|
---|
| 4 | // The contents of this file are covered under the licence agreement in the
|
---|
| 5 | // file "LICENCE" distributed with Cforall.
|
---|
| 6 | //
|
---|
| 7 | // Bitfield.hpp --
|
---|
| 8 | //
|
---|
| 9 | // Author : Aaron B. Moss
|
---|
| 10 | // Created On : Thu May 9 10:00:00 2019
|
---|
| 11 | // Last Modified By : Aaron B. Moss
|
---|
| 12 | // Last Modified On : Thu May 9 10:00:00 2019
|
---|
| 13 | // Update Count : 1
|
---|
| 14 | //
|
---|
| 15 |
|
---|
| 16 | #pragma once
|
---|
| 17 |
|
---|
| 18 | #include <strings.h> // for ffs
|
---|
| 19 |
|
---|
| 20 | /// Make a type a bitfield.
|
---|
[14cebb7a] | 21 | /// Include in type definition to add operators. Used to simulate inheritance because union
|
---|
[2bb4a01] | 22 | /// does not allow it. Requires type to have `unsigned val` field
|
---|
| 23 | /// @param BFType Name of containing type
|
---|
[b96d7c1] | 24 | template<typename T>
|
---|
| 25 | struct bitfield : public T {
|
---|
| 26 | static_assert(sizeof(T) == sizeof(unsigned int), "Type has incorrect size");
|
---|
| 27 | using T::val;
|
---|
| 28 | using val_t = decltype(val);
|
---|
| 29 |
|
---|
| 30 | constexpr bitfield() : T( 0 ) {}
|
---|
| 31 | constexpr bitfield( val_t v ) : T( v ) {}
|
---|
| 32 |
|
---|
| 33 | bool operator[]( val_t i ) const { return val & (1 << i); }
|
---|
| 34 | bool any() const { return val != 0; }
|
---|
| 35 | void reset() { val = 0; }
|
---|
| 36 | int ffs() { return ::ffs( val ) - 1; }
|
---|
| 37 |
|
---|
| 38 | bitfield operator&=( bitfield other ) {
|
---|
| 39 | val &= other.val; return *this;
|
---|
| 40 | }
|
---|
| 41 | bitfield operator&( bitfield other ) const {
|
---|
| 42 | bitfield q = other;
|
---|
| 43 | q &= *this;
|
---|
| 44 | return q;
|
---|
| 45 | }
|
---|
| 46 | bitfield operator|=( bitfield other ) {
|
---|
| 47 | val |= other.val; return *this;
|
---|
| 48 | }
|
---|
| 49 | bitfield operator|( bitfield other ) const {
|
---|
| 50 | bitfield q = other;
|
---|
| 51 | q |= *this;
|
---|
| 52 | return q;
|
---|
| 53 | }
|
---|
| 54 | bitfield operator-=( bitfield other ) {
|
---|
| 55 | val &= ~other.val; return *this;
|
---|
[2bb4a01] | 56 | }
|
---|
[b96d7c1] | 57 | };
|
---|
[2bb4a01] | 58 |
|
---|
[461046f] | 59 | template<typename T>
|
---|
| 60 | inline bool operator== ( const bitfield<T> & a, const bitfield<T> & b ) {
|
---|
| 61 | return a.val == b.val;
|
---|
| 62 | }
|
---|
| 63 |
|
---|
| 64 | template<typename T>
|
---|
| 65 | inline bool operator!= ( const bitfield<T> & a, const bitfield<T> & b ) {
|
---|
| 66 | return !(a == b);
|
---|
| 67 | }
|
---|
[2bb4a01] | 68 |
|
---|
| 69 | // Local Variables: //
|
---|
| 70 | // tab-width: 4 //
|
---|
| 71 | // mode: c++ //
|
---|
| 72 | // compile-command: "make install" //
|
---|
| 73 | // End: //
|
---|