b648eef6549a28ab9c3c1b77e0f1beb1074ddcc3
[sliver-openvswitch.git] / lib / dynamic-string.c
1 /*
2  * Copyright (c) 2008, 2009, 2010, 2011, 2012 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18 #include "dynamic-string.h"
19 #include <assert.h>
20 #include <stdlib.h>
21 #include <string.h>
22 #include <time.h>
23 #include "timeval.h"
24 #include "util.h"
25
26 /* Initializes 'ds' as an empty string buffer. */
27 void
28 ds_init(struct ds *ds)
29 {
30     ds->string = NULL;
31     ds->length = 0;
32     ds->allocated = 0;
33 }
34
35 /* Sets 'ds''s length to 0, effectively clearing any existing content.  Does
36  * not free any memory. */
37 void
38 ds_clear(struct ds *ds)
39 {
40     ds->length = 0;
41 }
42
43 /* Reduces 'ds''s length to no more than 'new_length'.  (If its length is
44  * already 'new_length' or less, does nothing.)  */
45 void
46 ds_truncate(struct ds *ds, size_t new_length)
47 {
48     if (ds->length > new_length) {
49         ds->length = new_length;
50         ds->string[new_length] = '\0';
51     }
52 }
53
54 /* Ensures that at least 'min_length + 1' bytes (including space for a null
55  * terminator) are allocated for ds->string, allocating or reallocating memory
56  * as necessary. */
57 void
58 ds_reserve(struct ds *ds, size_t min_length)
59 {
60     if (min_length > ds->allocated || !ds->string) {
61         ds->allocated += MAX(min_length, ds->allocated);
62         ds->allocated = MAX(8, ds->allocated);
63         ds->string = xrealloc(ds->string, ds->allocated + 1);
64     }
65 }
66
67 /* Appends space for 'n' bytes to the end of 'ds->string', increasing
68  * 'ds->length' by the same amount, and returns the first appended byte.  The
69  * caller should fill in all 'n' bytes starting at the return value. */
70 char *
71 ds_put_uninit(struct ds *ds, size_t n)
72 {
73     ds_reserve(ds, ds->length + n);
74     ds->length += n;
75     ds->string[ds->length] = '\0';
76     return &ds->string[ds->length - n];
77 }
78
79 void
80 ds_put_char__(struct ds *ds, char c)
81 {
82     *ds_put_uninit(ds, 1) = c;
83 }
84
85 /* Appends unicode code point 'uc' to 'ds' in UTF-8 encoding. */
86 void
87 ds_put_utf8(struct ds *ds, int uc)
88 {
89     if (uc <= 0x7f) {
90         ds_put_char(ds, uc);
91     } else if (uc <= 0x7ff) {
92         ds_put_char(ds, 0xc0 | (uc >> 6));
93         ds_put_char(ds, 0x80 | (uc & 0x3f));
94     } else if (uc <= 0xffff) {
95         ds_put_char(ds, 0xe0 | (uc >> 12));
96         ds_put_char(ds, 0x80 | ((uc >> 6) & 0x3f));
97         ds_put_char(ds, 0x80 | (uc & 0x3f));
98     } else if (uc <= 0x10ffff) {
99         ds_put_char(ds, 0xf0 | (uc >> 18));
100         ds_put_char(ds, 0x80 | ((uc >> 12) & 0x3f));
101         ds_put_char(ds, 0x80 | ((uc >> 6) & 0x3f));
102         ds_put_char(ds, 0x80 | (uc & 0x3f));
103     } else {
104         /* Invalid code point.  Insert the Unicode general substitute
105          * REPLACEMENT CHARACTER. */
106         ds_put_utf8(ds, 0xfffd);
107     }
108 }
109
110 void
111 ds_put_char_multiple(struct ds *ds, char c, size_t n)
112 {
113     memset(ds_put_uninit(ds, n), c, n);
114 }
115
116 void
117 ds_put_buffer(struct ds *ds, const char *s, size_t n)
118 {
119     memcpy(ds_put_uninit(ds, n), s, n);
120 }
121
122 void
123 ds_put_cstr(struct ds *ds, const char *s)
124 {
125     size_t s_len = strlen(s);
126     memcpy(ds_put_uninit(ds, s_len), s, s_len);
127 }
128
129 void
130 ds_put_and_free_cstr(struct ds *ds, char *s)
131 {
132     ds_put_cstr(ds, s);
133     free(s);
134 }
135
136 void
137 ds_put_format(struct ds *ds, const char *format, ...)
138 {
139     va_list args;
140
141     va_start(args, format);
142     ds_put_format_valist(ds, format, args);
143     va_end(args);
144 }
145
146 void
147 ds_put_format_valist(struct ds *ds, const char *format, va_list args_)
148 {
149     va_list args;
150     size_t available;
151     int needed;
152
153     va_copy(args, args_);
154     available = ds->string ? ds->allocated - ds->length + 1 : 0;
155     needed = vsnprintf(&ds->string[ds->length], available, format, args);
156     va_end(args);
157
158     if (needed < available) {
159         ds->length += needed;
160     } else {
161         ds_reserve(ds, ds->length + needed);
162
163         va_copy(args, args_);
164         available = ds->allocated - ds->length + 1;
165         needed = vsnprintf(&ds->string[ds->length], available, format, args);
166         va_end(args);
167
168         assert(needed < available);
169         ds->length += needed;
170     }
171 }
172
173 void
174 ds_put_printable(struct ds *ds, const char *s, size_t n)
175 {
176     ds_reserve(ds, ds->length + n);
177     while (n-- > 0) {
178         unsigned char c = *s++;
179         if (c < 0x20 || c > 0x7e || c == '\\' || c == '"') {
180             ds_put_format(ds, "\\%03o", (int) c);
181         } else {
182             ds_put_char(ds, c);
183         }
184     }
185 }
186
187 /* Writes the current time to 'string' based on 'template'.
188  * The current time is either localtime or UTC based on 'utc'. */
189 void
190 ds_put_strftime(struct ds *ds, const char *template, bool utc)
191 {
192     const struct tm *tm;
193     time_t now = time_wall();
194     if (utc) {
195         tm = gmtime(&now);
196     } else {
197         tm = localtime(&now);
198     }
199
200     for (;;) {
201         size_t avail = ds->string ? ds->allocated - ds->length + 1 : 0;
202         size_t used = strftime(&ds->string[ds->length], avail, template, tm);
203         if (used) {
204             ds->length += used;
205             return;
206         }
207         ds_reserve(ds, ds->length + (avail < 32 ? 64 : 2 * avail));
208     }
209 }
210
211 int
212 ds_get_line(struct ds *ds, FILE *file)
213 {
214     ds_clear(ds);
215     for (;;) {
216         int c = getc(file);
217         if (c == EOF) {
218             return ds->length ? 0 : EOF;
219         } else if (c == '\n') {
220             return 0;
221         } else {
222             ds_put_char(ds, c);
223         }
224     }
225 }
226
227 /* Reads a line from 'file' into 'ds', clearing anything initially in 'ds'.
228  * Deletes comments introduced by "#" and skips lines that contains only white
229  * space (after deleting comments).
230  *
231  * Returns 0 if successful, EOF if no non-blank line was found. */
232 int
233 ds_get_preprocessed_line(struct ds *ds, FILE *file)
234 {
235     while (!ds_get_line(ds, file)) {
236         char *line = ds_cstr(ds);
237         char *comment;
238
239         /* Delete comments. */
240         comment = strchr(line, '#');
241         if (comment) {
242             *comment = '\0';
243         }
244
245         /* Return successfully unless the line is all spaces. */
246         if (line[strspn(line, " \t\n")] != '\0') {
247             return 0;
248         }
249     }
250     return EOF;
251 }
252
253 /* Reads a line from 'file' into 'ds' and does some preprocessing on it:
254  *
255  *    - If the line begins with #, prints it on stdout and reads the next line.
256  *
257  *    - Otherwise, if the line contains an # somewhere else, strips it and
258  *      everything following it (as a comment).
259  *
260  *    - If (after comment removal) the line contains only white space, prints
261  *      a blank line on stdout and reads the next line.
262  *
263  *    - Otherwise, returns the line to the caller.
264  *
265  * This is useful in some of the OVS tests, where we want to check that parsing
266  * and then re-formatting some kind of data does not change it, but we also
267  * want to be able to put comments in the input.
268  *
269  * Returns 0 if successful, EOF if no non-blank line was found. */
270 int
271 ds_get_test_line(struct ds *ds, FILE *file)
272 {
273     for (;;) {
274         char *s, *comment;
275         int retval;
276
277         retval = ds_get_line(ds, file);
278         if (retval) {
279             return retval;
280         }
281
282         s = ds_cstr(ds);
283         if (*s == '#') {
284             puts(s);
285             continue;
286         }
287
288         comment = strchr(s, '#');
289         if (comment) {
290             *comment = '\0';
291         }
292         if (s[strspn(s, " \t\n")] == '\0') {
293             putchar('\n');
294             continue;
295         }
296
297         return 0;
298     }
299 }
300
301 char *
302 ds_cstr(struct ds *ds)
303 {
304     if (!ds->string) {
305         ds_reserve(ds, 0);
306     }
307     ds->string[ds->length] = '\0';
308     return ds->string;
309 }
310
311 const char *
312 ds_cstr_ro(const struct ds *ds)
313 {
314     return ds_cstr(CONST_CAST(struct ds *, ds));
315 }
316
317 /* Returns a null-terminated string representing the current contents of 'ds',
318  * which the caller is expected to free with free(), then clears the contents
319  * of 'ds'. */
320 char *
321 ds_steal_cstr(struct ds *ds)
322 {
323     char *s = ds_cstr(ds);
324     ds_init(ds);
325     return s;
326 }
327
328 void
329 ds_destroy(struct ds *ds)
330 {
331     free(ds->string);
332 }
333
334 /* Swaps the content of 'a' and 'b'. */
335 void
336 ds_swap(struct ds *a, struct ds *b)
337 {
338     struct ds temp = *a;
339     *a = *b;
340     *b = temp;
341 }
342
343 /* Writes the 'size' bytes in 'buf' to 'string' as hex bytes arranged 16 per
344  * line.  Numeric offsets are also included, starting at 'ofs' for the first
345  * byte in 'buf'.  If 'ascii' is true then the corresponding ASCII characters
346  * are also rendered alongside. */
347 void
348 ds_put_hex_dump(struct ds *ds, const void *buf_, size_t size,
349                 uintptr_t ofs, bool ascii)
350 {
351   const uint8_t *buf = buf_;
352   const size_t per_line = 16; /* Maximum bytes per line. */
353
354   while (size > 0)
355     {
356       size_t start, end, n;
357       size_t i;
358
359       /* Number of bytes on this line. */
360       start = ofs % per_line;
361       end = per_line;
362       if (end - start > size)
363         end = start + size;
364       n = end - start;
365
366       /* Print line. */
367       ds_put_format(ds, "%08jx  ", (uintmax_t) ROUND_DOWN(ofs, per_line));
368       for (i = 0; i < start; i++)
369         ds_put_format(ds, "   ");
370       for (; i < end; i++)
371         ds_put_format(ds, "%02hhx%c",
372                 buf[i - start], i == per_line / 2 - 1? '-' : ' ');
373       if (ascii)
374         {
375           for (; i < per_line; i++)
376             ds_put_format(ds, "   ");
377           ds_put_format(ds, "|");
378           for (i = 0; i < start; i++)
379             ds_put_format(ds, " ");
380           for (; i < end; i++) {
381               int c = buf[i - start];
382               ds_put_char(ds, c >= 32 && c < 127 ? c : '.');
383           }
384           for (; i < per_line; i++)
385             ds_put_format(ds, " ");
386           ds_put_format(ds, "|");
387         }
388       ds_put_format(ds, "\n");
389
390       ofs += n;
391       buf += n;
392       size -= n;
393     }
394 }
395
396 int
397 ds_last(const struct ds *ds)
398 {
399     return ds->length > 0 ? (unsigned char) ds->string[ds->length - 1] : EOF;
400 }
401
402 void
403 ds_chomp(struct ds *ds, int c)
404 {
405     if (ds->length > 0 && ds->string[ds->length - 1] == (char) c) {
406         ds->string[--ds->length] = '\0';
407     }
408 }