]> git.ozlabs.org Git - ccan/blob - ccan/bytestring/bytestring.h
bytestring: Add bytestring_byte() function
[ccan] / ccan / bytestring / bytestring.h
1 /* Licensed under LGPLv2+ - see LICENSE file for details */
2 #ifndef CCAN_BYTESTRING_H_
3 #define CCAN_BYTESTRING_H_
4
5 #include <stdlib.h>
6 #include <string.h>
7 #include <stdbool.h>
8 #include <assert.h>
9
10 #include <ccan/array_size/array_size.h>
11
12 struct bytestring {
13         const char *ptr;
14         size_t len;
15 };
16
17 /**
18  * bytestring - construct a new bytestring
19  * @p: pointer to the content of the bytestring
20  * @l: length of the bytestring
21  *
22  * Builds a new bytestring starting at p, of length l.
23  *
24  * Example:
25  *      char x[5] = "abcde";
26  *      struct bytestring bs = bytestring(x, 5);
27  *      assert(bs.len == 5);
28  */
29 static inline struct bytestring bytestring(const char *p, size_t l)
30 {
31         struct bytestring bs = {
32                 .ptr = p,
33                 .len = l,
34         };
35
36         return bs;
37 }
38
39 #define bytestring_NULL         bytestring(NULL, 0)
40
41 /**
42  * BYTESTRING - construct a bytestring from a string literal
43  * @s: string literal
44  *
45  * Builds a new bytestring containing the given literal string, not
46  * including the terminating \0 (but including any internal \0s).
47  *
48  * Example:
49  *      assert(BYTESTRING("abc\0def").len == 7);
50  */
51 #define BYTESTRING(s) (bytestring((s), ARRAY_SIZE(s) - 1))
52
53
54 /**
55  * bytestring_from_string - construct a bytestring from a NUL terminated string
56  * @s: NUL-terminated string pointer
57  *
58  * Builds a new bytestring containing the given NUL-terminated string,
59  * up to, but not including, the terminating \0.
60  *
61  * Example:
62  *      assert(bytestring_from_string("abc\0def").len == 3);
63  */
64 static inline struct bytestring bytestring_from_string(const char *s)
65 {
66         if (!s)
67                 return bytestring_NULL;
68         return bytestring(s, strlen(s));
69 }
70
71 /**
72  * bytestring_eq - test if bytestrings have identical content
73  * @a, @b: bytestrings
74  *
75  * Returns 1 if the given bytestrings have identical length and
76  * content, 0 otherwise.
77  */
78 static inline bool bytestring_eq(struct bytestring a, struct bytestring b)
79 {
80         return (a.len == b.len)
81                 && (memcmp(a.ptr, b.ptr, a.len) == 0);
82 }
83
84 /**
85  * bytestring_byte - get a byte from a bytestring
86  * @s: bytestring
87  * @n: index
88  *
89  * Return the @n-th byte from @s.  Aborts (via assert) if @n is out of
90  * range for the length of @s.
91  */
92 static inline char bytestring_byte(struct bytestring s, size_t n)
93 {
94         assert(n < s.len);
95         return s.ptr[n];
96 }
97
98 #endif /* CCAN_BYTESTRING_H_ */