Import from old repository commit 61ef2b42a9c4ba8e1600f15bb0236765edc2ad45.
[cascardo/ovs.git] / lib / bitmap.h
1 /*
2  * Copyright (c) 2008 Nicira Networks.
3  *
4  * Permission to use, copy, modify, and/or distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16
17 #ifndef BITMAP_H
18 #define BITMAP_H 1
19
20 #include <limits.h>
21 #include <stdlib.h>
22 #include "util.h"
23
24 #define BITMAP_ULONG_BITS (sizeof(unsigned long) * CHAR_BIT)
25
26 static inline unsigned long *
27 bitmap_unit__(const unsigned long *bitmap, size_t offset)
28 {
29     return (unsigned long *) &bitmap[offset / BITMAP_ULONG_BITS];
30 }
31
32 static inline unsigned long
33 bitmap_bit__(size_t offset)
34 {
35     return 1UL << (offset % BITMAP_ULONG_BITS);
36 }
37
38 static inline unsigned long *
39 bitmap_allocate(size_t n_bits)
40 {
41     return xcalloc(1, ROUND_UP(n_bits, BITMAP_ULONG_BITS));
42 }
43
44 static inline void
45 bitmap_free(unsigned long *bitmap)
46 {
47     free(bitmap);
48 }
49
50 static inline bool
51 bitmap_is_set(const unsigned long *bitmap, size_t offset)
52 {
53     return (*bitmap_unit__(bitmap, offset) & bitmap_bit__(offset)) != 0;
54 }
55
56 static inline void
57 bitmap_set1(unsigned long *bitmap, size_t offset)
58 {
59     *bitmap_unit__(bitmap, offset) |= bitmap_bit__(offset);
60 }
61
62 static inline void
63 bitmap_set0(unsigned long *bitmap, size_t offset)
64 {
65     *bitmap_unit__(bitmap, offset) &= ~bitmap_bit__(offset);
66 }
67
68 static inline void
69 bitmap_set(unsigned long *bitmap, size_t offset, bool value)
70 {
71     if (value) {
72         bitmap_set1(bitmap, offset);
73     } else {
74         bitmap_set0(bitmap, offset);
75     }
76 }
77
78 void bitmap_set_multiple(unsigned long *, size_t start, size_t count,
79                          bool value);
80 bool bitmap_equal(const unsigned long *, const unsigned long *, size_t n);
81
82 #endif /* bitmap.h */