d7c71b11f5509f15678693555676c54cc4662e3f
[pspp] / src / libpspp / str.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 1997-9, 2000, 2006, 2009, 2010, 2011, 2012 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program 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 General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include "str.h"
20
21 #include <ctype.h>
22 #include <errno.h>
23 #include <stdint.h>
24 #include <stdlib.h>
25 #include <unistr.h>
26
27 #include "libpspp/cast.h"
28 #include "libpspp/message.h"
29 #include "libpspp/pool.h"
30
31 #include "gl/c-ctype.h"
32 #include "gl/c-vasnprintf.h"
33 #include "gl/relocatable.h"
34 #include "gl/minmax.h"
35 #include "gl/xalloc.h"
36 #include "gl/xmemdup0.h"
37 #include "gl/xsize.h"
38 \f
39 /* Reverses the order of NBYTES bytes at address P, thus converting
40    between little- and big-endian byte orders.  */
41 void
42 buf_reverse (char *p, size_t nbytes)
43 {
44   char *h = p, *t = &h[nbytes - 1];
45   char temp;
46
47   nbytes /= 2;
48   while (nbytes--)
49     {
50       temp = *h;
51       *h++ = *t;
52       *t-- = temp;
53     }
54 }
55
56 /* Compares the SIZE bytes in A to those in B, disregarding case,
57    and returns a strcmp()-type result. */
58 int
59 buf_compare_case (const char *a_, const char *b_, size_t size)
60 {
61   const unsigned char *a = (unsigned char *) a_;
62   const unsigned char *b = (unsigned char *) b_;
63
64   while (size-- > 0)
65     {
66       unsigned char ac = toupper (*a++);
67       unsigned char bc = toupper (*b++);
68
69       if (ac != bc)
70         return ac > bc ? 1 : -1;
71     }
72
73   return 0;
74 }
75
76 /* Compares A of length A_LEN to B of length B_LEN.  The shorter
77    string is considered to be padded with spaces to the length of
78    the longer. */
79 int
80 buf_compare_rpad (const char *a, size_t a_len, const char *b, size_t b_len)
81 {
82   size_t min_len;
83   int result;
84
85   min_len = a_len < b_len ? a_len : b_len;
86   result = memcmp (a, b, min_len);
87   if (result != 0)
88     return result;
89   else
90     {
91       size_t idx;
92
93       if (a_len < b_len)
94         {
95           for (idx = min_len; idx < b_len; idx++)
96             if (' ' != b[idx])
97               return ' ' > b[idx] ? 1 : -1;
98         }
99       else
100         {
101           for (idx = min_len; idx < a_len; idx++)
102             if (a[idx] != ' ')
103               return a[idx] > ' ' ? 1 : -1;
104         }
105       return 0;
106     }
107 }
108
109 /* Compares strin A to string B.  The shorter string is
110    considered to be padded with spaces to the length of the
111    longer. */
112 int
113 str_compare_rpad (const char *a, const char *b)
114 {
115   return buf_compare_rpad (a, strlen (a), b, strlen (b));
116 }
117
118 /* Copies string SRC to buffer DST, of size DST_SIZE bytes.
119    DST is truncated to DST_SIZE bytes or padded on the right with
120    copies of PAD as needed. */
121 void
122 buf_copy_str_rpad (char *dst, size_t dst_size, const char *src, char pad)
123 {
124   size_t src_len = strlen (src);
125   if (src_len >= dst_size)
126     memcpy (dst, src, dst_size);
127   else
128     {
129       memcpy (dst, src, src_len);
130       memset (&dst[src_len], pad, dst_size - src_len);
131     }
132 }
133
134 /* Copies string SRC to buffer DST, of size DST_SIZE bytes.
135    DST is truncated to DST_SIZE bytes or padded on the left with
136    copies of PAD as needed. */
137 void
138 buf_copy_str_lpad (char *dst, size_t dst_size, const char *src, char pad)
139 {
140   size_t src_len = strlen (src);
141   if (src_len >= dst_size)
142     memcpy (dst, src, dst_size);
143   else
144     {
145       size_t pad_cnt = dst_size - src_len;
146       memset (&dst[0], pad, pad_cnt);
147       memcpy (dst + pad_cnt, src, src_len);
148     }
149 }
150
151 /* Copies buffer SRC, of SRC_SIZE bytes, to DST, of DST_SIZE bytes.
152    DST is truncated to DST_SIZE bytes or padded on the left with
153    copies of PAD as needed. */
154 void
155 buf_copy_lpad (char *dst, size_t dst_size,
156                const char *src, size_t src_size,
157                char pad)
158 {
159   if (src_size >= dst_size)
160     memmove (dst, src, dst_size);
161   else
162     {
163       memset (dst, pad, dst_size - src_size);
164       memmove (&dst[dst_size - src_size], src, src_size);
165     }
166 }
167
168 /* Copies buffer SRC, of SRC_SIZE bytes, to DST, of DST_SIZE bytes.
169    DST is truncated to DST_SIZE bytes or padded on the right with
170    copies of PAD as needed. */
171 void
172 buf_copy_rpad (char *dst, size_t dst_size,
173                const char *src, size_t src_size,
174                char pad)
175 {
176   if (src_size >= dst_size)
177     memmove (dst, src, dst_size);
178   else
179     {
180       memmove (dst, src, src_size);
181       memset (&dst[src_size], pad, dst_size - src_size);
182     }
183 }
184
185 /* Copies string SRC to string DST, which is in a buffer DST_SIZE
186    bytes long.
187    Truncates DST to DST_SIZE - 1 bytes or right-pads with
188    spaces to DST_SIZE - 1 bytes if necessary. */
189 void
190 str_copy_rpad (char *dst, size_t dst_size, const char *src)
191 {
192   if (dst_size > 0) 
193     {
194       size_t src_len = strlen (src);
195       if (src_len < dst_size - 1)
196         {
197           memcpy (dst, src, src_len);
198           memset (&dst[src_len], ' ', dst_size - 1 - src_len);
199         }
200       else
201         memcpy (dst, src, dst_size - 1);
202       dst[dst_size - 1] = 0;
203     }
204 }
205
206 /* Copies SRC to DST, which is in a buffer DST_SIZE bytes long.
207    Truncates DST to DST_SIZE - 1 bytes, if necessary. */
208 void
209 str_copy_trunc (char *dst, size_t dst_size, const char *src)
210 {
211   size_t src_len = strlen (src);
212   assert (dst_size > 0);
213   if (src_len + 1 < dst_size)
214     memcpy (dst, src, src_len + 1);
215   else
216     {
217       memcpy (dst, src, dst_size - 1);
218       dst[dst_size - 1] = '\0';
219     }
220 }
221
222 /* Copies buffer SRC, of SRC_LEN bytes,
223    to DST, which is in a buffer DST_SIZE bytes long.
224    Truncates DST to DST_SIZE - 1 bytes, if necessary. */
225 void
226 str_copy_buf_trunc (char *dst, size_t dst_size,
227                     const char *src, size_t src_size)
228 {
229   size_t dst_len;
230   assert (dst_size > 0);
231
232   dst_len = src_size < dst_size ? src_size : dst_size - 1;
233   memcpy (dst, src, dst_len);
234   dst[dst_len] = '\0';
235 }
236
237 /* Converts each byte in S to uppercase.
238
239    This is suitable only for ASCII strings.  Use utf8_to_upper() for UTF-8
240    strings.*/
241 void
242 str_uppercase (char *s)
243 {
244   for (; *s != '\0'; s++)
245     *s = c_toupper ((unsigned char) *s);
246 }
247
248 /* Converts each byte in S to lowercase.
249
250    This is suitable only for ASCII strings.  Use utf8_to_lower() for UTF-8
251    strings.*/
252 void
253 str_lowercase (char *s)
254 {
255   for (; *s != '\0'; s++)
256     *s = c_tolower ((unsigned char) *s);
257 }
258
259 /* Converts NUMBER into a string in 26-adic notation in BUFFER,
260    which has room for SIZE bytes.  Returns true if successful,
261    false if NUMBER, plus a trailing null, is too large to fit in
262    the available space.
263
264    26-adic notation is "spreadsheet column numbering": 1 = A, 2 =
265    B, 3 = C, ... 26 = Z, 27 = AA, 28 = AB, 29 = AC, ...
266
267    26-adic notation is the special case of a k-adic numeration
268    system (aka bijective base-k numeration) with k=26.  In k-adic
269    numeration, the digits are {1, 2, 3, ..., k} (there is no
270    digit 0), and integer 0 is represented by the empty string.
271    For more information, see
272    http://en.wikipedia.org/wiki/Bijective_numeration. */
273 bool
274 str_format_26adic (unsigned long int number, char buffer[], size_t size)
275 {
276   size_t length = 0;
277
278   while (number-- > 0)
279     {
280       if (length >= size)
281         goto overflow;
282       buffer[length++] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[number % 26];
283       number /= 26;
284     }
285
286   if (length >= size)
287     goto overflow;
288   buffer[length] = '\0';
289
290   buf_reverse (buffer, length);
291   return true;
292
293 overflow:
294   if (length > 0)
295     buffer[0] = '\0';
296   return false;
297 }
298
299 /* Sets the SIZE bytes starting at BLOCK to C,
300    and returns the byte following BLOCK. */
301 void *
302 mempset (void *block, int c, size_t size)
303 {
304   memset (block, c, size);
305   return (char *) block + size;
306 }
307 \f
308 /* Substrings. */
309
310 /* Returns a substring whose contents are the CNT bytes
311    starting at the (0-based) position START in SS. */
312 struct substring
313 ss_substr (struct substring ss, size_t start, size_t cnt)
314 {
315   if (start < ss.length)
316     return ss_buffer (ss.string + start, MIN (cnt, ss.length - start));
317   else
318     return ss_buffer (ss.string + ss.length, 0);
319 }
320
321 /* Returns a substring whose contents are the first CNT
322    bytes in SS. */
323 struct substring
324 ss_head (struct substring ss, size_t cnt)
325 {
326   return ss_buffer (ss.string, MIN (cnt, ss.length));
327 }
328
329 /* Returns a substring whose contents are the last CNT bytes
330    in SS. */
331 struct substring
332 ss_tail (struct substring ss, size_t cnt)
333 {
334   if (cnt < ss.length)
335     return ss_buffer (ss.string + (ss.length - cnt), cnt);
336   else
337     return ss;
338 }
339
340 /* Makes a malloc()'d, null-terminated copy of the contents of OLD
341    and stores it in NEW. */
342 void
343 ss_alloc_substring (struct substring *new, struct substring old)
344 {
345   new->string = xmemdup0 (old.string, old.length);
346   new->length = old.length;
347 }
348
349 /* Allocates room for a CNT-byte string in NEW. */
350 void
351 ss_alloc_uninit (struct substring *new, size_t cnt)
352 {
353   new->string = xmalloc (cnt);
354   new->length = cnt;
355 }
356
357 void
358 ss_realloc (struct substring *ss, size_t size)
359 {
360   ss->string = xrealloc (ss->string, size);
361 }
362
363 /* Makes a pool_alloc_unaligned()'d, null-terminated copy of the contents of
364    OLD in POOL, and stores it in NEW. */
365 void
366 ss_alloc_substring_pool (struct substring *new, struct substring old,
367                          struct pool *pool)
368 {
369   new->string = pool_alloc_unaligned (pool, old.length + 1);
370   new->length = old.length;
371   memcpy (new->string, old.string, old.length);
372   new->string[old.length] = '\0';
373 }
374
375 /* Allocates room for a CNT-byte string in NEW in POOL. */
376 void
377 ss_alloc_uninit_pool (struct substring *new, size_t cnt, struct pool *pool)
378 {
379   new->string = pool_alloc_unaligned (pool, cnt);
380   new->length = cnt;
381 }
382
383 /* Frees the string that SS points to. */
384 void
385 ss_dealloc (struct substring *ss)
386 {
387   free (ss->string);
388 }
389
390 /* Truncates SS to at most CNT bytes in length. */
391 void
392 ss_truncate (struct substring *ss, size_t cnt)
393 {
394   if (ss->length > cnt)
395     ss->length = cnt;
396 }
397
398 /* Removes trailing bytes in TRIM_SET from SS.
399    Returns number of bytes removed. */
400 size_t
401 ss_rtrim (struct substring *ss, struct substring trim_set)
402 {
403   size_t cnt = 0;
404   while (cnt < ss->length
405          && ss_find_byte (trim_set,
406                           ss->string[ss->length - cnt - 1]) != SIZE_MAX)
407     cnt++;
408   ss->length -= cnt;
409   return cnt;
410 }
411
412 /* Removes leading bytes in TRIM_SET from SS.
413    Returns number of bytes removed. */
414 size_t
415 ss_ltrim (struct substring *ss, struct substring trim_set)
416 {
417   size_t cnt = ss_span (*ss, trim_set);
418   ss_advance (ss, cnt);
419   return cnt;
420 }
421
422 /* Trims leading and trailing bytes in TRIM_SET from SS. */
423 void
424 ss_trim (struct substring *ss, struct substring trim_set)
425 {
426   ss_ltrim (ss, trim_set);
427   ss_rtrim (ss, trim_set);
428 }
429
430 /* If the last byte in SS is C, removes it and returns true.
431    Otherwise, returns false without changing the string. */
432 bool
433 ss_chomp_byte (struct substring *ss, char c)
434 {
435   if (ss_last (*ss) == c)
436     {
437       ss->length--;
438       return true;
439     }
440   else
441     return false;
442 }
443
444 /* If SS ends with SUFFIX, removes it and returns true.
445    Otherwise, returns false without changing the string. */
446 bool
447 ss_chomp (struct substring *ss, struct substring suffix)
448 {
449   if (ss_ends_with (*ss, suffix))
450     {
451       ss->length -= suffix.length;
452       return true;
453     }
454   else
455     return false;
456 }
457
458 /* Divides SS into tokens separated by any of the DELIMITERS.
459    Each call replaces TOKEN by the next token in SS, or by an
460    empty string if no tokens remain.  Returns true if a token was
461    obtained, false otherwise.
462
463    Before the first call, initialize *SAVE_IDX to 0.  Do not
464    modify *SAVE_IDX between calls.
465
466    SS divides into exactly one more tokens than it contains
467    delimiters.  That is, a delimiter at the start or end of SS or
468    a pair of adjacent delimiters yields an empty token, and the
469    empty string contains a single token. */
470 bool
471 ss_separate (struct substring ss, struct substring delimiters,
472              size_t *save_idx, struct substring *token)
473 {
474   if (*save_idx <= ss_length (ss))
475     {
476       struct substring tmp = ss_substr (ss, *save_idx, SIZE_MAX);
477       size_t length = ss_cspan (tmp, delimiters);
478       *token = ss_head (tmp, length);
479       *save_idx += length + 1;
480       return true;
481     }
482   else
483     {
484       *token = ss_empty ();
485       return false;
486     }
487 }
488
489 /* Divides SS into tokens separated by any of the DELIMITERS,
490    merging adjacent delimiters so that the empty string is never
491    produced as a token.  Each call replaces TOKEN by the next
492    token in SS, or by an empty string if no tokens remain, and
493    then skips past the first delimiter following the token.
494    Returns true if a token was obtained, false otherwise.
495
496    Before the first call, initialize *SAVE_IDX to 0.  Do not
497    modify *SAVE_IDX between calls. */
498 bool
499 ss_tokenize (struct substring ss, struct substring delimiters,
500              size_t *save_idx, struct substring *token)
501 {
502   bool found_token;
503
504   ss_advance (&ss, *save_idx);
505   *save_idx += ss_ltrim (&ss, delimiters);
506   ss_get_bytes (&ss, ss_cspan (ss, delimiters), token);
507
508   found_token = ss_length (*token) > 0;
509   *save_idx += ss_length (*token) + found_token;
510   return found_token;
511 }
512
513 /* Removes the first CNT bytes from SS. */
514 void
515 ss_advance (struct substring *ss, size_t cnt)
516 {
517   if (cnt > ss->length)
518     cnt = ss->length;
519   ss->string += cnt;
520   ss->length -= cnt;
521 }
522
523 /* If the first byte in SS is C, removes it and returns true.
524    Otherwise, returns false without changing the string. */
525 bool
526 ss_match_byte (struct substring *ss, char c)
527 {
528   if (ss_first (*ss) == c)
529     {
530       ss->string++;
531       ss->length--;
532       return true;
533     }
534   else
535     return false;
536 }
537
538 /* If the first byte in SS is in MATCH, removes it and
539    returns the byte that was removed.
540    Otherwise, returns EOF without changing the string. */
541 int
542 ss_match_byte_in (struct substring *ss, struct substring match)
543 {
544   int c = EOF;
545   if (ss->length > 0
546       && memchr (match.string, ss->string[0], match.length) != NULL)
547     {
548       c = ss->string[0];
549       ss->string++;
550       ss->length--;
551     }
552   return c;
553 }
554
555 /* If SS begins with TARGET, removes it and returns true.
556    Otherwise, returns false without changing SS. */
557 bool
558 ss_match_string (struct substring *ss, const struct substring target)
559 {
560   size_t length = ss_length (target);
561   if (ss_equals (ss_head (*ss, length), target))
562     {
563       ss_advance (ss, length);
564       return true;
565     }
566   else
567     return false;
568 }
569
570 /* Removes the first byte from SS and returns it.
571    If SS is empty, returns EOF without modifying SS. */
572 int
573 ss_get_byte (struct substring *ss)
574 {
575   int c = ss_first (*ss);
576   if (c != EOF)
577     {
578       ss->string++;
579       ss->length--;
580     }
581   return c;
582 }
583
584 /* Stores the prefix of SS up to the first DELIMITER in OUT (if
585    any).  Trims those same bytes from SS.  DELIMITER is
586    removed from SS but not made part of OUT.  Returns true if
587    DELIMITER was found (and removed), false otherwise. */
588 bool
589 ss_get_until (struct substring *ss, char delimiter, struct substring *out)
590 {
591   ss_get_bytes (ss, ss_cspan (*ss, ss_buffer (&delimiter, 1)), out);
592   return ss_match_byte (ss, delimiter);
593 }
594
595 /* Stores the first CNT bytes in SS in OUT (or fewer, if SS
596    is shorter than CNT bytes).  Trims the same bytes
597    from the beginning of SS.  Returns CNT. */
598 size_t
599 ss_get_bytes (struct substring *ss, size_t cnt, struct substring *out)
600 {
601   *out = ss_head (*ss, cnt);
602   ss_advance (ss, cnt);
603   return cnt;
604 }
605
606 /* Parses and removes an optionally signed decimal integer from
607    the beginning of SS.  Returns 0 if an error occurred,
608    otherwise the number of bytes removed from SS.  Stores
609    the integer's value into *VALUE. */
610 size_t
611 ss_get_long (struct substring *ss, long *value)
612 {
613   char tmp[64];
614   size_t length;
615
616   length = ss_span (*ss, ss_cstr ("+-"));
617   length += ss_span (ss_substr (*ss, length, SIZE_MAX), ss_cstr (CC_DIGITS));
618   if (length > 0 && length < sizeof tmp)
619     {
620       char *tail;
621
622       memcpy (tmp, ss_data (*ss), length);
623       tmp[length] = '\0';
624
625       *value = strtol (tmp, &tail, 10);
626       if (tail - tmp == length)
627         {
628           ss_advance (ss, length);
629           return length;
630         }
631     }
632   *value = 0;
633   return 0;
634 }
635
636 /* Returns true if SS is empty (has length 0 bytes),
637    false otherwise. */
638 bool
639 ss_is_empty (struct substring ss)
640 {
641   return ss.length == 0;
642 }
643
644 /* Returns the number of bytes in SS. */
645 size_t
646 ss_length (struct substring ss)
647 {
648   return ss.length;
649 }
650
651 /* Returns a pointer to the bytes in SS. */
652 char *
653 ss_data (struct substring ss)
654 {
655   return ss.string;
656 }
657
658 /* Returns a pointer just past the last byte in SS. */
659 char *
660 ss_end (struct substring ss)
661 {
662   return ss.string + ss.length;
663 }
664
665 /* Returns the byte in position IDX in SS, as a value in the
666    range of unsigned char.  Returns EOF if IDX is out of the
667    range of indexes for SS. */
668 int
669 ss_at (struct substring ss, size_t idx)
670 {
671   return idx < ss.length ? (unsigned char) ss.string[idx] : EOF;
672 }
673
674 /* Returns the first byte in SS as a value in the range of
675    unsigned char.  Returns EOF if SS is the empty string. */
676 int
677 ss_first (struct substring ss)
678 {
679   return ss_at (ss, 0);
680 }
681
682 /* Returns the last byte in SS as a value in the range of
683    unsigned char.  Returns EOF if SS is the empty string. */
684 int
685 ss_last (struct substring ss)
686 {
687   return ss.length > 0 ? (unsigned char) ss.string[ss.length - 1] : EOF;
688 }
689
690 /* Returns true if SS ends with SUFFIX, false otherwise. */
691 bool
692 ss_ends_with (struct substring ss, struct substring suffix)
693 {
694   return (ss.length >= suffix.length
695           && !memcmp (&ss.string[ss.length - suffix.length], suffix.string,
696                       suffix.length));
697 }
698
699 /* Returns the number of contiguous bytes at the beginning
700    of SS that are in SKIP_SET. */
701 size_t
702 ss_span (struct substring ss, struct substring skip_set)
703 {
704   size_t i;
705   for (i = 0; i < ss.length; i++)
706     if (ss_find_byte (skip_set, ss.string[i]) == SIZE_MAX)
707       break;
708   return i;
709 }
710
711 /* Returns the number of contiguous bytes at the beginning
712    of SS that are not in SKIP_SET. */
713 size_t
714 ss_cspan (struct substring ss, struct substring stop_set)
715 {
716   size_t i;
717   for (i = 0; i < ss.length; i++)
718     if (ss_find_byte (stop_set, ss.string[i]) != SIZE_MAX)
719       break;
720   return i;
721 }
722
723 /* Returns the offset in SS of the first instance of C,
724    or SIZE_MAX if C does not occur in SS. */
725 size_t
726 ss_find_byte (struct substring ss, char c)
727 {
728   const char *p = memchr (ss.string, c, ss.length);
729   return p != NULL ? p - ss.string : SIZE_MAX;
730 }
731
732 /* Compares A and B and returns a strcmp()-type comparison
733    result. */
734 int
735 ss_compare (struct substring a, struct substring b)
736 {
737   int retval = memcmp (a.string, b.string, MIN (a.length, b.length));
738   if (retval == 0)
739     retval = a.length < b.length ? -1 : a.length > b.length;
740   return retval;
741 }
742
743 /* Compares A and B case-insensitively and returns a
744    strcmp()-type comparison result. */
745 int
746 ss_compare_case (struct substring a, struct substring b)
747 {
748   int retval = memcasecmp (a.string, b.string, MIN (a.length, b.length));
749   if (retval == 0)
750     retval = a.length < b.length ? -1 : a.length > b.length;
751   return retval;
752 }
753
754 /* Compares A and B and returns true if their contents are
755    identical, false otherwise. */
756 int
757 ss_equals (struct substring a, struct substring b)
758 {
759   return a.length == b.length && !memcmp (a.string, b.string, a.length);
760 }
761
762 /* Compares A and B and returns true if their contents are
763    identical except possibly for case differences, false
764    otherwise. */
765 int
766 ss_equals_case (struct substring a, struct substring b)
767 {
768   return a.length == b.length && !memcasecmp (a.string, b.string, a.length);
769 }
770
771 /* Returns the position in SS that the byte at P occupies.
772    P must point within SS or one past its end. */
773 size_t
774 ss_pointer_to_position (struct substring ss, const char *p)
775 {
776   size_t pos = p - ss.string;
777   assert (pos <= ss.length);
778   return pos;
779 }
780
781 /* Allocates and returns a null-terminated string that contains
782    SS. */
783 char *
784 ss_xstrdup (struct substring ss)
785 {
786   char *s = xmalloc (ss.length + 1);
787   memcpy (s, ss.string, ss.length);
788   s[ss.length] = '\0';
789   return s;
790 }
791 /* UTF-8. */
792
793 /* Returns the character represented by the UTF-8 sequence at the start of S.
794    The return value is either a Unicode code point in the range 0 to 0x10ffff,
795    or UINT32_MAX if S is empty. */
796 ucs4_t
797 ss_first_mb (struct substring s)
798 {
799   return ss_at_mb (s, 0);
800 }
801
802 /* Returns the number of bytes in the UTF-8 character at the beginning of S.
803
804    The return value is 0 if S is empty, otherwise between 1 and 4. */
805 int
806 ss_first_mblen (struct substring s)
807 {
808   return ss_at_mblen (s, 0);
809 }
810
811 /* Advances S past the UTF-8 character at its beginning.  Returns the Unicode
812    code point that was skipped (in the range 0 to 0x10ffff), or UINT32_MAX if S
813    was not modified because it was initially empty. */
814 ucs4_t
815 ss_get_mb (struct substring *s)
816 {
817   if (s->length > 0)
818     {
819       ucs4_t uc;
820       int n;
821
822       n = u8_mbtouc (&uc, CHAR_CAST (const uint8_t *, s->string), s->length);
823       s->string += n;
824       s->length -= n;
825       return uc;
826     }
827   else
828     return UINT32_MAX;
829 }
830
831 /* Returns the character represented by the UTF-8 sequence starting OFS bytes
832    into S.  The return value is either a Unicode code point in the range 0 to
833    0x10ffff, or UINT32_MAX if OFS is past the last byte in S.
834
835    (Returns 0xfffd if OFS points into the middle, not the beginning, of a UTF-8
836    sequence.)  */
837 ucs4_t
838 ss_at_mb (struct substring s, size_t ofs)
839 {
840   if (s.length > ofs)
841     {
842       ucs4_t uc;
843       u8_mbtouc (&uc, CHAR_CAST (const uint8_t *, s.string + ofs),
844                  s.length - ofs);
845       return uc;
846     }
847   else
848     return UINT32_MAX;
849 }
850
851 /* Returns the number of bytes represented by the UTF-8 sequence starting OFS
852    bytes into S.  The return value is 0 if OFS is past the last byte in S,
853    otherwise between 1 and 4. */
854 int
855 ss_at_mblen (struct substring s, size_t ofs)
856 {
857   if (s.length > ofs)
858     {
859       ucs4_t uc;
860       return u8_mbtouc (&uc, CHAR_CAST (const uint8_t *, s.string + ofs),
861                         s.length - ofs);
862     }
863   else
864     return 0;
865 }
866 \f
867 /* Initializes ST as an empty string. */
868 void
869 ds_init_empty (struct string *st)
870 {
871   st->ss = ss_empty ();
872   st->capacity = 0;
873 }
874
875 /* Initializes ST with initial contents S. */
876 void
877 ds_init_string (struct string *st, const struct string *s)
878 {
879   ds_init_substring (st, ds_ss (s));
880 }
881
882 /* Initializes ST with initial contents SS. */
883 void
884 ds_init_substring (struct string *st, struct substring ss)
885 {
886   st->capacity = MAX (8, ss.length * 2);
887   st->ss.string = xmalloc (st->capacity + 1);
888   memcpy (st->ss.string, ss.string, ss.length);
889   st->ss.length = ss.length;
890 }
891
892 /* Initializes ST with initial contents S. */
893 void
894 ds_init_cstr (struct string *st, const char *s)
895 {
896   ds_init_substring (st, ss_cstr (s));
897 }
898
899 /* Frees ST. */
900 void
901 ds_destroy (struct string *st)
902 {
903   if (st != NULL)
904     {
905       ss_dealloc (&st->ss);
906       st->ss.string = NULL;
907       st->ss.length = 0;
908       st->capacity = 0;
909     }
910 }
911
912 /* Swaps the contents of strings A and B. */
913 void
914 ds_swap (struct string *a, struct string *b)
915 {
916   struct string tmp = *a;
917   *a = *b;
918   *b = tmp;
919 }
920
921 /* Helper function for ds_register_pool. */
922 static void
923 free_string (void *st_)
924 {
925   struct string *st = st_;
926   ds_destroy (st);
927 }
928
929 /* Arranges for ST to be destroyed automatically as part of
930    POOL. */
931 void
932 ds_register_pool (struct string *st, struct pool *pool)
933 {
934   pool_register (pool, free_string, st);
935 }
936
937 /* Cancels the arrangement for ST to be destroyed automatically
938    as part of POOL. */
939 void
940 ds_unregister_pool (struct string *st, struct pool *pool)
941 {
942   pool_unregister (pool, st);
943 }
944
945 /* Copies SRC into DST.
946    DST and SRC may be the same string. */
947 void
948 ds_assign_string (struct string *dst, const struct string *src)
949 {
950   ds_assign_substring (dst, ds_ss (src));
951 }
952
953 /* Replaces DST by SS.
954    SS may be a substring of DST. */
955 void
956 ds_assign_substring (struct string *dst, struct substring ss)
957 {
958   dst->ss.length = ss.length;
959   ds_extend (dst, ss.length);
960   memmove (dst->ss.string, ss.string, ss.length);
961 }
962
963 /* Replaces DST by null-terminated string SRC.  SRC may overlap
964    with DST. */
965 void
966 ds_assign_cstr (struct string *dst, const char *src)
967 {
968   ds_assign_substring (dst, ss_cstr (src));
969 }
970
971 /* Truncates ST to zero length. */
972 void
973 ds_clear (struct string *st)
974 {
975   st->ss.length = 0;
976 }
977
978 /* Returns a substring that contains ST. */
979 struct substring
980 ds_ss (const struct string *st)
981 {
982   return st->ss;
983 }
984
985 /* Returns a substring that contains CNT bytes from ST
986    starting at position START.
987
988    If START is greater than or equal to the length of ST, then
989    the substring will be the empty string.  If START + CNT
990    exceeds the length of ST, then the substring will only be
991    ds_length(ST) - START bytes long. */
992 struct substring
993 ds_substr (const struct string *st, size_t start, size_t cnt)
994 {
995   return ss_substr (ds_ss (st), start, cnt);
996 }
997
998 /* Returns a substring that contains the first CNT bytes in
999    ST.  If CNT exceeds the length of ST, then the substring will
1000    contain all of ST. */
1001 struct substring
1002 ds_head (const struct string *st, size_t cnt)
1003 {
1004   return ss_head (ds_ss (st), cnt);
1005 }
1006
1007 /* Returns a substring that contains the last CNT bytes in
1008    ST.  If CNT exceeds the length of ST, then the substring will
1009    contain all of ST. */
1010 struct substring
1011 ds_tail (const struct string *st, size_t cnt)
1012 {
1013   return ss_tail (ds_ss (st), cnt);
1014 }
1015
1016 /* Ensures that ST can hold at least MIN_CAPACITY bytes plus a null
1017    terminator. */
1018 void
1019 ds_extend (struct string *st, size_t min_capacity)
1020 {
1021   if (min_capacity > st->capacity)
1022     {
1023       st->capacity *= 2;
1024       if (st->capacity < min_capacity)
1025         st->capacity = 2 * min_capacity;
1026
1027       st->ss.string = xrealloc (st->ss.string, st->capacity + 1);
1028     }
1029 }
1030
1031 /* Shrink ST to the minimum capacity need to contain its content. */
1032 void
1033 ds_shrink (struct string *st)
1034 {
1035   if (st->capacity != st->ss.length)
1036     {
1037       st->capacity = st->ss.length;
1038       st->ss.string = xrealloc (st->ss.string, st->capacity + 1);
1039     }
1040 }
1041
1042 /* Truncates ST to at most LENGTH bytes long. */
1043 void
1044 ds_truncate (struct string *st, size_t length)
1045 {
1046   ss_truncate (&st->ss, length);
1047 }
1048
1049 /* Removes trailing bytes in TRIM_SET from ST.
1050    Returns number of bytes removed. */
1051 size_t
1052 ds_rtrim (struct string *st, struct substring trim_set)
1053 {
1054   return ss_rtrim (&st->ss, trim_set);
1055 }
1056
1057 /* Removes leading bytes in TRIM_SET from ST.
1058    Returns number of bytes removed. */
1059 size_t
1060 ds_ltrim (struct string *st, struct substring trim_set)
1061 {
1062   size_t cnt = ds_span (st, trim_set);
1063   if (cnt > 0)
1064     ds_assign_substring (st, ds_substr (st, cnt, SIZE_MAX));
1065   return cnt;
1066 }
1067
1068 /* Trims leading and trailing bytes in TRIM_SET from ST.
1069    Returns number of bytes removed. */
1070 size_t
1071 ds_trim (struct string *st, struct substring trim_set)
1072 {
1073   size_t cnt = ds_rtrim (st, trim_set);
1074   return cnt + ds_ltrim (st, trim_set);
1075 }
1076
1077 /* If the last byte in ST is C, removes it and returns true.
1078    Otherwise, returns false without modifying ST. */
1079 bool
1080 ds_chomp_byte (struct string *st, char c)
1081 {
1082   return ss_chomp_byte (&st->ss, c);
1083 }
1084
1085 /* If ST ends with SUFFIX, removes it and returns true.
1086    Otherwise, returns false without modifying ST. */
1087 bool
1088 ds_chomp (struct string *st, struct substring suffix)
1089 {
1090   return ss_chomp (&st->ss, suffix);
1091 }
1092
1093 /* Divides ST into tokens separated by any of the DELIMITERS.
1094    Each call replaces TOKEN by the next token in ST, or by an
1095    empty string if no tokens remain.  Returns true if a token was
1096    obtained, false otherwise.
1097
1098    Before the first call, initialize *SAVE_IDX to 0.  Do not
1099    modify *SAVE_IDX between calls.
1100
1101    ST divides into exactly one more tokens than it contains
1102    delimiters.  That is, a delimiter at the start or end of ST or
1103    a pair of adjacent delimiters yields an empty token, and the
1104    empty string contains a single token. */
1105 bool
1106 ds_separate (const struct string *st, struct substring delimiters,
1107              size_t *save_idx, struct substring *token)
1108 {
1109   return ss_separate (ds_ss (st), delimiters, save_idx, token);
1110 }
1111
1112 /* Divides ST into tokens separated by any of the DELIMITERS,
1113    merging adjacent delimiters so that the empty string is never
1114    produced as a token.  Each call replaces TOKEN by the next
1115    token in ST, or by an empty string if no tokens remain.
1116    Returns true if a token was obtained, false otherwise.
1117
1118    Before the first call, initialize *SAVE_IDX to 0.  Do not
1119    modify *SAVE_IDX between calls. */
1120 bool
1121 ds_tokenize (const struct string *st, struct substring delimiters,
1122              size_t *save_idx, struct substring *token)
1123 {
1124   return ss_tokenize (ds_ss (st), delimiters, save_idx, token);
1125 }
1126
1127 /* Pad ST on the right with copies of PAD until ST is at least
1128    LENGTH bytes in size.  If ST is initially LENGTH
1129    bytes or longer, this is a no-op. */
1130 void
1131 ds_rpad (struct string *st, size_t length, char pad)
1132 {
1133   if (length > st->ss.length)
1134     ds_put_byte_multiple (st, pad, length - st->ss.length);
1135 }
1136
1137 /* Sets the length of ST to exactly NEW_LENGTH,
1138    either by truncating bytes from the end,
1139    or by padding on the right with PAD. */
1140 void
1141 ds_set_length (struct string *st, size_t new_length, char pad)
1142 {
1143   if (st->ss.length < new_length)
1144     ds_rpad (st, new_length, pad);
1145   else
1146     st->ss.length = new_length;
1147 }
1148
1149 /* Removes N bytes from ST starting at offset START. */
1150 void
1151 ds_remove (struct string *st, size_t start, size_t n)
1152 {
1153   if (n > 0 && start < st->ss.length)
1154     {
1155       if (st->ss.length - start <= n)
1156         {
1157           /* All bytes at or beyond START are deleted. */
1158           st->ss.length = start;
1159         }
1160       else
1161         {
1162           /* Some bytes remain and must be shifted into
1163              position. */
1164           memmove (st->ss.string + st->ss.length,
1165                    st->ss.string + st->ss.length + n,
1166                    st->ss.length - start - n);
1167           st->ss.length -= n;
1168         }
1169     }
1170   else
1171     {
1172       /* There are no bytes to delete or no bytes at or
1173          beyond START, hence deletion is a no-op. */
1174     }
1175 }
1176
1177 /* Returns true if ST is empty, false otherwise. */
1178 bool
1179 ds_is_empty (const struct string *st)
1180 {
1181   return ss_is_empty (st->ss);
1182 }
1183
1184 /* Returns the length of ST. */
1185 size_t
1186 ds_length (const struct string *st)
1187 {
1188   return ss_length (ds_ss (st));
1189 }
1190
1191 /* Returns the string data inside ST. */
1192 char *
1193 ds_data (const struct string *st)
1194 {
1195   return ss_data (ds_ss (st));
1196 }
1197
1198 /* Returns a pointer to the null terminator ST.
1199    This might not be an actual null byte unless ds_c_str() has
1200    been called since the last modification to ST. */
1201 char *
1202 ds_end (const struct string *st)
1203 {
1204   return ss_end (ds_ss (st));
1205 }
1206
1207 /* Returns the byte in position IDX in ST, as a value in the
1208    range of unsigned char.  Returns EOF if IDX is out of the
1209    range of indexes for ST. */
1210 int
1211 ds_at (const struct string *st, size_t idx)
1212 {
1213   return ss_at (ds_ss (st), idx);
1214 }
1215
1216 /* Returns the first byte in ST as a value in the range of
1217    unsigned char.  Returns EOF if ST is the empty string. */
1218 int
1219 ds_first (const struct string *st)
1220 {
1221   return ss_first (ds_ss (st));
1222 }
1223
1224 /* Returns the last byte in ST as a value in the range of
1225    unsigned char.  Returns EOF if ST is the empty string. */
1226 int
1227 ds_last (const struct string *st)
1228 {
1229   return ss_last (ds_ss (st));
1230 }
1231
1232 /* Returns true if ST ends with SUFFIX, false otherwise. */
1233 bool
1234 ds_ends_with (const struct string *st, struct substring suffix)
1235 {
1236   return ss_ends_with (st->ss, suffix);
1237 }
1238
1239 /* Returns the number of consecutive bytes at the beginning
1240    of ST that are in SKIP_SET. */
1241 size_t
1242 ds_span (const struct string *st, struct substring skip_set)
1243 {
1244   return ss_span (ds_ss (st), skip_set);
1245 }
1246
1247 /* Returns the number of consecutive bytes at the beginning
1248    of ST that are not in STOP_SET.  */
1249 size_t
1250 ds_cspan (const struct string *st, struct substring stop_set)
1251 {
1252   return ss_cspan (ds_ss (st), stop_set);
1253 }
1254
1255 /* Returns the position of the first occurrence of byte C in
1256    ST at or after position OFS, or SIZE_MAX if there is no such
1257    occurrence. */
1258 size_t
1259 ds_find_byte (const struct string *st, char c)
1260 {
1261   return ss_find_byte (ds_ss (st), c);
1262 }
1263
1264 /* Compares A and B and returns a strcmp()-type comparison
1265    result. */
1266 int
1267 ds_compare (const struct string *a, const struct string *b)
1268 {
1269   return ss_compare (ds_ss (a), ds_ss (b));
1270 }
1271
1272 /* Returns the position in ST that the byte at P occupies.
1273    P must point within ST or one past its end. */
1274 size_t
1275 ds_pointer_to_position (const struct string *st, const char *p)
1276 {
1277   return ss_pointer_to_position (ds_ss (st), p);
1278 }
1279
1280 /* Allocates and returns a null-terminated string that contains
1281    ST. */
1282 char *
1283 ds_xstrdup (const struct string *st)
1284 {
1285   return ss_xstrdup (ds_ss (st));
1286 }
1287
1288 /* Returns the allocation size of ST. */
1289 size_t
1290 ds_capacity (const struct string *st)
1291 {
1292   return st->capacity;
1293 }
1294
1295 /* Returns the value of ST as a null-terminated string. */
1296 char *
1297 ds_cstr (const struct string *st_)
1298 {
1299   struct string *st = CONST_CAST (struct string *, st_);
1300   if (st->ss.string == NULL)
1301     ds_extend (st, 1);
1302   st->ss.string[st->ss.length] = '\0';
1303   return st->ss.string;
1304 }
1305
1306 /* Returns the value of ST as a null-terminated string and then
1307    reinitialized ST as an empty string.  The caller must free the
1308    returned string with free(). */
1309 char *
1310 ds_steal_cstr (struct string *st)
1311 {
1312   char *s = ds_cstr (st);
1313   ds_init_empty (st);
1314   return s;
1315 }
1316
1317 /* Reads bytes from STREAM and appends them to ST, stopping
1318    after MAX_LENGTH bytes, after appending a newline, or
1319    after an I/O error or end of file was encountered, whichever
1320    comes first.  Returns true if at least one byte was added
1321    to ST, false if no bytes were read before an I/O error or
1322    end of file (or if MAX_LENGTH was 0).
1323
1324    This function treats LF and CR LF sequences as new-line,
1325    translating each of them to a single '\n' in ST. */
1326 bool
1327 ds_read_line (struct string *st, FILE *stream, size_t max_length)
1328 {
1329   size_t length;
1330
1331   for (length = 0; length < max_length; length++)
1332     {
1333       int c = getc (stream);
1334       switch (c)
1335         {
1336         case EOF:
1337           return length > 0;
1338
1339         case '\n':
1340           ds_put_byte (st, c);
1341           return true;
1342
1343         case '\r':
1344           c = getc (stream);
1345           if (c == '\n')
1346             {
1347               /* CR followed by LF is special: translate to \n. */
1348               ds_put_byte (st, '\n');
1349               return true;
1350             }
1351           else
1352             {
1353               /* CR followed by anything else is just CR. */
1354               ds_put_byte (st, '\r');
1355               if (c == EOF)
1356                 return true;
1357               ungetc (c, stream);
1358             }
1359           break;
1360
1361         default:
1362           ds_put_byte (st, c);
1363         }
1364     }
1365
1366   return length > 0;
1367 }
1368
1369 /* Removes a comment introduced by `#' from ST,
1370    ignoring occurrences inside quoted strings. */
1371 static void
1372 remove_comment (struct string *st)
1373 {
1374   char *cp;
1375   int quote = 0;
1376
1377   for (cp = ds_data (st); cp < ds_end (st); cp++)
1378     if (quote)
1379       {
1380         if (*cp == quote)
1381           quote = 0;
1382         else if (*cp == '\\')
1383           cp++;
1384       }
1385     else if (*cp == '\'' || *cp == '"')
1386       quote = *cp;
1387     else if (*cp == '#')
1388       {
1389         ds_truncate (st, cp - ds_cstr (st));
1390         break;
1391       }
1392 }
1393
1394 /* Reads a line from STREAM into ST, then preprocesses as follows:
1395
1396    - Splices lines terminated with `\'.
1397
1398    - Deletes comments introduced by `#' outside of single or double
1399      quotes.
1400
1401    - Deletes trailing white space.
1402
1403    Returns true if a line was successfully read, false on
1404    failure.  If LINE_NUMBER is non-null, then *LINE_NUMBER is
1405    incremented by the number of lines read. */
1406 bool
1407 ds_read_config_line (struct string *st, int *line_number, FILE *stream)
1408 {
1409   ds_clear (st);
1410   do
1411     {
1412       if (!ds_read_line (st, stream, SIZE_MAX))
1413         return false;
1414       (*line_number)++;
1415       ds_rtrim (st, ss_cstr (CC_SPACES));
1416     }
1417   while (ds_chomp_byte (st, '\\'));
1418
1419   remove_comment (st);
1420   return true;
1421 }
1422
1423 /* Attempts to read SIZE * CNT bytes from STREAM and append them
1424    to ST.
1425    Returns true if all the requested data was read, false otherwise. */
1426 bool
1427 ds_read_stream (struct string *st, size_t size, size_t cnt, FILE *stream)
1428 {
1429   if (size != 0)
1430     {
1431       size_t try_bytes = xtimes (cnt, size);
1432       if (size_in_bounds_p (xsum (ds_length (st), try_bytes)))
1433         {
1434           char *buffer = ds_put_uninit (st, try_bytes);
1435           size_t got_bytes = fread (buffer, 1, try_bytes, stream);
1436           ds_truncate (st, ds_length (st) - (try_bytes - got_bytes));
1437           return got_bytes == try_bytes;
1438         }
1439       else
1440         {
1441           errno = ENOMEM;
1442           return false;
1443         }
1444     }
1445   else
1446     return true;
1447 }
1448
1449 /* Concatenates S onto ST. */
1450 void
1451 ds_put_cstr (struct string *st, const char *s)
1452 {
1453   if (s != NULL)
1454     ds_put_substring (st, ss_cstr (s));
1455 }
1456
1457 /* Concatenates SS to ST. */
1458 void
1459 ds_put_substring (struct string *st, struct substring ss)
1460 {
1461   memcpy (ds_put_uninit (st, ss_length (ss)), ss_data (ss), ss_length (ss));
1462 }
1463
1464 /* Returns ds_end(ST) and THEN increases the length by INCR. */
1465 char *
1466 ds_put_uninit (struct string *st, size_t incr)
1467 {
1468   char *end;
1469   ds_extend (st, ds_length (st) + incr);
1470   end = ds_end (st);
1471   st->ss.length += incr;
1472   return end;
1473 }
1474
1475 /* Moves the bytes in ST following offset OFS + OLD_LEN in ST to offset OFS +
1476    NEW_LEN and returns the byte at offset OFS.  The first min(OLD_LEN, NEW_LEN)
1477    bytes at the returned position are unchanged; if NEW_LEN > OLD_LEN then the
1478    following NEW_LEN - OLD_LEN bytes are initially indeterminate.
1479
1480    The intention is that the caller should write NEW_LEN bytes at the returned
1481    position, to effectively replace the OLD_LEN bytes previously at that
1482    position. */
1483 char *
1484 ds_splice_uninit (struct string *st,
1485                   size_t ofs, size_t old_len, size_t new_len)
1486 {
1487   if (new_len != old_len)
1488     {
1489       if (new_len > old_len)
1490         ds_extend (st, ds_length (st) + (new_len - old_len));
1491       memmove (ds_data (st) + (ofs + new_len),
1492                ds_data (st) + (ofs + old_len),
1493                ds_length (st) - (ofs + old_len));
1494       st->ss.length += new_len - old_len;
1495     }
1496   return ds_data (st) + ofs;
1497 }
1498
1499 /* Formats FORMAT as a printf string and appends the result to ST. */
1500 void
1501 ds_put_format (struct string *st, const char *format, ...)
1502 {
1503   va_list args;
1504
1505   va_start (args, format);
1506   ds_put_vformat (st, format, args);
1507   va_end (args);
1508 }
1509
1510 /* Formats FORMAT as a printf string as if in the C locale and appends the result to ST. */
1511 void
1512 ds_put_c_format (struct string *st, const char *format, ...)
1513 {
1514   va_list args;
1515
1516   va_start (args, format);
1517   ds_put_c_vformat (st, format, args);
1518   va_end (args);
1519 }
1520
1521
1522 /* Formats FORMAT as a printf string, using fmt_func (a snprintf like function) 
1523    and appends the result to ST. */
1524 static void
1525 ds_put_vformat_int (struct string *st, const char *format, va_list args_,
1526                     int (*fmt_func) (char *, size_t, const char *, va_list))
1527 {
1528   int avail, needed;
1529   va_list args;
1530
1531   va_copy (args, args_);
1532   avail = st->ss.string != NULL ? st->capacity - st->ss.length + 1 : 0;
1533   needed = fmt_func (st->ss.string + st->ss.length, avail, format, args);
1534   va_end (args);
1535
1536   if (needed >= avail)
1537     {
1538       va_copy (args, args_);
1539       fmt_func (ds_put_uninit (st, needed), needed + 1, format, args);
1540       va_end (args);
1541     }
1542   else
1543     {
1544       /* Some old libc's returned -1 when the destination string
1545          was too short. */
1546       while (needed == -1)
1547         {
1548           ds_extend (st, (st->capacity + 1) * 2);
1549           avail = st->capacity - st->ss.length + 1;
1550
1551           va_copy (args, args_);
1552           needed = fmt_func (ds_end (st), avail, format, args);
1553           va_end (args);
1554         }
1555       st->ss.length += needed;
1556     }
1557 }
1558
1559
1560 static int
1561 vasnwrapper (char *str, size_t size,  const char *format, va_list ap)
1562 {
1563   c_vasnprintf (str, &size, format, ap);
1564   return size;
1565 }
1566
1567 /* Formats FORMAT as a printf string and appends the result to ST. */
1568 void
1569 ds_put_vformat (struct string *st, const char *format, va_list args_)
1570 {
1571   ds_put_vformat_int (st, format, args_, vsnprintf);
1572 }
1573
1574 /* Formats FORMAT as a printf string, as if in the C locale, 
1575    and appends the result to ST. */
1576 void
1577 ds_put_c_vformat (struct string *st, const char *format, va_list args_)
1578 {
1579   ds_put_vformat_int (st, format, args_, vasnwrapper);
1580 }
1581
1582 /* Appends byte CH to ST. */
1583 void
1584 ds_put_byte (struct string *st, int ch)
1585 {
1586   ds_put_uninit (st, 1)[0] = ch;
1587 }
1588
1589 /* Appends CNT copies of byte CH to ST. */
1590 void
1591 ds_put_byte_multiple (struct string *st, int ch, size_t cnt)
1592 {
1593   memset (ds_put_uninit (st, cnt), ch, cnt);
1594 }
1595
1596 /* Appends Unicode code point UC to ST in UTF-8 encoding. */
1597 void
1598 ds_put_unichar (struct string *st, ucs4_t uc)
1599 {
1600   ds_extend (st, ds_length (st) + 6);
1601   st->ss.length += u8_uctomb (CHAR_CAST (uint8_t *, ds_end (st)), uc, 6);
1602 }
1603
1604 /* If relocation has been enabled, replace ST,
1605    with its relocated version */
1606 void
1607 ds_relocate (struct string *st)
1608 {
1609   const char *orig = ds_cstr (st);
1610   const char *rel = relocate (orig);
1611
1612   if ( orig != rel)
1613     {
1614       ds_clear (st);
1615       ds_put_cstr (st, rel);
1616       /* The documentation for relocate says that casting away const
1617         and then freeing is appropriate ... */
1618       free (CONST_CAST (char *, rel));
1619     }
1620 }
1621
1622
1623 \f
1624
1625 /* Operations on uint8_t "strings" */
1626
1627 /* Copies buffer SRC, of SRC_SIZE bytes, to DST, of DST_SIZE bytes.
1628    DST is truncated to DST_SIZE bytes or padded on the right with
1629    copies of PAD as needed. */
1630 void
1631 u8_buf_copy_rpad (uint8_t *dst, size_t dst_size,
1632                   const uint8_t *src, size_t src_size,
1633                   char pad)
1634 {
1635   if (src_size >= dst_size)
1636     memmove (dst, src, dst_size);
1637   else
1638     {
1639       memmove (dst, src, src_size);
1640       memset (&dst[src_size], pad, dst_size - src_size);
1641     }
1642 }