[ccan] [PATCH 3/9] bytestring: bytestring_startswith() and bytestring_endswith() functions

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


This implements bytestring_startswith() and bytestring_endswith() which
will test if a given bytestring starts or ends with another given
bytestring.

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

diff --git a/ccan/bytestring/bytestring.h b/ccan/bytestring/bytestring.h
index aa7283d..8882b42 100644
--- a/ccan/bytestring/bytestring.h
+++ b/ccan/bytestring/bytestring.h
@@ -118,4 +118,31 @@ static inline struct bytestring bytestring_slice(struct bytestring s,
 	return bytestring(s.ptr + start, end - start);
 }
 
+/**
+ * bytestring_startswith - test if the start of one bytestring matches another
+ * @s, @prefix: bytestrings
+ *
+ * Returns true if @prefix appears as a substring at the beginning of
+ * @s, false otherwise.
+ */
+static inline bool bytestring_startswith(struct bytestring s,
+					 struct bytestring prefix)
+{
+	return bytestring_eq(prefix, bytestring_slice(s, 0, prefix.len));
+}
+
+/**
+ * bytestring_endswith - test if the end of one bytestring matches another
+ * @s, @suffix: bytestrings
+ *
+ * Returns true if @suffix appears as a substring at the end of @s,
+ * false otherwise.
+ */
+static inline bool bytestring_endswith(struct bytestring s,
+				       struct bytestring suffix)
+{
+	return bytestring_eq(suffix,
+			     bytestring_slice(s, s.len - suffix.len, s.len));
+}
+
 #endif /* CCAN_BYTESTRING_H_ */
diff --git a/ccan/bytestring/test/run.c b/ccan/bytestring/test/run.c
index 97fa8c5..d978bbd 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(22);
+	plan_tests(30);
 
 	bs = bytestring(str1, sizeof(str1) - 1);
 	ok1(bs.ptr == str1);
@@ -50,6 +50,15 @@ int main(void)
 	ok1(bytestring_eq(bytestring_slice(bs2, 10, 20), bytestring_NULL));
 	ok1(bytestring_eq(bytestring_slice(bs2, 2, 1), bytestring_NULL));
 
+	ok1(bytestring_startswith(bs, BYTESTRING("test")));
+	ok1(bytestring_endswith(bs, BYTESTRING("string")));
+	ok1(bytestring_startswith(bs2, BYTESTRING("abc")));
+	ok1(bytestring_startswith(bs2, BYTESTRING("abc\0")));
+	ok1(bytestring_endswith(bs2, BYTESTRING("def")));
+	ok1(bytestring_endswith(bs2, BYTESTRING("\0def")));
+	ok1(!bytestring_startswith(bs2, BYTESTRING("def")));
+	ok1(!bytestring_endswith(bs2, BYTESTRING("abc")));
+
 	/* This exits depending on whether all tests passed */
 	return exit_status();
 }
-- 
1.9.3



More information about the ccan mailing list