1 /* Copyright 2014-2021 Free Software Foundation, Inc.
2 
3    This program is free software: you can redistribute it and/or modify
4    it under the terms of the GNU General Public License as published by
5    the Free Software Foundation, either version 3 of the License, or
6    (at your option) any later version.
7 
8    This program is distributed in the hope that it will be useful,
9    but WITHOUT ANY WARRANTY; without even the implied warranty of
10    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11    GNU General Public License for more details.
12 
13    You should have received a copy of the GNU General Public License
14    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
15 
16 #include <config.h>
17 #include <stdlib.h>
18 #include <string.h>
19 #include <stdio.h>
20 #include <stdarg.h>
21 
22 #include "errors.h"
23 #include "text.h"
24 
25 /* Make sure there are LEN free bytes. */
26 void
text_alloc(TEXT * t,size_t len)27 text_alloc (TEXT *t, size_t len)
28 {
29   if (t->end + len > t->space)
30     {
31       t->space = t->end + len;
32       if (t->space < 10)
33         t->space = 10;
34       /* This makes a huge difference under Valgrind, is not noticable
35          otherwise. */
36       t->space *= 2;
37       t->text = realloc (t->text, t->space);
38       if (!t->text)
39         fatal ("realloc failed");
40     }
41 }
42 
43 void
text_printf(TEXT * t,char * format,...)44 text_printf (TEXT *t, char *format, ...)
45 {
46   va_list v;
47   char *s;
48 
49   va_start (v, format);
50   vasprintf (&s, format, v);
51   text_append (t, s);
52   free (s);
53   va_end (v);
54 }
55 
56 void
text_append_n(TEXT * t,char * s,size_t len)57 text_append_n (TEXT *t, char *s, size_t len)
58 {
59   text_alloc (t, len + 1);
60   memcpy (t->text + t->end, s, len);
61   t->end += len;
62   t->text[t->end] = '\0';
63 }
64 
65 void
text_append(TEXT * t,char * s)66 text_append (TEXT *t, char *s)
67 {
68   size_t len = strlen (s);
69   text_append_n (t, s, len);
70 }
71 
72 void
text_reset(TEXT * t)73 text_reset (TEXT *t)
74 {
75   if (t->end > 0)
76     {
77       t->end = 0;
78       t->text[0] = 0;
79     }
80 }
81 
82 void
text_init(TEXT * t)83 text_init (TEXT *t)
84 {
85   t->end = t->space = 0;
86   t->text = 0;
87 }
88