#ifndef CCAN_BYTESTRING_H_
#define CCAN_BYTESTRING_H_
+#include "config.h"
+
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include <ccan/array_size/array_size.h>
+#include <ccan/mem/mem.h>
struct bytestring {
const char *ptr;
suffix.ptr, suffix.len) == 0);
}
+/**
+ * bytestring_index - locate character in bytestring
+ * @haystack: a bytestring
+ * @needle: a character or byte value
+ *
+ * Returns a pointer to the first occurrence of @needle within
+ * @haystack, or NULL if @needle does not appear in @haystack.
+ */
+static inline const char *bytestring_index(struct bytestring haystack,
+ char needle)
+{
+ return memchr(haystack.ptr, needle, haystack.len);
+}
+
+/**
+ * bytestring_rindex - locate character in bytestring
+ * @haystack: a bytestring
+ * @needle: a character or byte value
+ *
+ * Returns a pointer to the last occurrence of @needle within
+ * @haystack, or NULL if @needle does not appear in @haystack.
+ */
+static inline const char *bytestring_rindex(struct bytestring haystack,
+ char needle)
+{
+ return memrchr(haystack.ptr, needle, haystack.len);
+}
+
#endif /* CCAN_BYTESTRING_H_ */
+#include "config.h"
+
#include <ccan/bytestring/bytestring.h>
#include <ccan/tap/tap.h>
struct bytestring bs, bs1, bs2, bs3, bs4, bs5;
/* This is how many tests you plan to run */
- plan_tests(30);
+ plan_tests(42);
bs = bytestring(str1, sizeof(str1) - 1);
ok1(bs.ptr == str1);
ok1(!bytestring_starts(bs2, BYTESTRING("def")));
ok1(!bytestring_ends(bs2, BYTESTRING("abc")));
+ ok1(bytestring_index(bs1, ' ') == (bs1.ptr + 4));
+ ok1(bytestring_index(bs1, 't') == (bs1.ptr + 0));
+ ok1(bytestring_index(bs1, 0) == NULL);
+ ok1(bytestring_index(bs2, 0) == (bs2.ptr + 3));
+ ok1(bytestring_index(bs2, 'f') == (bs2.ptr + 6));
+ ok1(bytestring_index(bs2, 'q') == NULL);
+
+ ok1(bytestring_rindex(bs1, ' ') == (bs1.ptr + 4));
+ ok1(bytestring_rindex(bs1, 't') == (bs1.ptr + 6));
+ ok1(bytestring_rindex(bs1, 0) == NULL);
+ ok1(bytestring_rindex(bs2, 0) == (bs2.ptr + 3));
+ ok1(bytestring_rindex(bs2, 'f') == (bs2.ptr + 6));
+ ok1(bytestring_rindex(bs2, 'q') == NULL);
+
/* This exits depending on whether all tests passed */
return exit_status();
}