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