[ccan] [PATCH 4/9] bytestring: Add bytestring_chr() function

David Gibson david at gibson.dropbear.id.au
Mon Jul 28 19:59:52 EST 2014


Add bytestring_chr() which, in analogy to strchr() and memchr() searches
for a specific byte value within a bytestring.

Signed-off-by: David Gibson <david at gibson.dropbear.id.au>
---
 ccan/bytestring/bytestring.h | 14 ++++++++++++++
 ccan/bytestring/test/run.c   |  8 +++++++-
 2 files changed, 21 insertions(+), 1 deletion(-)

diff --git a/ccan/bytestring/bytestring.h b/ccan/bytestring/bytestring.h
index 8882b42..ca5afd9 100644
--- a/ccan/bytestring/bytestring.h
+++ b/ccan/bytestring/bytestring.h
@@ -145,4 +145,18 @@ static inline bool bytestring_endswith(struct bytestring s,
 			     bytestring_slice(s, s.len - suffix.len, s.len));
 }
 
+/**
+ * bytestring_chr - search for a specific byte or character in a 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_chr(struct bytestring haystack,
+					 char needle)
+{
+	return memchr(haystack.ptr, needle, haystack.len);
+}
+
 #endif /* CCAN_BYTESTRING_H_ */
diff --git a/ccan/bytestring/test/run.c b/ccan/bytestring/test/run.c
index d978bbd..b0d2ce6 100644
--- a/ccan/bytestring/test/run.c
+++ b/ccan/bytestring/test/run.c
@@ -12,7 +12,7 @@ int main(void)
 	struct bytestring bs, bs1, bs2, bs3, bs4, bs5;
 
 	/* This is how many tests you plan to run */
-	plan_tests(30);
+	plan_tests(35);
 
 	bs = bytestring(str1, sizeof(str1) - 1);
 	ok1(bs.ptr == str1);
@@ -59,6 +59,12 @@ int main(void)
 	ok1(!bytestring_startswith(bs2, BYTESTRING("def")));
 	ok1(!bytestring_endswith(bs2, BYTESTRING("abc")));
 
+	ok1(bytestring_chr(bs1, ' ') == (bs1.ptr + 4));
+	ok1(bytestring_chr(bs1, 0) == NULL);
+	ok1(bytestring_chr(bs2, 0) == (bs2.ptr + 3));
+	ok1(bytestring_chr(bs2, 'f') == (bs2.ptr + 6));
+	ok1(bytestring_chr(bs2, 'q') == NULL);
+
 	/* This exits depending on whether all tests passed */
 	return exit_status();
 }
-- 
1.9.3



More information about the ccan mailing list