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