From 2c1c44c4fe7609cdfa3f04c2f156a2da773a5b0a Mon Sep 17 00:00:00 2001 From: Andrew Bettison Date: Tue, 10 Jul 2012 19:36:25 +0930 Subject: [PATCH] Add strbuf_trunc() primitive, fix bug in strbuf_substr() --- strbuf.c | 18 +++++++++++++++++- strbuf.h | 28 ++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/strbuf.c b/strbuf.c index d2d0da1b..b89a75c5 100644 --- a/strbuf.c +++ b/strbuf.c @@ -98,7 +98,7 @@ char *strbuf_substr(const_strbuf sb, int offset) { char *s; if (offset < 0) { - s = sb->end + offset; + s = (sb->current < sb->end ? sb->current : sb->end) + offset; if (s < sb->start) s = sb->start; } else { @@ -108,3 +108,19 @@ char *strbuf_substr(const_strbuf sb, int offset) } return s; } + +strbuf strbuf_trunc(strbuf sb, int offset) +{ + char *s; + if (offset < 0) { + s = (sb->current < sb->end ? sb->current : sb->end) + offset; + if (s < sb->start) + s = sb->start; + } else { + s = sb->start + offset; + if (s > sb->end) + s = sb->end; + } + sb->current = s; + return sb; +} diff --git a/strbuf.h b/strbuf.h index caf0ecb3..c018255c 100644 --- a/strbuf.h +++ b/strbuf.h @@ -311,6 +311,34 @@ __STRBUF_INLINE char *strbuf_str(const_strbuf sb) { char *strbuf_substr(const_strbuf sb, int offset); +/** Truncate the string in the strbuf to a given offset. If the offset is + * negative, then it is taken from the end of the string, ie, the length of the + * string is added to it. If the string is shorter than the given offset, then + * it is unchanged. Otherwise, a terminating nul char is written at the offset + * and the string's length truncated accordingly. Return a pointer to the + * strbuf so that operations can be chained in a single line. + * + * After the operation: + * len = strbuf_len(sb); + * strbuf_trunc(sb, off); + * the following invariants hold: + * where len <= off, sb is unchanged; + * where 0 <= off < len: + * strbuf_count(sb) == off + * strbuf_len(sb) == off + * where -len <= off < 0: + * strbuf_count(sb) == len + off + * strbuf_len(sb) == len + off + * where off < -len: + * strbuf_count(sb) == 0 + * strbuf_len(sb) == 0 + * strbuf_str(sb)[0] == '\0' + * + * @author Andrew Bettison + */ +strbuf strbuf_trunc(strbuf sb, int offset); + + /** Return true if the given strbuf is "empty", ie, not modified since being * initialised to STRUCT_STRBUF_EMPTY or with strbuf_init(sb, NULL, 0); *