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