1 /*
2 * bits.h -- bit vector manipulation
3 *
4 * Copyright (C) 2010-2011 Olaf Bergmann <bergmann@tzi.org>
5 *
6 * This file is part of the CoAP library libcoap. Please see README for terms
7 * of use.
8 */
9
10 /**
11 * @file bits.h
12 * @brief Bit vector manipulation
13 */
14
15 #ifndef _COAP_BITS_H_
16 #define _COAP_BITS_H_
17
18 #include <stdint.h>
19
20 /**
21 * Sets the bit @p bit in bit-vector @p vec. This function returns @c 1 if bit
22 * was set or @c -1 on error (i.e. when the given bit does not fit in the
23 * vector).
24 *
25 * @param vec The bit-vector to change.
26 * @param size The size of @p vec in bytes.
27 * @param bit The bit to set in @p vec.
28 *
29 * @return @c -1 if @p bit does not fit into @p vec, @c 1 otherwise.
30 */
31 inline static int
bits_setb(uint8_t * vec,size_t size,uint8_t bit)32 bits_setb(uint8_t *vec, size_t size, uint8_t bit) {
33 if (size <= (bit >> 3))
34 return -1;
35
36 *(vec + (bit >> 3)) |= (uint8_t)(1 << (bit & 0x07));
37 return 1;
38 }
39
40 /**
41 * Clears the bit @p bit from bit-vector @p vec. This function returns @c 1 if
42 * bit was cleared or @c -1 on error (i.e. when the given bit does not fit in
43 * the vector).
44 *
45 * @param vec The bit-vector to change.
46 * @param size The size of @p vec in bytes.
47 * @param bit The bit to clear from @p vec.
48 *
49 * @return @c -1 if @p bit does not fit into @p vec, @c 1 otherwise.
50 */
51 inline static int
bits_clrb(uint8_t * vec,size_t size,uint8_t bit)52 bits_clrb(uint8_t *vec, size_t size, uint8_t bit) {
53 if (size <= (bit >> 3))
54 return -1;
55
56 *(vec + (bit >> 3)) &= (uint8_t)(~(1 << (bit & 0x07)));
57 return 1;
58 }
59
60 /**
61 * Gets the status of bit @p bit from bit-vector @p vec. This function returns
62 * @c 1 if the bit is set, @c 0 otherwise (even in case of an error).
63 *
64 * @param vec The bit-vector to read from.
65 * @param size The size of @p vec in bytes.
66 * @param bit The bit to get from @p vec.
67 *
68 * @return @c 1 if the bit is set, @c 0 otherwise.
69 */
70 inline static int
bits_getb(const uint8_t * vec,size_t size,uint8_t bit)71 bits_getb(const uint8_t *vec, size_t size, uint8_t bit) {
72 if (size <= (bit >> 3))
73 return -1;
74
75 return (*(vec + (bit >> 3)) & (1 << (bit & 0x07))) != 0;
76 }
77
78 #endif /* _COAP_BITS_H_ */
79