20281a0d8078a1402cf227afc96ce76c0f9aa243
[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 #ifdef HAVE_SYS_TYPES_H
19 #include <sys/types.h>
20 #endif
21 #include <stdint.h>
22
23 /**
24  * Sets the bit @p bit in bit-vector @p vec. This function returns @c
25  * 1 if bit was set or @c -1 on error (i.e. when the given bit does
26  * not fit in the vector).
27  *
28  * @param vec  The bit-vector to change.
29  * @param size The size of @p vec in bytes.
30  * @param bit  The bit to set in @p vec.
31  *
32  * @return @c -1 if @p bit does not fit into @p vec, @c 1 otherwise.
33  */
34 inline static int bits_setb(uint8_t *vec, size_t size, uint8_t bit)
35 {
36     if (size <= (bit >> 3))
37         return -1;
38
39     *(vec + (bit >> 3)) |= (uint8_t)(1 << (bit & 0x07));
40     return 1;
41 }
42
43 /**
44  * Clears the bit @p bit from bit-vector @p vec. This function returns
45  * @c 1 if bit was cleared or @c -1 on error (i.e. when the given bit
46  * does not fit in the vector).
47  *
48  * @param vec  The bit-vector to change.
49  * @param size The size of @p vec in bytes.
50  * @param bit  The bit to clear from @p vec.
51  *
52  * @return @c -1 if @p bit does not fit into @p vec, @c 1 otherwise.
53  */
54 inline static int bits_clrb(uint8_t *vec, size_t size, uint8_t bit)
55 {
56     if (size <= (bit >> 3))
57         return -1;
58
59     *(vec + (bit >> 3)) &= (uint8_t)(~(1 << (bit & 0x07)));
60     return 1;
61 }
62
63 /**
64  * Gets the status of bit @p bit from bit-vector @p vec. This function returns
65  * @c 1 if the bit is set, @c 0 otherwise (even in case of an error)..
66  *
67  * @param vec  The bit-vector to read from..
68  * @param size The size of @p vec in bytes.
69  * @param bit  The bit to get from @p vec.
70  *
71  * @return @c 1 if the bit is set, @c 0 otherwise.
72  */
73 inline static int bits_getb(const uint8_t *vec, size_t size, uint8_t bit)
74 {
75     if (size <= (bit >> 3))
76         return -1;
77
78     return (*(vec + (bit >> 3)) & (1 << (bit & 0x07))) != 0;
79 }
80
81 #endif /* _BITS_H_ */