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