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