Haka
bitfield.h
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4 
5 #ifndef HAKA_CONTAINER_BITFIELD_H
6 #define HAKA_CONTAINER_BITFIELD_H
7 
8 #include <haka/compiler.h>
9 #include <haka/types.h>
10 #include <assert.h>
11 
12 
13 /*
14  * Basic bitfield type which store bit by group of 32
15  * inside a 32 bit integer.
16  *
17  * TODO: The dynamic API is not yet written, so you can only use the
18  * BITFIELD_STATIC macro for now.
19  */
20 struct bitfield {
21  size_t size;
22  int32 data[0];
23 };
24 
25 #define BITFIELD_STATIC(size, name) \
26  struct name { \
27  struct bitfield bitfield; \
28  int32 data[(size+31) / 32]; \
29  };
30 
31 #define BITFIELD_STATIC_INIT(n) { { size: n }, {0} }
32 
36 INLINE bool bitfield_get(struct bitfield *bf, int off)
37 {
38  assert(off < bf->size);
39  return (bf->data[off >> 5] & (1L << (off & 0x1f))) != 0;
40 }
41 
45 INLINE void bitfield_set(struct bitfield *bf, int off, bool val)
46 {
47  int32 * const ptr = bf->data + (off >> 5);
48  const int32 mask = off & 0x1f;
49 
50  assert(off < bf->size);
51 
52  *ptr = (*ptr & ~(1L << mask)) | (val << mask);
53 }
54 
55 #endif /* HAKA_CONTAINER_BITFIELD_H */
HAKA_32BIT_TYPE int32
Definition: types.h:24