X-Git-Url: https://git.ozlabs.org/?p=ccan;a=blobdiff_plain;f=ccan%2Fbytestring%2Fbytestring.h;fp=ccan%2Fbytestring%2Fbytestring.h;h=abc7dd7bb0424bb684bdd5000006cfce97cc8578;hp=bd525601eb3a71cb40c050838db1f76268b5530b;hb=4008ec0eb0f9a42827db7dd36d6e00d3c50409e7;hpb=c06054cd124670216d147c2e0660aab3c3fa683c diff --git a/ccan/bytestring/bytestring.h b/ccan/bytestring/bytestring.h index bd525601..abc7dd7b 100644 --- a/ccan/bytestring/bytestring.h +++ b/ccan/bytestring/bytestring.h @@ -95,4 +95,31 @@ 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); +} + #endif /* CCAN_BYTESTRING_H_ */