From f1e31c66572ef5997e08a1ecadf2e45b2fb04532 Mon Sep 17 00:00:00 2001 From: David Gibson Date: Sat, 26 Jul 2014 22:51:22 +1000 Subject: [PATCH] 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 --- ccan/bytestring/bytestring.h | 19 +++++++++++++++++++ ccan/bytestring/test/run.c | 17 +++++++++++++++-- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/ccan/bytestring/bytestring.h b/ccan/bytestring/bytestring.h index 042b1843..62141bea 100644 --- a/ccan/bytestring/bytestring.h +++ b/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_ */ diff --git a/ccan/bytestring/test/run.c b/ccan/bytestring/test/run.c index 50d28853..ef149c56 100644 --- a/ccan/bytestring/test/run.c +++ b/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(); } -- 2.39.2