1 /* Copyright 2014, 2015, 2016, 2018 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 #ifdef HAVE_CONFIG_H
17   #include <config.h>
18 #endif
19 #include <stdlib.h>
20 #include <string.h>
21 #include <stdio.h>
22 #include <stdarg.h>
23 
24 #include "text.h"
25 
26 /* Make sure there are LEN free bytes. */
27 static void
text_alloc(TEXT * t,size_t len)28 text_alloc (TEXT *t, size_t len)
29 {
30   if (t->end + len > t->space)
31     {
32       /* FIXME: Double it instead? */
33       t->space = t->end + len;
34       if (t->space < 10)
35         t->space = 10;
36       t->text = realloc (t->text, t->space);
37       if (!t->text)
38         abort ();
39     }
40 }
41 
42 void
text_printf(TEXT * t,char * format,...)43 text_printf (TEXT *t, char *format, ...)
44 {
45   va_list v;
46   char *s;
47 
48   va_start (v, format);
49   vasprintf (&s, format, v);
50   text_append (t, s);
51   free (s);
52   va_end (v);
53 }
54 
55 void
text_append_n(TEXT * t,char * s,size_t len)56 text_append_n (TEXT *t, char *s, size_t len)
57 {
58   text_alloc (t, len + 1);
59   memcpy (t->text + t->end, s, len);
60   t->end += len;
61   t->text[t->end] = '\0';
62 }
63 
64 void
text_append(TEXT * t,char * s)65 text_append (TEXT *t, char *s)
66 {
67   size_t len = strlen (s);
68   text_append_n (t, s, len);
69 }
70 
71 /* Set text to an empty string without clearing any storage */
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 
89 void
text_destroy(TEXT * t)90 text_destroy (TEXT *t)
91 {
92   t->end = t->space = 0;
93   free(t->text); t->text = 0;
94 }
95