str: Make ss_alloc_substring_pool() null-terminate its output.
[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, null-terminated copy of the contents of
351    OLD 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 + 1);
357   new->length = old.length;
358   memcpy (new->string, old.string, old.length);
359   new->string[old.length] = '\0';
360 }
361
362 /* Allocates room for a CNT-byte string in NEW in POOL. */
363 void
364 ss_alloc_uninit_pool (struct substring *new, size_t cnt, struct pool *pool)
365 {
366   new->string = pool_alloc_unaligned (pool, cnt);
367   new->length = cnt;
368 }
369
370 /* Frees the string that SS points to. */
371 void
372 ss_dealloc (struct substring *ss)
373 {
374   free (ss->string);
375 }
376
377 /* Truncates SS to at most CNT bytes in length. */
378 void
379 ss_truncate (struct substring *ss, size_t cnt)
380 {
381   if (ss->length > cnt)
382     ss->length = cnt;
383 }
384
385 /* Removes trailing bytes in TRIM_SET from SS.
386    Returns number of bytes removed. */
387 size_t
388 ss_rtrim (struct substring *ss, struct substring trim_set)
389 {
390   size_t cnt = 0;
391   while (cnt < ss->length
392          && ss_find_byte (trim_set,
393                           ss->string[ss->length - cnt - 1]) != SIZE_MAX)
394     cnt++;
395   ss->length -= cnt;
396   return cnt;
397 }
398
399 /* Removes leading bytes in TRIM_SET from SS.
400    Returns number of bytes removed. */
401 size_t
402 ss_ltrim (struct substring *ss, struct substring trim_set)
403 {
404   size_t cnt = ss_span (*ss, trim_set);
405   ss_advance (ss, cnt);
406   return cnt;
407 }
408
409 /* Trims leading and trailing bytes in TRIM_SET from SS. */
410 void
411 ss_trim (struct substring *ss, struct substring trim_set)
412 {
413   ss_ltrim (ss, trim_set);
414   ss_rtrim (ss, trim_set);
415 }
416
417 /* If the last byte in SS is C, removes it and returns true.
418    Otherwise, returns false without changing the string. */
419 bool
420 ss_chomp_byte (struct substring *ss, char c)
421 {
422   if (ss_last (*ss) == c)
423     {
424       ss->length--;
425       return true;
426     }
427   else
428     return false;
429 }
430
431 /* If SS ends with SUFFIX, removes it and returns true.
432    Otherwise, returns false without changing the string. */
433 bool
434 ss_chomp (struct substring *ss, struct substring suffix)
435 {
436   if (ss_ends_with (*ss, suffix))
437     {
438       ss->length -= suffix.length;
439       return true;
440     }
441   else
442     return false;
443 }
444
445 /* Divides SS into tokens separated by any of the DELIMITERS.
446    Each call replaces TOKEN by the next token in SS, or by an
447    empty string if no tokens remain.  Returns true if a token was
448    obtained, false otherwise.
449
450    Before the first call, initialize *SAVE_IDX to 0.  Do not
451    modify *SAVE_IDX between calls.
452
453    SS divides into exactly one more tokens than it contains
454    delimiters.  That is, a delimiter at the start or end of SS or
455    a pair of adjacent delimiters yields an empty token, and the
456    empty string contains a single token. */
457 bool
458 ss_separate (struct substring ss, struct substring delimiters,
459              size_t *save_idx, struct substring *token)
460 {
461   if (*save_idx <= ss_length (ss))
462     {
463       struct substring tmp = ss_substr (ss, *save_idx, SIZE_MAX);
464       size_t length = ss_cspan (tmp, delimiters);
465       *token = ss_head (tmp, length);
466       *save_idx += length + 1;
467       return true;
468     }
469   else
470     {
471       *token = ss_empty ();
472       return false;
473     }
474 }
475
476 /* Divides SS into tokens separated by any of the DELIMITERS,
477    merging adjacent delimiters so that the empty string is never
478    produced as a token.  Each call replaces TOKEN by the next
479    token in SS, or by an empty string if no tokens remain, and
480    then skips past the first delimiter following the token.
481    Returns true if a token was obtained, false otherwise.
482
483    Before the first call, initialize *SAVE_IDX to 0.  Do not
484    modify *SAVE_IDX between calls. */
485 bool
486 ss_tokenize (struct substring ss, struct substring delimiters,
487              size_t *save_idx, struct substring *token)
488 {
489   ss_advance (&ss, *save_idx);
490   *save_idx += ss_ltrim (&ss, delimiters);
491   ss_get_bytes (&ss, ss_cspan (ss, delimiters), token);
492   *save_idx += ss_length (*token) + 1;
493   return ss_length (*token) > 0;
494 }
495
496 /* Removes the first CNT bytes from SS. */
497 void
498 ss_advance (struct substring *ss, size_t cnt)
499 {
500   if (cnt > ss->length)
501     cnt = ss->length;
502   ss->string += cnt;
503   ss->length -= cnt;
504 }
505
506 /* If the first byte in SS is C, removes it and returns true.
507    Otherwise, returns false without changing the string. */
508 bool
509 ss_match_byte (struct substring *ss, char c)
510 {
511   if (ss_first (*ss) == c)
512     {
513       ss->string++;
514       ss->length--;
515       return true;
516     }
517   else
518     return false;
519 }
520
521 /* If the first byte in SS is in MATCH, removes it and
522    returns the byte that was removed.
523    Otherwise, returns EOF without changing the string. */
524 int
525 ss_match_byte_in (struct substring *ss, struct substring match)
526 {
527   int c = EOF;
528   if (ss->length > 0
529       && memchr (match.string, ss->string[0], match.length) != NULL)
530     {
531       c = ss->string[0];
532       ss->string++;
533       ss->length--;
534     }
535   return c;
536 }
537
538 /* If SS begins with TARGET, removes it and returns true.
539    Otherwise, returns false without changing SS. */
540 bool
541 ss_match_string (struct substring *ss, const struct substring target)
542 {
543   size_t length = ss_length (target);
544   if (ss_equals (ss_head (*ss, length), target))
545     {
546       ss_advance (ss, length);
547       return true;
548     }
549   else
550     return false;
551 }
552
553 /* Removes the first byte from SS and returns it.
554    If SS is empty, returns EOF without modifying SS. */
555 int
556 ss_get_byte (struct substring *ss)
557 {
558   int c = ss_first (*ss);
559   if (c != EOF)
560     {
561       ss->string++;
562       ss->length--;
563     }
564   return c;
565 }
566
567 /* Stores the prefix of SS up to the first DELIMITER in OUT (if
568    any).  Trims those same bytes from SS.  DELIMITER is
569    removed from SS but not made part of OUT.  Returns true if
570    DELIMITER was found (and removed), false otherwise. */
571 bool
572 ss_get_until (struct substring *ss, char delimiter, struct substring *out)
573 {
574   ss_get_bytes (ss, ss_cspan (*ss, ss_buffer (&delimiter, 1)), out);
575   return ss_match_byte (ss, delimiter);
576 }
577
578 /* Stores the first CNT bytes in SS in OUT (or fewer, if SS
579    is shorter than CNT bytes).  Trims the same bytes
580    from the beginning of SS.  Returns CNT. */
581 size_t
582 ss_get_bytes (struct substring *ss, size_t cnt, struct substring *out)
583 {
584   *out = ss_head (*ss, cnt);
585   ss_advance (ss, cnt);
586   return cnt;
587 }
588
589 /* Parses and removes an optionally signed decimal integer from
590    the beginning of SS.  Returns 0 if an error occurred,
591    otherwise the number of bytes removed from SS.  Stores
592    the integer's value into *VALUE. */
593 size_t
594 ss_get_long (struct substring *ss, long *value)
595 {
596   char tmp[64];
597   size_t length;
598
599   length = ss_span (*ss, ss_cstr ("+-"));
600   length += ss_span (ss_substr (*ss, length, SIZE_MAX), ss_cstr (CC_DIGITS));
601   if (length > 0 && length < sizeof tmp)
602     {
603       char *tail;
604
605       memcpy (tmp, ss_data (*ss), length);
606       tmp[length] = '\0';
607
608       *value = strtol (tmp, &tail, 10);
609       if (tail - tmp == length)
610         {
611           ss_advance (ss, length);
612           return length;
613         }
614     }
615   *value = 0;
616   return 0;
617 }
618
619 /* Returns true if SS is empty (has length 0 bytes),
620    false otherwise. */
621 bool
622 ss_is_empty (struct substring ss)
623 {
624   return ss.length == 0;
625 }
626
627 /* Returns the number of bytes in SS. */
628 size_t
629 ss_length (struct substring ss)
630 {
631   return ss.length;
632 }
633
634 /* Returns a pointer to the bytes in SS. */
635 char *
636 ss_data (struct substring ss)
637 {
638   return ss.string;
639 }
640
641 /* Returns a pointer just past the last byte in SS. */
642 char *
643 ss_end (struct substring ss)
644 {
645   return ss.string + ss.length;
646 }
647
648 /* Returns the byte in position IDX in SS, as a value in the
649    range of unsigned char.  Returns EOF if IDX is out of the
650    range of indexes for SS. */
651 int
652 ss_at (struct substring ss, size_t idx)
653 {
654   return idx < ss.length ? (unsigned char) ss.string[idx] : EOF;
655 }
656
657 /* Returns the first byte in SS as a value in the range of
658    unsigned char.  Returns EOF if SS is the empty string. */
659 int
660 ss_first (struct substring ss)
661 {
662   return ss_at (ss, 0);
663 }
664
665 /* Returns the last byte in SS as a value in the range of
666    unsigned char.  Returns EOF if SS is the empty string. */
667 int
668 ss_last (struct substring ss)
669 {
670   return ss.length > 0 ? (unsigned char) ss.string[ss.length - 1] : EOF;
671 }
672
673 /* Returns true if SS ends with SUFFIX, false otherwise. */
674 bool
675 ss_ends_with (struct substring ss, struct substring suffix)
676 {
677   return (ss.length >= suffix.length
678           && !memcmp (&ss.string[ss.length - suffix.length], suffix.string,
679                       suffix.length));
680 }
681
682 /* Returns the number of contiguous bytes at the beginning
683    of SS that are in SKIP_SET. */
684 size_t
685 ss_span (struct substring ss, struct substring skip_set)
686 {
687   size_t i;
688   for (i = 0; i < ss.length; i++)
689     if (ss_find_byte (skip_set, ss.string[i]) == SIZE_MAX)
690       break;
691   return i;
692 }
693
694 /* Returns the number of contiguous bytes at the beginning
695    of SS that are not in SKIP_SET. */
696 size_t
697 ss_cspan (struct substring ss, struct substring stop_set)
698 {
699   size_t i;
700   for (i = 0; i < ss.length; i++)
701     if (ss_find_byte (stop_set, ss.string[i]) != SIZE_MAX)
702       break;
703   return i;
704 }
705
706 /* Returns the offset in SS of the first instance of C,
707    or SIZE_MAX if C does not occur in SS. */
708 size_t
709 ss_find_byte (struct substring ss, char c)
710 {
711   const char *p = memchr (ss.string, c, ss.length);
712   return p != NULL ? p - ss.string : SIZE_MAX;
713 }
714
715 /* Compares A and B and returns a strcmp()-type comparison
716    result. */
717 int
718 ss_compare (struct substring a, struct substring b)
719 {
720   int retval = memcmp (a.string, b.string, MIN (a.length, b.length));
721   if (retval == 0)
722     retval = a.length < b.length ? -1 : a.length > b.length;
723   return retval;
724 }
725
726 /* Compares A and B case-insensitively and returns a
727    strcmp()-type comparison result. */
728 int
729 ss_compare_case (struct substring a, struct substring b)
730 {
731   int retval = memcasecmp (a.string, b.string, MIN (a.length, b.length));
732   if (retval == 0)
733     retval = a.length < b.length ? -1 : a.length > b.length;
734   return retval;
735 }
736
737 /* Compares A and B and returns true if their contents are
738    identical, false otherwise. */
739 int
740 ss_equals (struct substring a, struct substring b)
741 {
742   return a.length == b.length && !memcmp (a.string, b.string, a.length);
743 }
744
745 /* Compares A and B and returns true if their contents are
746    identical except possibly for case differences, false
747    otherwise. */
748 int
749 ss_equals_case (struct substring a, struct substring b)
750 {
751   return a.length == b.length && !memcasecmp (a.string, b.string, a.length);
752 }
753
754 /* Returns the position in SS that the byte at P occupies.
755    P must point within SS or one past its end. */
756 size_t
757 ss_pointer_to_position (struct substring ss, const char *p)
758 {
759   size_t pos = p - ss.string;
760   assert (pos <= ss.length);
761   return pos;
762 }
763
764 /* Allocates and returns a null-terminated string that contains
765    SS. */
766 char *
767 ss_xstrdup (struct substring ss)
768 {
769   char *s = xmalloc (ss.length + 1);
770   memcpy (s, ss.string, ss.length);
771   s[ss.length] = '\0';
772   return s;
773 }
774 /* UTF-8. */
775
776 /* Returns the character represented by the UTF-8 sequence at the start of S.
777    The return value is either a Unicode code point in the range 0 to 0x10ffff,
778    or UINT32_MAX if S is empty. */
779 ucs4_t
780 ss_first_mb (struct substring s)
781 {
782   return ss_at_mb (s, 0);
783 }
784
785 /* Returns the number of bytes in the UTF-8 character at the beginning of S.
786
787    The return value is 0 if S is empty, otherwise between 1 and 4. */
788 int
789 ss_first_mblen (struct substring s)
790 {
791   return ss_at_mblen (s, 0);
792 }
793
794 /* Advances S past the UTF-8 character at its beginning.  Returns the Unicode
795    code point that was skipped (in the range 0 to 0x10ffff), or UINT32_MAX if S
796    was not modified because it was initially empty. */
797 ucs4_t
798 ss_get_mb (struct substring *s)
799 {
800   if (s->length > 0)
801     {
802       ucs4_t uc;
803       int n;
804
805       n = u8_mbtouc (&uc, CHAR_CAST (const uint8_t *, s->string), s->length);
806       s->string += n;
807       s->length -= n;
808       return uc;
809     }
810   else
811     return UINT32_MAX;
812 }
813
814 /* Returns the character represented by the UTF-8 sequence starting OFS bytes
815    into S.  The return value is either a Unicode code point in the range 0 to
816    0x10ffff, or UINT32_MAX if OFS is past the last byte in S.
817
818    (Returns 0xfffd if OFS points into the middle, not the beginning, of a UTF-8
819    sequence.)  */
820 ucs4_t
821 ss_at_mb (struct substring s, size_t ofs)
822 {
823   if (s.length > ofs)
824     {
825       ucs4_t uc;
826       u8_mbtouc (&uc, CHAR_CAST (const uint8_t *, s.string + ofs),
827                  s.length - ofs);
828       return uc;
829     }
830   else
831     return UINT32_MAX;
832 }
833
834 /* Returns the number of bytes represented by the UTF-8 sequence starting OFS
835    bytes into S.  The return value is 0 if OFS is past the last byte in S,
836    otherwise between 1 and 4. */
837 int
838 ss_at_mblen (struct substring s, size_t ofs)
839 {
840   if (s.length > ofs)
841     {
842       ucs4_t uc;
843       return u8_mbtouc (&uc, CHAR_CAST (const uint8_t *, s.string + ofs),
844                         s.length - ofs);
845     }
846   else
847     return 0;
848 }
849 \f
850 /* Initializes ST as an empty string. */
851 void
852 ds_init_empty (struct string *st)
853 {
854   st->ss = ss_empty ();
855   st->capacity = 0;
856 }
857
858 /* Initializes ST with initial contents S. */
859 void
860 ds_init_string (struct string *st, const struct string *s)
861 {
862   ds_init_substring (st, ds_ss (s));
863 }
864
865 /* Initializes ST with initial contents SS. */
866 void
867 ds_init_substring (struct string *st, struct substring ss)
868 {
869   st->capacity = MAX (8, ss.length * 2);
870   st->ss.string = xmalloc (st->capacity + 1);
871   memcpy (st->ss.string, ss.string, ss.length);
872   st->ss.length = ss.length;
873 }
874
875 /* Initializes ST with initial contents S. */
876 void
877 ds_init_cstr (struct string *st, const char *s)
878 {
879   ds_init_substring (st, ss_cstr (s));
880 }
881
882 /* Frees ST. */
883 void
884 ds_destroy (struct string *st)
885 {
886   if (st != NULL)
887     {
888       ss_dealloc (&st->ss);
889       st->ss.string = NULL;
890       st->ss.length = 0;
891       st->capacity = 0;
892     }
893 }
894
895 /* Swaps the contents of strings A and B. */
896 void
897 ds_swap (struct string *a, struct string *b)
898 {
899   struct string tmp = *a;
900   *a = *b;
901   *b = tmp;
902 }
903
904 /* Helper function for ds_register_pool. */
905 static void
906 free_string (void *st_)
907 {
908   struct string *st = st_;
909   ds_destroy (st);
910 }
911
912 /* Arranges for ST to be destroyed automatically as part of
913    POOL. */
914 void
915 ds_register_pool (struct string *st, struct pool *pool)
916 {
917   pool_register (pool, free_string, st);
918 }
919
920 /* Cancels the arrangement for ST to be destroyed automatically
921    as part of POOL. */
922 void
923 ds_unregister_pool (struct string *st, struct pool *pool)
924 {
925   pool_unregister (pool, st);
926 }
927
928 /* Copies SRC into DST.
929    DST and SRC may be the same string. */
930 void
931 ds_assign_string (struct string *dst, const struct string *src)
932 {
933   ds_assign_substring (dst, ds_ss (src));
934 }
935
936 /* Replaces DST by SS.
937    SS may be a substring of DST. */
938 void
939 ds_assign_substring (struct string *dst, struct substring ss)
940 {
941   dst->ss.length = ss.length;
942   ds_extend (dst, ss.length);
943   memmove (dst->ss.string, ss.string, ss.length);
944 }
945
946 /* Replaces DST by null-terminated string SRC.  SRC may overlap
947    with DST. */
948 void
949 ds_assign_cstr (struct string *dst, const char *src)
950 {
951   ds_assign_substring (dst, ss_cstr (src));
952 }
953
954 /* Truncates ST to zero length. */
955 void
956 ds_clear (struct string *st)
957 {
958   st->ss.length = 0;
959 }
960
961 /* Returns a substring that contains ST. */
962 struct substring
963 ds_ss (const struct string *st)
964 {
965   return st->ss;
966 }
967
968 /* Returns a substring that contains CNT bytes from ST
969    starting at position START.
970
971    If START is greater than or equal to the length of ST, then
972    the substring will be the empty string.  If START + CNT
973    exceeds the length of ST, then the substring will only be
974    ds_length(ST) - START bytes long. */
975 struct substring
976 ds_substr (const struct string *st, size_t start, size_t cnt)
977 {
978   return ss_substr (ds_ss (st), start, cnt);
979 }
980
981 /* Returns a substring that contains the first CNT bytes in
982    ST.  If CNT exceeds the length of ST, then the substring will
983    contain all of ST. */
984 struct substring
985 ds_head (const struct string *st, size_t cnt)
986 {
987   return ss_head (ds_ss (st), cnt);
988 }
989
990 /* Returns a substring that contains the last CNT bytes in
991    ST.  If CNT exceeds the length of ST, then the substring will
992    contain all of ST. */
993 struct substring
994 ds_tail (const struct string *st, size_t cnt)
995 {
996   return ss_tail (ds_ss (st), cnt);
997 }
998
999 /* Ensures that ST can hold at least MIN_CAPACITY bytes plus a null
1000    terminator. */
1001 void
1002 ds_extend (struct string *st, size_t min_capacity)
1003 {
1004   if (min_capacity > st->capacity)
1005     {
1006       st->capacity *= 2;
1007       if (st->capacity < min_capacity)
1008         st->capacity = 2 * min_capacity;
1009
1010       st->ss.string = xrealloc (st->ss.string, st->capacity + 1);
1011     }
1012 }
1013
1014 /* Shrink ST to the minimum capacity need to contain its content. */
1015 void
1016 ds_shrink (struct string *st)
1017 {
1018   if (st->capacity != st->ss.length)
1019     {
1020       st->capacity = st->ss.length;
1021       st->ss.string = xrealloc (st->ss.string, st->capacity + 1);
1022     }
1023 }
1024
1025 /* Truncates ST to at most LENGTH bytes long. */
1026 void
1027 ds_truncate (struct string *st, size_t length)
1028 {
1029   ss_truncate (&st->ss, length);
1030 }
1031
1032 /* Removes trailing bytes in TRIM_SET from ST.
1033    Returns number of bytes removed. */
1034 size_t
1035 ds_rtrim (struct string *st, struct substring trim_set)
1036 {
1037   return ss_rtrim (&st->ss, trim_set);
1038 }
1039
1040 /* Removes leading bytes in TRIM_SET from ST.
1041    Returns number of bytes removed. */
1042 size_t
1043 ds_ltrim (struct string *st, struct substring trim_set)
1044 {
1045   size_t cnt = ds_span (st, trim_set);
1046   if (cnt > 0)
1047     ds_assign_substring (st, ds_substr (st, cnt, SIZE_MAX));
1048   return cnt;
1049 }
1050
1051 /* Trims leading and trailing bytes in TRIM_SET from ST.
1052    Returns number of bytes removed. */
1053 size_t
1054 ds_trim (struct string *st, struct substring trim_set)
1055 {
1056   size_t cnt = ds_rtrim (st, trim_set);
1057   return cnt + ds_ltrim (st, trim_set);
1058 }
1059
1060 /* If the last byte in ST is C, removes it and returns true.
1061    Otherwise, returns false without modifying ST. */
1062 bool
1063 ds_chomp_byte (struct string *st, char c)
1064 {
1065   return ss_chomp_byte (&st->ss, c);
1066 }
1067
1068 /* If ST ends with SUFFIX, removes it and returns true.
1069    Otherwise, returns false without modifying ST. */
1070 bool
1071 ds_chomp (struct string *st, struct substring suffix)
1072 {
1073   return ss_chomp (&st->ss, suffix);
1074 }
1075
1076 /* Divides ST into tokens separated by any of the DELIMITERS.
1077    Each call replaces TOKEN by the next token in ST, or by an
1078    empty string if no tokens remain.  Returns true if a token was
1079    obtained, false otherwise.
1080
1081    Before the first call, initialize *SAVE_IDX to 0.  Do not
1082    modify *SAVE_IDX between calls.
1083
1084    ST divides into exactly one more tokens than it contains
1085    delimiters.  That is, a delimiter at the start or end of ST or
1086    a pair of adjacent delimiters yields an empty token, and the
1087    empty string contains a single token. */
1088 bool
1089 ds_separate (const struct string *st, struct substring delimiters,
1090              size_t *save_idx, struct substring *token)
1091 {
1092   return ss_separate (ds_ss (st), delimiters, save_idx, token);
1093 }
1094
1095 /* Divides ST into tokens separated by any of the DELIMITERS,
1096    merging adjacent delimiters so that the empty string is never
1097    produced as a token.  Each call replaces TOKEN by the next
1098    token in ST, or by an empty string if no tokens remain.
1099    Returns true if a token was obtained, false otherwise.
1100
1101    Before the first call, initialize *SAVE_IDX to 0.  Do not
1102    modify *SAVE_IDX between calls. */
1103 bool
1104 ds_tokenize (const struct string *st, struct substring delimiters,
1105              size_t *save_idx, struct substring *token)
1106 {
1107   return ss_tokenize (ds_ss (st), delimiters, save_idx, token);
1108 }
1109
1110 /* Pad ST on the right with copies of PAD until ST is at least
1111    LENGTH bytes in size.  If ST is initially LENGTH
1112    bytes or longer, this is a no-op. */
1113 void
1114 ds_rpad (struct string *st, size_t length, char pad)
1115 {
1116   if (length > st->ss.length)
1117     ds_put_byte_multiple (st, pad, length - st->ss.length);
1118 }
1119
1120 /* Sets the length of ST to exactly NEW_LENGTH,
1121    either by truncating bytes from the end,
1122    or by padding on the right with PAD. */
1123 void
1124 ds_set_length (struct string *st, size_t new_length, char pad)
1125 {
1126   if (st->ss.length < new_length)
1127     ds_rpad (st, new_length, pad);
1128   else
1129     st->ss.length = new_length;
1130 }
1131
1132 /* Removes N bytes from ST starting at offset START. */
1133 void
1134 ds_remove (struct string *st, size_t start, size_t n)
1135 {
1136   if (n > 0 && start < st->ss.length)
1137     {
1138       if (st->ss.length - start <= n)
1139         {
1140           /* All bytes at or beyond START are deleted. */
1141           st->ss.length = start;
1142         }
1143       else
1144         {
1145           /* Some bytes remain and must be shifted into
1146              position. */
1147           memmove (st->ss.string + st->ss.length,
1148                    st->ss.string + st->ss.length + n,
1149                    st->ss.length - start - n);
1150           st->ss.length -= n;
1151         }
1152     }
1153   else
1154     {
1155       /* There are no bytes to delete or no bytes at or
1156          beyond START, hence deletion is a no-op. */
1157     }
1158 }
1159
1160 /* Returns true if ST is empty, false otherwise. */
1161 bool
1162 ds_is_empty (const struct string *st)
1163 {
1164   return ss_is_empty (st->ss);
1165 }
1166
1167 /* Returns the length of ST. */
1168 size_t
1169 ds_length (const struct string *st)
1170 {
1171   return ss_length (ds_ss (st));
1172 }
1173
1174 /* Returns the string data inside ST. */
1175 char *
1176 ds_data (const struct string *st)
1177 {
1178   return ss_data (ds_ss (st));
1179 }
1180
1181 /* Returns a pointer to the null terminator ST.
1182    This might not be an actual null byte unless ds_c_str() has
1183    been called since the last modification to ST. */
1184 char *
1185 ds_end (const struct string *st)
1186 {
1187   return ss_end (ds_ss (st));
1188 }
1189
1190 /* Returns the byte in position IDX in ST, as a value in the
1191    range of unsigned char.  Returns EOF if IDX is out of the
1192    range of indexes for ST. */
1193 int
1194 ds_at (const struct string *st, size_t idx)
1195 {
1196   return ss_at (ds_ss (st), idx);
1197 }
1198
1199 /* Returns the first byte in ST as a value in the range of
1200    unsigned char.  Returns EOF if ST is the empty string. */
1201 int
1202 ds_first (const struct string *st)
1203 {
1204   return ss_first (ds_ss (st));
1205 }
1206
1207 /* Returns the last byte in ST as a value in the range of
1208    unsigned char.  Returns EOF if ST is the empty string. */
1209 int
1210 ds_last (const struct string *st)
1211 {
1212   return ss_last (ds_ss (st));
1213 }
1214
1215 /* Returns true if ST ends with SUFFIX, false otherwise. */
1216 bool
1217 ds_ends_with (const struct string *st, struct substring suffix)
1218 {
1219   return ss_ends_with (st->ss, suffix);
1220 }
1221
1222 /* Returns the number of consecutive bytes at the beginning
1223    of ST that are in SKIP_SET. */
1224 size_t
1225 ds_span (const struct string *st, struct substring skip_set)
1226 {
1227   return ss_span (ds_ss (st), skip_set);
1228 }
1229
1230 /* Returns the number of consecutive bytes at the beginning
1231    of ST that are not in STOP_SET.  */
1232 size_t
1233 ds_cspan (const struct string *st, struct substring stop_set)
1234 {
1235   return ss_cspan (ds_ss (st), stop_set);
1236 }
1237
1238 /* Returns the position of the first occurrence of byte C in
1239    ST at or after position OFS, or SIZE_MAX if there is no such
1240    occurrence. */
1241 size_t
1242 ds_find_byte (const struct string *st, char c)
1243 {
1244   return ss_find_byte (ds_ss (st), c);
1245 }
1246
1247 /* Compares A and B and returns a strcmp()-type comparison
1248    result. */
1249 int
1250 ds_compare (const struct string *a, const struct string *b)
1251 {
1252   return ss_compare (ds_ss (a), ds_ss (b));
1253 }
1254
1255 /* Returns the position in ST that the byte at P occupies.
1256    P must point within ST or one past its end. */
1257 size_t
1258 ds_pointer_to_position (const struct string *st, const char *p)
1259 {
1260   return ss_pointer_to_position (ds_ss (st), p);
1261 }
1262
1263 /* Allocates and returns a null-terminated string that contains
1264    ST. */
1265 char *
1266 ds_xstrdup (const struct string *st)
1267 {
1268   return ss_xstrdup (ds_ss (st));
1269 }
1270
1271 /* Returns the allocation size of ST. */
1272 size_t
1273 ds_capacity (const struct string *st)
1274 {
1275   return st->capacity;
1276 }
1277
1278 /* Returns the value of ST as a null-terminated string. */
1279 char *
1280 ds_cstr (const struct string *st_)
1281 {
1282   struct string *st = CONST_CAST (struct string *, st_);
1283   if (st->ss.string == NULL)
1284     ds_extend (st, 1);
1285   st->ss.string[st->ss.length] = '\0';
1286   return st->ss.string;
1287 }
1288
1289 /* Returns the value of ST as a null-terminated string and then
1290    reinitialized ST as an empty string.  The caller must free the
1291    returned string with free(). */
1292 char *
1293 ds_steal_cstr (struct string *st)
1294 {
1295   char *s = ds_cstr (st);
1296   ds_init_empty (st);
1297   return s;
1298 }
1299
1300 /* Reads bytes from STREAM and appends them to ST, stopping
1301    after MAX_LENGTH bytes, after appending a newline, or
1302    after an I/O error or end of file was encountered, whichever
1303    comes first.  Returns true if at least one byte was added
1304    to ST, false if no bytes were read before an I/O error or
1305    end of file (or if MAX_LENGTH was 0).
1306
1307    This function treats LF and CR LF sequences as new-line,
1308    translating each of them to a single '\n' in ST. */
1309 bool
1310 ds_read_line (struct string *st, FILE *stream, size_t max_length)
1311 {
1312   size_t length;
1313
1314   for (length = 0; length < max_length; length++)
1315     {
1316       int c = getc (stream);
1317       switch (c)
1318         {
1319         case EOF:
1320           return length > 0;
1321
1322         case '\n':
1323           ds_put_byte (st, c);
1324           return true;
1325
1326         case '\r':
1327           c = getc (stream);
1328           if (c == '\n')
1329             {
1330               /* CR followed by LF is special: translate to \n. */
1331               ds_put_byte (st, '\n');
1332               return true;
1333             }
1334           else
1335             {
1336               /* CR followed by anything else is just CR. */
1337               ds_put_byte (st, '\r');
1338               if (c == EOF)
1339                 return true;
1340               ungetc (c, stream);
1341             }
1342           break;
1343
1344         default:
1345           ds_put_byte (st, c);
1346         }
1347     }
1348
1349   return length > 0;
1350 }
1351
1352 /* Removes a comment introduced by `#' from ST,
1353    ignoring occurrences inside quoted strings. */
1354 static void
1355 remove_comment (struct string *st)
1356 {
1357   char *cp;
1358   int quote = 0;
1359
1360   for (cp = ds_data (st); cp < ds_end (st); cp++)
1361     if (quote)
1362       {
1363         if (*cp == quote)
1364           quote = 0;
1365         else if (*cp == '\\')
1366           cp++;
1367       }
1368     else if (*cp == '\'' || *cp == '"')
1369       quote = *cp;
1370     else if (*cp == '#')
1371       {
1372         ds_truncate (st, cp - ds_cstr (st));
1373         break;
1374       }
1375 }
1376
1377 /* Reads a line from STREAM into ST, then preprocesses as follows:
1378
1379    - Splices lines terminated with `\'.
1380
1381    - Deletes comments introduced by `#' outside of single or double
1382      quotes.
1383
1384    - Deletes trailing white space.
1385
1386    Returns true if a line was successfully read, false on
1387    failure.  If LINE_NUMBER is non-null, then *LINE_NUMBER is
1388    incremented by the number of lines read. */
1389 bool
1390 ds_read_config_line (struct string *st, int *line_number, FILE *stream)
1391 {
1392   ds_clear (st);
1393   do
1394     {
1395       if (!ds_read_line (st, stream, SIZE_MAX))
1396         return false;
1397       (*line_number)++;
1398       ds_rtrim (st, ss_cstr (CC_SPACES));
1399     }
1400   while (ds_chomp_byte (st, '\\'));
1401
1402   remove_comment (st);
1403   return true;
1404 }
1405
1406 /* Attempts to read SIZE * CNT bytes from STREAM and append them
1407    to ST.
1408    Returns true if all the requested data was read, false otherwise. */
1409 bool
1410 ds_read_stream (struct string *st, size_t size, size_t cnt, FILE *stream)
1411 {
1412   if (size != 0)
1413     {
1414       size_t try_bytes = xtimes (cnt, size);
1415       if (size_in_bounds_p (xsum (ds_length (st), try_bytes)))
1416         {
1417           char *buffer = ds_put_uninit (st, try_bytes);
1418           size_t got_bytes = fread (buffer, 1, try_bytes, stream);
1419           ds_truncate (st, ds_length (st) - (try_bytes - got_bytes));
1420           return got_bytes == try_bytes;
1421         }
1422       else
1423         {
1424           errno = ENOMEM;
1425           return false;
1426         }
1427     }
1428   else
1429     return true;
1430 }
1431
1432 /* Concatenates S onto ST. */
1433 void
1434 ds_put_cstr (struct string *st, const char *s)
1435 {
1436   if (s != NULL)
1437     ds_put_substring (st, ss_cstr (s));
1438 }
1439
1440 /* Concatenates SS to ST. */
1441 void
1442 ds_put_substring (struct string *st, struct substring ss)
1443 {
1444   memcpy (ds_put_uninit (st, ss_length (ss)), ss_data (ss), ss_length (ss));
1445 }
1446
1447 /* Returns ds_end(ST) and THEN increases the length by INCR. */
1448 char *
1449 ds_put_uninit (struct string *st, size_t incr)
1450 {
1451   char *end;
1452   ds_extend (st, ds_length (st) + incr);
1453   end = ds_end (st);
1454   st->ss.length += incr;
1455   return end;
1456 }
1457
1458 /* Formats FORMAT as a printf string and appends the result to ST. */
1459 void
1460 ds_put_format (struct string *st, const char *format, ...)
1461 {
1462   va_list args;
1463
1464   va_start (args, format);
1465   ds_put_vformat (st, format, args);
1466   va_end (args);
1467 }
1468
1469 /* Formats FORMAT as a printf string and appends the result to ST. */
1470 void
1471 ds_put_vformat (struct string *st, const char *format, va_list args_)
1472 {
1473   int avail, needed;
1474   va_list args;
1475
1476   va_copy (args, args_);
1477   avail = st->ss.string != NULL ? st->capacity - st->ss.length + 1 : 0;
1478   needed = vsnprintf (st->ss.string + st->ss.length, avail, format, args);
1479   va_end (args);
1480
1481   if (needed >= avail)
1482     {
1483       va_copy (args, args_);
1484       vsprintf (ds_put_uninit (st, needed), format, args);
1485       va_end (args);
1486     }
1487   else
1488     {
1489       /* Some old libc's returned -1 when the destination string
1490          was too short. */
1491       while (needed == -1)
1492         {
1493           ds_extend (st, (st->capacity + 1) * 2);
1494           avail = st->capacity - st->ss.length + 1;
1495
1496           va_copy (args, args_);
1497           needed = vsnprintf (ds_end (st), avail, format, args);
1498           va_end (args);
1499         }
1500       st->ss.length += needed;
1501     }
1502 }
1503
1504 /* Appends byte CH to ST. */
1505 void
1506 ds_put_byte (struct string *st, int ch)
1507 {
1508   ds_put_uninit (st, 1)[0] = ch;
1509 }
1510
1511 /* Appends CNT copies of byte CH to ST. */
1512 void
1513 ds_put_byte_multiple (struct string *st, int ch, size_t cnt)
1514 {
1515   memset (ds_put_uninit (st, cnt), ch, cnt);
1516 }
1517
1518
1519 /* If relocation has been enabled, replace ST,
1520    with its relocated version */
1521 void
1522 ds_relocate (struct string *st)
1523 {
1524   const char *orig = ds_cstr (st);
1525   const char *rel = relocate (orig);
1526
1527   if ( orig != rel)
1528     {
1529       ds_clear (st);
1530       ds_put_cstr (st, rel);
1531       /* The documentation for relocate says that casting away const
1532         and then freeing is appropriate ... */
1533       free (CONST_CAST (char *, rel));
1534     }
1535 }
1536
1537
1538 \f
1539
1540 /* Operations on uint8_t "strings" */
1541
1542 /* Copies buffer SRC, of SRC_SIZE bytes, to DST, of DST_SIZE bytes.
1543    DST is truncated to DST_SIZE bytes or padded on the right with
1544    copies of PAD as needed. */
1545 void
1546 u8_buf_copy_rpad (uint8_t *dst, size_t dst_size,
1547                   const uint8_t *src, size_t src_size,
1548                   char pad)
1549 {
1550   if (src_size >= dst_size)
1551     memmove (dst, src, dst_size);
1552   else
1553     {
1554       memmove (dst, src, src_size);
1555       memset (&dst[src_size], pad, dst_size - src_size);
1556     }
1557 }