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