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