]> git.ozlabs.org Git - ccan/commitdiff
bytestring: bytestring_starts() and bytestring_ends() functions
authorDavid Gibson <david@gibson.dropbear.id.au>
Sun, 19 Oct 2014 10:26:29 +0000 (12:26 +0200)
committerDavid Gibson <david@gibson.dropbear.id.au>
Thu, 30 Oct 2014 00:35:14 +0000 (11:35 +1100)
This implements bytestring_starts() and bytestring_ends() which
will test if a given bytestring starts or ends with another given
bytestring.

Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
ccan/bytestring/bytestring.h
ccan/bytestring/test/run.c

index abc7dd7bb0424bb684bdd5000006cfce97cc8578..54e9fa8735122a70f7d7b032b8c776ead3096297 100644 (file)
@@ -122,4 +122,32 @@ static inline struct bytestring bytestring_slice(struct bytestring s,
        return bytestring(s.ptr + start, end - start);
 }
 
+/**
+ * bytestring_starts - 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_starts(struct bytestring s,
+                                    struct bytestring prefix)
+{
+       return (s.len >= prefix.len) && (memcmp(s.ptr,
+                                               prefix.ptr, prefix.len) == 0);
+}
+
+/**
+ * bytestring_ends - 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_ends(struct bytestring s,
+                                  struct bytestring suffix)
+{
+       return (s.len >= suffix.len) && (memcmp(s.ptr + s.len - suffix.len,
+                                               suffix.ptr, suffix.len) == 0);
+}
+
 #endif /* CCAN_BYTESTRING_H_ */
index 97fa8c5cc5d41e7d570cc1ac68c1b30a6057b068..ac6368d87495b67894ce69b869d64b82025b175c 100644 (file)
@@ -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_starts(bs, BYTESTRING("test")));
+       ok1(bytestring_ends(bs, BYTESTRING("string")));
+       ok1(bytestring_starts(bs2, BYTESTRING("abc")));
+       ok1(bytestring_starts(bs2, BYTESTRING("abc\0")));
+       ok1(bytestring_ends(bs2, BYTESTRING("def")));
+       ok1(bytestring_ends(bs2, BYTESTRING("\0def")));
+       ok1(!bytestring_starts(bs2, BYTESTRING("def")));
+       ok1(!bytestring_ends(bs2, BYTESTRING("abc")));
+
        /* This exits depending on whether all tests passed */
        return exit_status();
 }