COSA
An Object-Oriented Platform for Arduino Programming
BitSet.hh
Go to the documentation of this file.
1 
21 #ifndef COSA_BITSET_HH
22 #define COSA_BITSET_HH
23 
24 #include "Cosa/Types.h"
25 #include "Cosa/IOStream.hh"
26 
32 template<uint16_t N>
33 class BitSet {
34 public:
39  __attribute__((always_inline))
40  {
41  empty();
42  }
43 
47  uint16_t members() const
48  {
49  return (N);
50  }
51 
56  const uint8_t* bits() const
57  {
58  return (m_set);
59  }
60 
64  void empty()
65  __attribute__((always_inline))
66  {
67  memset(m_set, 0, sizeof(m_set));
68  }
69 
73  bool is_empty() const
74  {
75  for (uint16_t i = 0; i < sizeof(m_set); i++)
76  if (m_set[i] != 0) return (false);
77  return (true);
78  }
79 
84  bool operator[](uint16_t ix) const
85  {
86  return ((ix < N) ? ((m_set[ix / CHARBITS] & _BV(ix & MASK)) != 0) : false);
87  }
88 
93  void operator+=(uint16_t ix)
94  {
95  if (ix < N) m_set[ix / CHARBITS] |= _BV(ix & MASK);
96  }
97 
102  void operator-=(uint16_t ix)
103  {
104  if (ix < N) m_set[ix / CHARBITS] &= ~_BV(ix & MASK);
105  }
106 
111  void operator=(BitSet& rhs)
112  {
113  if (UNLIKELY(rhs.members() != N)) return;
114  for (uint16_t i = 0; i < sizeof(m_set); i++)
115  m_set[i] = rhs.m_set[i];
116  }
117 
122  void operator+=(BitSet& rhs)
123  {
124  if (UNLIKELY(rhs.members() != N)) return;
125  for (uint16_t i = 0; i < sizeof(m_set); i++)
126  m_set[i] |= rhs.m_set[i];
127  }
128 
133  void operator-=(BitSet& rhs)
134  {
135  if (UNLIKELY(rhs.members() != N)) return;
136  for (uint16_t i = 0; i < sizeof(m_set); i++)
137  m_set[i] &= ~rhs.m_set[i];
138  }
139 
145  bool operator==(BitSet& rhs)
146  {
147  if (UNLIKELY(rhs.members() != N)) return (false);
148  return (memcmp(m_set, rhs.m_set, sizeof(m_set)) == 0);
149  }
150 
157  friend IOStream& operator<<(IOStream& outs, BitSet& rhs)
158  {
159  for (uint16_t i = 0; i < N; i++)
160  outs << ((rhs.m_set[i / CHARBITS] & _BV(i & MASK)) != 0);
161  return (outs);
162  }
163 
164 private:
166  static const uint8_t MASK = (CHARBITS - 1);
167 
169  static const size_t SET_MAX = (N + (CHARBITS/2)) / CHARBITS;
170 
172  uint8_t m_set[SET_MAX];
173 };
174 #endif
void operator-=(BitSet &rhs)
Definition: BitSet.hh:133
bool is_empty() const
Definition: BitSet.hh:73
void operator+=(uint16_t ix)
Definition: BitSet.hh:93
BitSet()
Definition: BitSet.hh:38
void operator-=(uint16_t ix)
Definition: BitSet.hh:102
const uint8_t * bits() const
Definition: BitSet.hh:56
uint16_t members() const
Definition: BitSet.hh:47
void operator+=(BitSet &rhs)
Definition: BitSet.hh:122
bool operator==(BitSet &rhs)
Definition: BitSet.hh:145
#define CHARBITS
Definition: Types.h:57
bool operator[](uint16_t ix) const
Definition: BitSet.hh:84
Definition: BitSet.hh:33
friend IOStream & operator<<(IOStream &outs, BitSet &rhs)
Definition: BitSet.hh:157
void operator=(BitSet &rhs)
Definition: BitSet.hh:111
#define UNLIKELY(x)
Definition: Types.h:153
void empty()
Definition: BitSet.hh:64