Line data Source code
1 : /***************************************************************************//**
2 :
3 : @file bitfield.c
4 :
5 : @author Stephen Brennan
6 :
7 : @date Created Wednesday, 29 January 2014
8 :
9 : @brief Implementation of "libstephen/bf.h".
10 :
11 : @copyright Copyright (c) 2013-2016, Stephen Brennan. Released under the
12 : Revised BSD License. See the LICENSE.txt file for details.
13 :
14 : *******************************************************************************/
15 :
16 : #include <string.h>
17 : #include <assert.h>
18 :
19 : #include "libstephen/base.h"
20 : #include "libstephen/bf.h"
21 :
22 5 : void bf_init(unsigned char *data, int num_bools) {
23 5 : int size = SMB_BITFIELD_SIZE(num_bools);
24 5 : memset(data, 0, size);
25 5 : }
26 :
27 1 : unsigned char *bf_create(int num_bools) {
28 : unsigned char *data;
29 1 : int size = SMB_BITFIELD_SIZE(num_bools);
30 :
31 1 : data = smb_new(unsigned char, size);
32 :
33 1 : bf_init(data, num_bools);
34 1 : return data;
35 : }
36 :
37 1 : void bf_delete(unsigned char *data, int num_bools) {
38 : (void) num_bools; // unused
39 1 : smb_free(data);
40 1 : }
41 :
42 416 : int bf_check(unsigned char *data, int index) {
43 416 : int byte_index = (int)(index / BIT_PER_CHAR);
44 416 : unsigned char bit_mask = 0x01 << (index % BIT_PER_CHAR);
45 :
46 416 : return data[byte_index] & bit_mask;
47 : }
48 :
49 160 : void bf_set(unsigned char *data, int index) {
50 160 : int byte_index = (int)(index / BIT_PER_CHAR);
51 160 : unsigned char bit_mask = 0x01 << (index % BIT_PER_CHAR);
52 :
53 160 : data[byte_index] |= bit_mask;
54 160 : }
55 :
56 40 : void bf_clear(unsigned char *data, int index) {
57 40 : int byte_index = (int)(index / BIT_PER_CHAR);
58 40 : unsigned char bit_mask = ~(0x01 << (index % BIT_PER_CHAR));
59 :
60 40 : data[byte_index] &= bit_mask;
61 40 : }
62 :
63 80 : void bf_flip(unsigned char *data, int index) {
64 80 : int byte_index = (int)(index / BIT_PER_CHAR);
65 80 : unsigned char bit_mask = 0x01 << (index % BIT_PER_CHAR);
66 :
67 80 : unsigned char value = ~(data[byte_index] & bit_mask) & bit_mask;
68 80 : data[byte_index] = (data[byte_index] & ~bit_mask) | value;
69 80 : }
|