]> git.ozlabs.org Git - ccan/blobdiff - ccan/bytestring/bytestring.h
bytestring: bytestring_starts() and bytestring_ends() functions
[ccan] / ccan / bytestring / bytestring.h
index bd525601eb3a71cb40c050838db1f76268b5530b..54e9fa8735122a70f7d7b032b8c776ead3096297 100644 (file)
@@ -95,4 +95,59 @@ static inline char bytestring_byte(struct bytestring s, size_t n)
        return s.ptr[n];
 }
 
+/**
+ * bytestring_slice - extract a substring from a bytestring
+ * @s: bytestring
+ * @start, @end: indexes
+ *
+ * Return a sub-bytestring of @s, starting at byte index @start, and
+ * running to, but not including byte @end.  If @end is before start,
+ * returns a zero-length bytestring.  If @start is out of range,
+ * return a zero length bytestring at the end of @s.
+ *
+ * Note that this doesn't copy or allocate anything - the returned
+ * bytestring occupies (some of) the same memory as the given
+ * bytestring.
+ */
+static inline struct bytestring bytestring_slice(struct bytestring s,
+                                                size_t start, size_t end)
+{
+       if (start > s.len)
+               start = s.len;
+       if (end > s.len)
+               end = s.len;
+       if (end < start)
+               end = start;
+
+       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_ */