4 /* (c) 2017 Workware Systems Pty Ltd -- All Rights Reserved */
11 * A stringbuf is a resizing, null terminated string buffer.
13 * The buffer is reallocated as necessary.
15 * In general it is *not* OK to call these functions with a NULL pointer
16 * unless stated otherwise.
18 * If USE_UTF8 is defined, supports utf8.
22 * The stringbuf structure should not be accessed directly.
23 * Use the functions below.
26 int remaining; /**< Allocated, but unused space */
27 int last; /**< Index of the null terminator (and thus the length of the string) */
29 int chars; /**< Count of characters */
31 char *data; /**< Allocated memory containing the string or NULL for empty */
35 * Allocates and returns a new stringbuf with no elements.
37 stringbuf *sb_alloc(void);
41 * It is OK to call this with NULL.
43 void sb_free(stringbuf *sb);
46 * Returns an allocated copy of the stringbuf
48 stringbuf *sb_copy(stringbuf *sb);
51 * Returns the length of the buffer.
53 * Returns 0 for both a NULL buffer and an empty buffer.
55 static inline int sb_len(stringbuf *sb) {
60 * Returns the utf8 character length of the buffer.
62 * Returns 0 for both a NULL buffer and an empty buffer.
64 static inline int sb_chars(stringbuf *sb) {
73 * Appends a null terminated string to the stringbuf
75 void sb_append(stringbuf *sb, const char *str);
78 * Like sb_append() except does not require a null terminated string.
79 * The length of 'str' is given as 'len'
81 * Note that in utf8 mode, characters will *not* be counted correctly
82 * if a partial utf8 sequence is added with sb_append_len()
84 void sb_append_len(stringbuf *sb, const char *str, int len);
87 * Returns a pointer to the null terminated string in the buffer.
89 * Note this pointer only remains valid until the next modification to the
92 * The returned pointer can be used to update the buffer in-place
93 * as long as care is taken to not overwrite the end of the buffer.
95 static inline char *sb_str(const stringbuf *sb)
101 * Inserts the given string *before* (zero-based) 'index' in the stringbuf.
102 * If index is past the end of the buffer, the string is appended,
103 * just like sb_append()
105 void sb_insert(stringbuf *sb, int index, const char *str);
108 * Delete 'len' bytes in the string at the given index.
110 * Any bytes past the end of the buffer are ignored.
111 * The buffer remains null terminated.
113 * If len is -1, deletes to the end of the buffer.
115 void sb_delete(stringbuf *sb, int index, int len);
118 * Clear to an empty buffer.
120 void sb_clear(stringbuf *sb);
123 * Return an allocated copy of buffer and frees 'sb'.
125 * If 'sb' is empty, returns an allocated copy of "".
127 char *sb_to_string(stringbuf *sb);