1 /* A buffer that accumulates a string by piecewise concatenation. 2 Copyright (C) 2021 Free Software Foundation, Inc. 3 4 This file is free software: you can redistribute it and/or modify 5 it under the terms of the GNU Lesser General Public License as 6 published by the Free Software Foundation; either version 3 of the 7 License, or (at your option) any later version. 8 9 This file is distributed in the hope that it will be useful, 10 but WITHOUT ANY WARRANTY; without even the implied warranty of 11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 GNU Lesser General Public License for more details. 13 14 You should have received a copy of the GNU Lesser General Public License 15 along with this program. If not, see <https://www.gnu.org/licenses/>. */ 16 17 /* Written by Bruno Haible <bruno@clisp.org>, 2021. */ 18 19 #ifndef _STRING_BUFFER_H 20 #define _STRING_BUFFER_H 21 22 #include <stdarg.h> 23 #include <stdbool.h> 24 #include <stdlib.h> 25 26 #include "attribute.h" 27 28 /* A string buffer type. */ 29 struct string_buffer 30 { 31 char *data; 32 size_t length; /* used bytes, <= allocated */ 33 size_t allocated; /* allocated bytes */ 34 bool error; /* true if there was an error */ 35 char space[1024]; /* stack allocated space */ 36 }; 37 38 #ifdef __cplusplus 39 extern "C" { 40 #endif 41 42 /* Initializes BUFFER to the empty string. */ 43 extern void sb_init (struct string_buffer *buffer); 44 45 /* Appends the contents of STR to BUFFER. 46 Returns 0, or -1 in case of out-of-memory error. */ 47 extern int sb_append (struct string_buffer *buffer, const char *str); 48 49 /* Appends the result of the printf-compatible FORMATSTRING with the argument 50 list LIST to BUFFER. 51 Returns 0, or -1 in case of error. */ 52 extern int sb_appendvf (struct string_buffer *buffer, 53 const char *formatstring, va_list list) 54 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4) 55 ATTRIBUTE_FORMAT ((__gnu_printf__, 2, 0)) 56 #else 57 ATTRIBUTE_FORMAT ((__printf__, 2, 0)) 58 #endif 59 ; 60 61 /* Appends the result of the printf-compatible FORMATSTRING with the following 62 arguments to BUFFER. 63 Returns 0, or -1 in case of error. */ 64 extern int sb_appendf (struct string_buffer *buffer, 65 const char *formatstring, ...) 66 #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4) 67 ATTRIBUTE_FORMAT ((__gnu_printf__, 2, 3)) 68 #else 69 ATTRIBUTE_FORMAT ((__printf__, 2, 3)) 70 #endif 71 ; 72 73 /* Frees the memory held by BUFFER. */ 74 extern void sb_free (struct string_buffer *buffer); 75 76 /* Returns the contents of BUFFER, and frees all other memory held 77 by BUFFER. Returns NULL upon failure or if there was an error earlier. 78 It is the responsibility of the caller to free() the result. */ 79 extern char * sb_dupfree (struct string_buffer *buffer) 80 _GL_ATTRIBUTE_MALLOC _GL_ATTRIBUTE_DEALLOC_FREE; 81 82 #ifdef __cplusplus 83 } 84 #endif 85 86 #endif /* _STRING_BUFFER_H */