]> git.ozlabs.org Git - ccan/commitdiff
bytestring: Implement bytestring_bytestring()
authorDavid Gibson <david@gibson.dropbear.id.au>
Sat, 26 Jul 2014 12:51:22 +0000 (22:51 +1000)
committerDavid Gibson <david@gibson.dropbear.id.au>
Thu, 30 Oct 2014 00:35:15 +0000 (11:35 +1100)
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>
ccan/bytestring/bytestring.h
ccan/bytestring/test/run.c

index 042b1843220192bd1c4d2614cdd75df303812bc0..62141bea41149a30bd61214e8804d50c23e4c971 100644 (file)
@@ -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_ */
index 50d288537fc77533fd103de71c1d6c876fd172d8..ef149c56ba7c27a1a370ddc101e0833cd102e52b 100644 (file)
@@ -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();
 }