1 /* Licensed under LGPLv2+ - see LICENSE file for details */
2 #ifndef CCAN_BYTESTRING_H_
3 #define CCAN_BYTESTRING_H_
10 #include <ccan/array_size/array_size.h>
18 * bytestring - construct a new bytestring
19 * @p: pointer to the content of the bytestring
20 * @l: length of the bytestring
22 * Builds a new bytestring starting at p, of length l.
25 * char x[5] = "abcde";
26 * struct bytestring bs = bytestring(x, 5);
27 * assert(bs.len == 5);
29 static inline struct bytestring bytestring(const char *p, size_t l)
31 struct bytestring bs = {
39 #define bytestring_NULL bytestring(NULL, 0)
42 * BYTESTRING - construct a bytestring from a string literal
45 * Builds a new bytestring containing the given literal string, not
46 * including the terminating \0 (but including any internal \0s).
49 * assert(BYTESTRING("abc\0def").len == 7);
51 #define BYTESTRING(s) (bytestring((s), ARRAY_SIZE(s) - 1))
55 * bytestring_from_string - construct a bytestring from a NUL terminated string
56 * @s: NUL-terminated string pointer
58 * Builds a new bytestring containing the given NUL-terminated string,
59 * up to, but not including, the terminating \0.
62 * assert(bytestring_from_string("abc\0def").len == 3);
64 static inline struct bytestring bytestring_from_string(const char *s)
67 return bytestring_NULL;
68 return bytestring(s, strlen(s));
72 * bytestring_eq - test if bytestrings have identical content
75 * Returns 1 if the given bytestrings have identical length and
76 * content, 0 otherwise.
78 static inline bool bytestring_eq(struct bytestring a, struct bytestring b)
80 return (a.len == b.len)
81 && (memcmp(a.ptr, b.ptr, a.len) == 0);
85 * bytestring_byte - get a byte from a bytestring
89 * Return the @n-th byte from @s. Aborts (via assert) if @n is out of
90 * range for the length of @s.
92 static inline char bytestring_byte(struct bytestring s, size_t n)
99 * bytestring_slice - extract a substring from a bytestring
101 * @start, @end: indexes
103 * Return a sub-bytestring of @s, starting at byte index @start, and
104 * running to, but not including byte @end. If @end is before start,
105 * returns a zero-length bytestring. If @start is out of range,
106 * return a zero length bytestring at the end of @s.
108 * Note that this doesn't copy or allocate anything - the returned
109 * bytestring occupies (some of) the same memory as the given
112 static inline struct bytestring bytestring_slice(struct bytestring s,
113 size_t start, size_t end)
122 return bytestring(s.ptr + start, end - start);
125 #endif /* CCAN_BYTESTRING_H_ */