]> git.ozlabs.org Git - ccan/blob - ccan/bytestring/bytestring.h
endian: add constant versions.
[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
9 #include <ccan/array_size/array_size.h>
10
11 struct bytestring {
12         const char *ptr;
13         size_t len;
14 };
15
16 /**
17  * bytestring - construct a new bytestring
18  * @p: pointer to the content of the bytestring
19  * @l: length of the bytestring
20  *
21  * Builds a new bytestring starting at p, of length l.
22  *
23  * Example:
24  *      char x[5] = "abcde";
25  *      struct bytestring bs = bytestring(x, 5);
26  *      assert(bs.len == 5);
27  */
28 static inline struct bytestring bytestring(const char *p, size_t l)
29 {
30         struct bytestring bs = {
31                 .ptr = p,
32                 .len = l,
33         };
34
35         return bs;
36 }
37
38 #define bytestring_NULL         bytestring(NULL, 0)
39
40 /**
41  * BYTESTRING - construct a bytestring from a string literal
42  * @s: string literal
43  *
44  * Builds a new bytestring containing the given literal string, not
45  * including the terminating \0 (but including any internal \0s).
46  *
47  * Example:
48  *      assert(BYTESTRING("abc\0def").len == 7);
49  */
50 #define BYTESTRING(s) (bytestring((s), ARRAY_SIZE(s) - 1))
51
52
53 /**
54  * bytestring_from_string - construct a bytestring from a NUL terminated string
55  * @s: NUL-terminated string pointer
56  *
57  * Builds a new bytestring containing the given NUL-terminated string,
58  * up to, but not including, the terminating \0.
59  *
60  * Example:
61  *      assert(bytestring_from_string("abc\0def").len == 3);
62  */
63 static inline struct bytestring bytestring_from_string(const char *s)
64 {
65         if (!s)
66                 return bytestring_NULL;
67         return bytestring(s, strlen(s));
68 }
69
70 /**
71  * bytestring_eq - test if bytestrings have identical content
72  * @a, @b: bytestrings
73  *
74  * Returns 1 if the given bytestrings have identical length and
75  * content, 0 otherwise.
76  */
77 static inline bool bytestring_eq(struct bytestring a, struct bytestring b)
78 {
79         return (a.len == b.len)
80                 && (memcmp(a.ptr, b.ptr, a.len) == 0);
81 }
82
83 #endif /* CCAN_BYTESTRING_H_ */