4 * resizable string buffer
6 * (c) 2017-2020 Steve Bennett <steveb@workware.net.au>
8 * See utf8.c for licence details.
15 * A stringbuf is a resizing, null terminated string buffer.
17 * The buffer is reallocated as necessary.
19 * In general it is *not* OK to call these functions with a NULL pointer
20 * unless stated otherwise.
22 * If USE_UTF8 is defined, supports utf8.
26 * The stringbuf structure should not be accessed directly.
27 * Use the functions below.
30 int remaining; /**< Allocated, but unused space */
31 int last; /**< Index of the null terminator (and thus the length of the string) */
33 int chars; /**< Count of characters */
35 char *data; /**< Allocated memory containing the string or NULL for empty */
39 * Allocates and returns a new stringbuf with no elements.
41 stringbuf *sb_alloc(void);
45 * It is OK to call this with NULL.
47 void sb_free(stringbuf *sb);
50 * Returns an allocated copy of the stringbuf
52 stringbuf *sb_copy(stringbuf *sb);
55 * Returns the byte length of the buffer.
57 * Returns 0 for both a NULL buffer and an empty buffer.
59 static inline int sb_len(stringbuf *sb) {
64 * Returns the utf8 character length of the buffer.
66 * Returns 0 for both a NULL buffer and an empty buffer.
68 static inline int sb_chars(stringbuf *sb) {
77 * Appends a null terminated string to the stringbuf
79 void sb_append(stringbuf *sb, const char *str);
82 * Like sb_append() except does not require a null terminated string.
83 * The length of 'str' is given as 'len'
85 * Note that in utf8 mode, characters will *not* be counted correctly
86 * if a partial utf8 sequence is added with sb_append_len()
88 void sb_append_len(stringbuf *sb, const char *str, int len);
91 * Returns a pointer to the null terminated string in the buffer.
93 * Note this pointer only remains valid until the next modification to the
96 * The returned pointer can be used to update the buffer in-place
97 * as long as care is taken to not overwrite the end of the buffer.
99 static inline char *sb_str(const stringbuf *sb)
105 * Inserts the given string *before* (zero-based) byte 'index' in the stringbuf.
106 * If index is past the end of the buffer, the string is appended,
107 * just like sb_append()
109 void sb_insert(stringbuf *sb, int index, const char *str);
112 * Delete 'len' bytes in the string at the given index.
114 * Any bytes past the end of the buffer are ignored.
115 * The buffer remains null terminated.
117 * If len is -1, deletes to the end of the buffer.
119 void sb_delete(stringbuf *sb, int index, int len);
122 * Clear to an empty buffer.
124 void sb_clear(stringbuf *sb);
127 * Return an allocated copy of buffer and frees 'sb'.
129 * If 'sb' is empty, returns an allocated copy of "".
131 char *sb_to_string(stringbuf *sb);