txtbuf.h (2078B)
1 #ifndef _TXTBUF_H_ 2 #define _TXTBUF_H_ 3 4 #include <stddef.h> 5 6 /* 7 * txtbuf is really just a string data type that is badly named. 8 * The stored text is always nul-terminated. 9 */ 10 11 typedef struct { 12 size_t len, cap; 13 char *text; 14 } txtbuf; 15 16 /* 17 * Create an empty txtbuf. 18 */ 19 txtbuf *txtbuf_new(void); 20 21 /* 22 * Create a new txtbuf, initializing it with the nul-terminated 23 * string 'str'. The input string is copied. 24 */ 25 txtbuf *txtbuf_new_from_char(char *str); 26 27 /* 28 * Create a new txtbuf, initializing it with the string 'str' 29 * of length 'len'. The input string is copied. 30 */ 31 txtbuf *txtbuf_new_from_char_len(char *str, size_t len); 32 33 /* 34 * Replace the stored text in 'buf' with the text generated by 35 * 'snprintf' when called with the given format string and args. 36 */ 37 void txtbuf_fmt(txtbuf *buf, char *fmt, ...); 38 39 /* 40 * Replace the stored text in 'buf' with 'text'. 41 */ 42 void txtbuf_set_text(txtbuf *buf, char *text); 43 44 /* 45 * Same as txtbuf_set_text, but with explicit length for 'text'. 46 */ 47 void txtbuf_set_textn(txtbuf *buf, char *text, size_t len); 48 49 /* 50 * Append 'text' to the text stored in 'buf'. 51 */ 52 void txtbuf_append(txtbuf *buf, char *text); 53 54 /* 55 * Same as txtbuf_append, but with explicit length for 'text'. 56 */ 57 void txtbuf_appendn(txtbuf *buf, char *text, size_t len); 58 59 /* 60 * Compare the text of two txtbuf's like 'strcmp'. 61 */ 62 int txtbuf_cmp(txtbuf *buf1, txtbuf *buf2); 63 64 /* 65 * Convenience function for calling 'txtbuf_cmp' and checking if the 66 * return value is 0, i.e. the strings are equal. 67 */ 68 int txtbuf_eql(txtbuf *buf1, txtbuf *buf2); 69 70 /* 71 * Make sure the txtbuf has space for at least the given size, 72 * plus '\0' at the end. 73 */ 74 void txtbuf_resize(txtbuf *buf, size_t sz); 75 76 /* 77 * Destroy a txtbuf. 78 */ 79 void txtbuf_destroy(txtbuf *buf); 80 81 /* 82 * Copy txtbuf 'src' to txtbuf 'dst'. 83 */ 84 void txtbuf_copy(txtbuf *dst, txtbuf *src); 85 86 /* 87 * Duplicate txtbuf 'src'. 88 */ 89 txtbuf *txtbuf_dup(txtbuf *src); 90 91 /* 92 * Clear the text, but do not reduce the internal capacity 93 * (for efficiency if it will be filled up again anyways). 94 */ 95 void txtbuf_clear(txtbuf *buf); 96 97 #endif