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