From: Baptiste Daroussin Date: Fri, 10 Feb 2023 12:54:40 +0000 (+0100) Subject: xstring: add a wrapper around open_memstream X-Git-Tag: RELEASE_1_4_0b1~181 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=baa8b70817ab43ac07462db11fe14a29bcab7124;p=thirdparty%2Fmlmmj.git xstring: add a wrapper around open_memstream --- diff --git a/include/xstring.h b/include/xstring.h new file mode 100644 index 00000000..24738a66 --- /dev/null +++ b/include/xstring.h @@ -0,0 +1,68 @@ +#ifndef __XSTRING_H_ +#define __XSTRING_H_ + +#include +#include +#include + +struct xstring { + char* buf; + size_t size; + FILE* fp; +}; + +typedef struct xstring xstring; + +static inline xstring * +xstring_new(void) +{ + xstring *str; + + str = calloc(1, sizeof(*str)); + if (str == NULL) + abort(); + str->fp = open_memstream(&str->buf, &str->size); + if (str->fp == NULL) + abort(); + + return (str); +} + +static inline void +xstring_reset(xstring *str) +{ + if (str->buf) + memset(str->buf, 0, str->size); + rewind(str->fp); + +} + +static inline void +xstring_free(xstring *str) +{ + if (str == NULL) + return; + fclose(str->fp); + free(str->buf); + free(str); +} + +#define xstring_renew(s) \ +do { \ + if (s) { \ + xstring_reset(s); \ + } else { \ + s = xstring_new(); \ + } \ +} while(0) + +static inline char * +xstring_get(xstring *str) +{ + fclose(str->fp); + char *ret = str->buf; + free(str); + return (ret); +} + +#endif