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