Browse Source

bytestring: Implement bytestring_bytestring()

Add a bytestring_bytestring() function which, in analogy with strstr() and
memmem() finds one bytestring within another.

Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
David Gibson 11 years ago
parent
commit
f1e31c6657
2 changed files with 34 additions and 2 deletions
  1. 19 0
      ccan/bytestring/bytestring.h
  2. 15 2
      ccan/bytestring/test/run.c

+ 19 - 0
ccan/bytestring/bytestring.h

@@ -181,4 +181,23 @@ static inline const char *bytestring_rindex(struct bytestring haystack,
 	return memrchr(haystack.ptr, needle, haystack.len);
 }
 
+/*
+ * bytestring_bytestring - search for a bytestring in another bytestring
+ * @haystack, @needle: bytestrings
+ *
+ * Returns a bytestring corresponding to the first occurrence of
+ * @needle in @haystack, or bytestring_NULL if @needle is not found
+ * within @haystack.
+ */
+static inline struct bytestring bytestring_bytestring(struct bytestring haystack,
+						      struct bytestring needle)
+{
+	const char *p = memmem(haystack.ptr, haystack.len,
+			       needle.ptr, needle.len);
+	if (p)
+		return bytestring(p, needle.len);
+	else
+		return bytestring_NULL;
+}
+
 #endif /* CCAN_BYTESTRING_H_ */

+ 15 - 2
ccan/bytestring/test/run.c

@@ -11,10 +11,10 @@ const char *str2 = TEST_STRING;
 
 int main(void)
 {
-	struct bytestring bs, bs1, bs2, bs3, bs4, bs5;
+	struct bytestring bs, bs1, bs2, bs3, bs4, bs5, bs6;
 
 	/* This is how many tests you plan to run */
-	plan_tests(42);
+	plan_tests(47);
 
 	bs = bytestring(str1, sizeof(str1) - 1);
 	ok1(bs.ptr == str1);
@@ -75,6 +75,19 @@ int main(void)
 	ok1(bytestring_rindex(bs2, 'f') == (bs2.ptr + 6));
 	ok1(bytestring_rindex(bs2, 'q') == NULL);
 
+	bs6 = BYTESTRING("string");
+	ok1(bytestring_eq(bytestring_bytestring(bs1, bs6),
+			  bytestring(bs1.ptr + 5, 6)));
+	bs6 = BYTESTRING("c\0d");
+	ok1(bytestring_eq(bytestring_bytestring(bs2, bs6),
+			  bytestring(bs2.ptr + 2, 3)));
+	bs6 = BYTESTRING("c\0e");
+	ok1(bytestring_bytestring(bs2, bs6).ptr == NULL);
+	ok1(bytestring_eq(bytestring_bytestring(bs1, bytestring_NULL),
+			  bytestring(bs1.ptr, 0)));
+	ok1(bytestring_eq(bytestring_bytestring(bs2, bytestring_NULL),
+			  bytestring(bs2.ptr, 0)));
+
 	/* This exits depending on whether all tests passed */
 	return exit_status();
 }