]> git.ozlabs.org Git - ccan/commitdiff
bytestring: Add bytestring_byte() function
authorDavid Gibson <david@gibson.dropbear.id.au>
Sun, 19 Oct 2014 10:20:14 +0000 (12:20 +0200)
committerDavid Gibson <david@gibson.dropbear.id.au>
Thu, 30 Oct 2014 00:35:14 +0000 (11:35 +1100)
Add a bytestring_byte() function to get a single byte / character
from a bytestring.

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

index 63472fe24d6cdfd6e84802f6103b2658a610b098..bd525601eb3a71cb40c050838db1f76268b5530b 100644 (file)
@@ -5,6 +5,7 @@
 #include <stdlib.h>
 #include <string.h>
 #include <stdbool.h>
 #include <stdlib.h>
 #include <string.h>
 #include <stdbool.h>
+#include <assert.h>
 
 #include <ccan/array_size/array_size.h>
 
 
 #include <ccan/array_size/array_size.h>
 
@@ -80,4 +81,18 @@ static inline bool bytestring_eq(struct bytestring a, struct bytestring b)
                && (memcmp(a.ptr, b.ptr, a.len) == 0);
 }
 
                && (memcmp(a.ptr, b.ptr, a.len) == 0);
 }
 
+/**
+ * bytestring_byte - get a byte from a bytestring
+ * @s: bytestring
+ * @n: index
+ *
+ * Return the @n-th byte from @s.  Aborts (via assert) if @n is out of
+ * range for the length of @s.
+ */
+static inline char bytestring_byte(struct bytestring s, size_t n)
+{
+       assert(n < s.len);
+       return s.ptr[n];
+}
+
 #endif /* CCAN_BYTESTRING_H_ */
 #endif /* CCAN_BYTESTRING_H_ */
index 9423b9a0bd72b094a570f34751de660027fda488..2d86926d06301b2c5ed8dd9d5242cd31aa3bb2b2 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 */
        struct bytestring bs, bs1, bs2, bs3, bs4, bs5;
 
        /* This is how many tests you plan to run */
-       plan_tests(9);
+       plan_tests(16);
 
        bs = bytestring(str1, sizeof(str1) - 1);
        ok1(bs.ptr == str1);
 
        bs = bytestring(str1, sizeof(str1) - 1);
        ok1(bs.ptr == str1);
@@ -35,6 +35,14 @@ int main(void)
        ok1(bs5.ptr == NULL);
        ok1(bytestring_eq(bs5, bytestring_NULL));
 
        ok1(bs5.ptr == NULL);
        ok1(bytestring_eq(bs5, bytestring_NULL));
 
+       ok1(bytestring_byte(bs2, 0) == 'a');
+       ok1(bytestring_byte(bs2, 1) == 'b');
+       ok1(bytestring_byte(bs2, 2) == 'c');
+       ok1(bytestring_byte(bs2, 3) == '\0');
+       ok1(bytestring_byte(bs2, 4) == 'd');
+       ok1(bytestring_byte(bs2, 5) == 'e');
+       ok1(bytestring_byte(bs2, 6) == 'f');
+       
        /* This exits depending on whether all tests passed */
        return exit_status();
 }
        /* This exits depending on whether all tests passed */
        return exit_status();
 }