source: src/AST/Bitfield.hpp@ 336d0b3

ADT arm-eh ast-experimental cleanup-dtors enum forall-pointer-decay jacob/cs343-translation jenkins-sandbox new-ast new-ast-unique-expr pthread-emulation qualifiedEnum
Last change on this file since 336d0b3 was b96d7c1, checked in by Thierry Delisle <tdelisle@…>, 6 years ago

Made bitfield a template rather than an macro

  • Property mode set to 100644
File size: 2.0 KB
Line 
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.
21/// Include in type definition to add operators. Used to simulate inheritance because union
22/// does not allow it. Requires type to have `unsigned val` field
23/// @param BFType Name of containing type
24template<typename T>
25struct 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;
56 }
57};
58
59/// Adds default printing operator to a bitfield type.
60/// Include in definition to add print function, requires other bitfield operators.
61/// @param N Number of bits in bitfield
62#define MakeBitfieldPrint( N ) \
63 static const char* Names[]; \
64 \
65 void print( std::ostream & os ) const { \
66 if ( (*this).any() ) { \
67 for ( unsigned int i = 0; i < N; i += 1 ) { \
68 if ( (*this)[i] ) { \
69 os << Names[i] << ' '; \
70 } \
71 } \
72 } \
73 }
74
75// Local Variables: //
76// tab-width: 4 //
77// mode: c++ //
78// compile-command: "make install" //
79// End: //
Note: See TracBrowser for help on using the repository browser.