1 /* PSPP - a program for statistical analysis.
2 Copyright (C) 1997-9, 2000, 2006, 2009, 2010 Free Software Foundation, Inc.
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.
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.
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/>. */
27 #include "libpspp/cast.h"
28 #include "libpspp/message.h"
29 #include "libpspp/pool.h"
31 #include "gl/relocatable.h"
32 #include "gl/minmax.h"
33 #include "gl/xalloc.h"
34 #include "gl/xmemdup0.h"
37 /* Reverses the order of NBYTES bytes at address P, thus converting
38 between little- and big-endian byte orders. */
40 buf_reverse (char *p, size_t nbytes)
42 char *h = p, *t = &h[nbytes - 1];
54 /* Compares the SIZE bytes in A to those in B, disregarding case,
55 and returns a strcmp()-type result. */
57 buf_compare_case (const char *a_, const char *b_, size_t size)
59 const unsigned char *a = (unsigned char *) a_;
60 const unsigned char *b = (unsigned char *) b_;
64 unsigned char ac = toupper (*a++);
65 unsigned char bc = toupper (*b++);
68 return ac > bc ? 1 : -1;
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
78 buf_compare_rpad (const char *a, size_t a_len, const char *b, size_t b_len)
83 min_len = a_len < b_len ? a_len : b_len;
84 result = memcmp (a, b, min_len);
93 for (idx = min_len; idx < b_len; idx++)
95 return ' ' > b[idx] ? 1 : -1;
99 for (idx = min_len; idx < a_len; idx++)
101 return a[idx] > ' ' ? 1 : -1;
107 /* Compares strin A to string B. The shorter string is
108 considered to be padded with spaces to the length of the
111 str_compare_rpad (const char *a, const char *b)
113 return buf_compare_rpad (a, strlen (a), b, strlen (b));
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. */
120 buf_copy_str_rpad (char *dst, size_t dst_size, const char *src, char pad)
122 size_t src_len = strlen (src);
123 if (src_len >= dst_size)
124 memcpy (dst, src, dst_size);
127 memcpy (dst, src, src_len);
128 memset (&dst[src_len], pad, dst_size - src_len);
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. */
136 buf_copy_str_lpad (char *dst, size_t dst_size, const char *src, char pad)
138 size_t src_len = strlen (src);
139 if (src_len >= dst_size)
140 memcpy (dst, src, dst_size);
143 size_t pad_cnt = dst_size - src_len;
144 memset (&dst[0], pad, pad_cnt);
145 memcpy (dst + pad_cnt, src, src_len);
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. */
153 buf_copy_lpad (char *dst, size_t dst_size,
154 const char *src, size_t src_size,
157 if (src_size >= dst_size)
158 memmove (dst, src, dst_size);
161 memset (dst, pad, dst_size - src_size);
162 memmove (&dst[dst_size - src_size], src, src_size);
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. */
170 buf_copy_rpad (char *dst, size_t dst_size,
171 const char *src, size_t src_size,
174 if (src_size >= dst_size)
175 memmove (dst, src, dst_size);
178 memmove (dst, src, src_size);
179 memset (&dst[src_size], pad, dst_size - src_size);
183 /* Copies string SRC to string DST, which is in a buffer DST_SIZE
185 Truncates DST to DST_SIZE - 1 bytes or right-pads with
186 spaces to DST_SIZE - 1 bytes if necessary. */
188 str_copy_rpad (char *dst, size_t dst_size, const char *src)
192 size_t src_len = strlen (src);
193 if (src_len < dst_size - 1)
195 memcpy (dst, src, src_len);
196 memset (&dst[src_len], ' ', dst_size - 1 - src_len);
199 memcpy (dst, src, dst_size - 1);
200 dst[dst_size - 1] = 0;
204 /* Copies SRC to DST, which is in a buffer DST_SIZE bytes long.
205 Truncates DST to DST_SIZE - 1 bytes, if necessary. */
207 str_copy_trunc (char *dst, size_t dst_size, const char *src)
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);
215 memcpy (dst, src, dst_size - 1);
216 dst[dst_size - 1] = '\0';
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. */
224 str_copy_buf_trunc (char *dst, size_t dst_size,
225 const char *src, size_t src_size)
228 assert (dst_size > 0);
230 dst_len = src_size < dst_size ? src_size : dst_size - 1;
231 memcpy (dst, src, dst_len);
235 /* Converts each byte in S to uppercase. */
237 str_uppercase (char *s)
239 for (; *s != '\0'; s++)
240 *s = toupper ((unsigned char) *s);
243 /* Converts each byte in S to lowercase. */
245 str_lowercase (char *s)
247 for (; *s != '\0'; s++)
248 *s = tolower ((unsigned char) *s);
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
256 26-adic notation is "spreadsheet column numbering": 1 = A, 2 =
257 B, 3 = C, ... 26 = Z, 27 = AA, 28 = AB, 29 = AC, ...
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. */
266 str_format_26adic (unsigned long int number, char buffer[], size_t size)
274 buffer[length++] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[number % 26];
280 buffer[length] = '\0';
282 buf_reverse (buffer, length);
286 /* Sets the SIZE bytes starting at BLOCK to C,
287 and returns the byte following BLOCK. */
289 mempset (void *block, int c, size_t size)
291 memset (block, c, size);
292 return (char *) block + size;
297 /* Returns a substring whose contents are the CNT bytes
298 starting at the (0-based) position START in SS. */
300 ss_substr (struct substring ss, size_t start, size_t cnt)
302 if (start < ss.length)
303 return ss_buffer (ss.string + start, MIN (cnt, ss.length - start));
305 return ss_buffer (ss.string + ss.length, 0);
308 /* Returns a substring whose contents are the first CNT
311 ss_head (struct substring ss, size_t cnt)
313 return ss_buffer (ss.string, MIN (cnt, ss.length));
316 /* Returns a substring whose contents are the last CNT bytes
319 ss_tail (struct substring ss, size_t cnt)
322 return ss_buffer (ss.string + (ss.length - cnt), cnt);
327 /* Makes a malloc()'d, null-terminated copy of the contents of OLD
328 and stores it in NEW. */
330 ss_alloc_substring (struct substring *new, struct substring old)
332 new->string = xmemdup0 (old.string, old.length);
333 new->length = old.length;
336 /* Allocates room for a CNT-byte string in NEW. */
338 ss_alloc_uninit (struct substring *new, size_t cnt)
340 new->string = xmalloc (cnt);
344 /* Makes a pool_alloc_unaligned()'d copy of the contents of OLD
345 in POOL, and stores it in NEW. */
347 ss_alloc_substring_pool (struct substring *new, struct substring old,
350 new->string = pool_alloc_unaligned (pool, old.length);
351 new->length = old.length;
352 memcpy (new->string, old.string, old.length);
355 /* Allocates room for a CNT-byte string in NEW in POOL. */
357 ss_alloc_uninit_pool (struct substring *new, size_t cnt, struct pool *pool)
359 new->string = pool_alloc_unaligned (pool, cnt);
363 /* Frees the string that SS points to. */
365 ss_dealloc (struct substring *ss)
370 /* Truncates SS to at most CNT bytes in length. */
372 ss_truncate (struct substring *ss, size_t cnt)
374 if (ss->length > cnt)
378 /* Removes trailing bytes in TRIM_SET from SS.
379 Returns number of bytes removed. */
381 ss_rtrim (struct substring *ss, struct substring trim_set)
384 while (cnt < ss->length
385 && ss_find_byte (trim_set,
386 ss->string[ss->length - cnt - 1]) != SIZE_MAX)
392 /* Removes leading bytes in TRIM_SET from SS.
393 Returns number of bytes removed. */
395 ss_ltrim (struct substring *ss, struct substring trim_set)
397 size_t cnt = ss_span (*ss, trim_set);
398 ss_advance (ss, cnt);
402 /* Trims leading and trailing bytes in TRIM_SET from SS. */
404 ss_trim (struct substring *ss, struct substring trim_set)
406 ss_ltrim (ss, trim_set);
407 ss_rtrim (ss, trim_set);
410 /* If the last byte in SS is C, removes it and returns true.
411 Otherwise, returns false without changing the string. */
413 ss_chomp (struct substring *ss, char c)
415 if (ss_last (*ss) == c)
424 /* Divides SS into tokens separated by any of the DELIMITERS.
425 Each call replaces TOKEN by the next token in SS, or by an
426 empty string if no tokens remain. Returns true if a token was
427 obtained, false otherwise.
429 Before the first call, initialize *SAVE_IDX to 0. Do not
430 modify *SAVE_IDX between calls.
432 SS divides into exactly one more tokens than it contains
433 delimiters. That is, a delimiter at the start or end of SS or
434 a pair of adjacent delimiters yields an empty token, and the
435 empty string contains a single token. */
437 ss_separate (struct substring ss, struct substring delimiters,
438 size_t *save_idx, struct substring *token)
440 if (*save_idx <= ss_length (ss))
442 struct substring tmp = ss_substr (ss, *save_idx, SIZE_MAX);
443 size_t length = ss_cspan (tmp, delimiters);
444 *token = ss_head (tmp, length);
445 *save_idx += length + 1;
450 *token = ss_empty ();
455 /* Divides SS into tokens separated by any of the DELIMITERS,
456 merging adjacent delimiters so that the empty string is never
457 produced as a token. Each call replaces TOKEN by the next
458 token in SS, or by an empty string if no tokens remain, and
459 then skips past the first delimiter following the token.
460 Returns true if a token was obtained, false otherwise.
462 Before the first call, initialize *SAVE_IDX to 0. Do not
463 modify *SAVE_IDX between calls. */
465 ss_tokenize (struct substring ss, struct substring delimiters,
466 size_t *save_idx, struct substring *token)
468 ss_advance (&ss, *save_idx);
469 *save_idx += ss_ltrim (&ss, delimiters);
470 ss_get_bytes (&ss, ss_cspan (ss, delimiters), token);
471 *save_idx += ss_length (*token) + 1;
472 return ss_length (*token) > 0;
475 /* Removes the first CNT bytes from SS. */
477 ss_advance (struct substring *ss, size_t cnt)
479 if (cnt > ss->length)
485 /* If the first byte in SS is C, removes it and returns true.
486 Otherwise, returns false without changing the string. */
488 ss_match_byte (struct substring *ss, char c)
490 if (ss_first (*ss) == c)
500 /* If the first byte in SS is in MATCH, removes it and
501 returns the byte that was removed.
502 Otherwise, returns EOF without changing the string. */
504 ss_match_byte_in (struct substring *ss, struct substring match)
508 && memchr (match.string, ss->string[0], match.length) != NULL)
517 /* If SS begins with TARGET, removes it and returns true.
518 Otherwise, returns false without changing SS. */
520 ss_match_string (struct substring *ss, const struct substring target)
522 size_t length = ss_length (target);
523 if (ss_equals (ss_head (*ss, length), target))
525 ss_advance (ss, length);
532 /* Removes the first byte from SS and returns it.
533 If SS is empty, returns EOF without modifying SS. */
535 ss_get_byte (struct substring *ss)
537 int c = ss_first (*ss);
546 /* Stores the prefix of SS up to the first DELIMITER in OUT (if
547 any). Trims those same bytes from SS. DELIMITER is
548 removed from SS but not made part of OUT. Returns true if
549 DELIMITER was found (and removed), false otherwise. */
551 ss_get_until (struct substring *ss, char delimiter, struct substring *out)
553 ss_get_bytes (ss, ss_cspan (*ss, ss_buffer (&delimiter, 1)), out);
554 return ss_match_byte (ss, delimiter);
557 /* Stores the first CNT bytes in SS in OUT (or fewer, if SS
558 is shorter than CNT bytes). Trims the same bytes
559 from the beginning of SS. Returns CNT. */
561 ss_get_bytes (struct substring *ss, size_t cnt, struct substring *out)
563 *out = ss_head (*ss, cnt);
564 ss_advance (ss, cnt);
568 /* Parses and removes an optionally signed decimal integer from
569 the beginning of SS. Returns 0 if an error occurred,
570 otherwise the number of bytes removed from SS. Stores
571 the integer's value into *VALUE. */
573 ss_get_long (struct substring *ss, long *value)
578 length = ss_span (*ss, ss_cstr ("+-"));
579 length += ss_span (ss_substr (*ss, length, SIZE_MAX), ss_cstr (CC_DIGITS));
580 if (length > 0 && length < sizeof tmp)
584 memcpy (tmp, ss_data (*ss), length);
587 *value = strtol (tmp, &tail, 10);
588 if (tail - tmp == length)
590 ss_advance (ss, length);
598 /* Returns true if SS is empty (has length 0 bytes),
601 ss_is_empty (struct substring ss)
603 return ss.length == 0;
606 /* Returns the number of bytes in SS. */
608 ss_length (struct substring ss)
613 /* Returns a pointer to the bytes in SS. */
615 ss_data (struct substring ss)
620 /* Returns a pointer just past the last byte in SS. */
622 ss_end (struct substring ss)
624 return ss.string + ss.length;
627 /* Returns the byte in position IDX in SS, as a value in the
628 range of unsigned char. Returns EOF if IDX is out of the
629 range of indexes for SS. */
631 ss_at (struct substring ss, size_t idx)
633 return idx < ss.length ? (unsigned char) ss.string[idx] : EOF;
636 /* Returns the first byte in SS as a value in the range of
637 unsigned char. Returns EOF if SS is the empty string. */
639 ss_first (struct substring ss)
641 return ss_at (ss, 0);
644 /* Returns the last byte in SS as a value in the range of
645 unsigned char. Returns EOF if SS is the empty string. */
647 ss_last (struct substring ss)
649 return ss.length > 0 ? (unsigned char) ss.string[ss.length - 1] : EOF;
652 /* Returns the number of contiguous bytes at the beginning
653 of SS that are in SKIP_SET. */
655 ss_span (struct substring ss, struct substring skip_set)
658 for (i = 0; i < ss.length; i++)
659 if (ss_find_byte (skip_set, ss.string[i]) == SIZE_MAX)
664 /* Returns the number of contiguous bytes at the beginning
665 of SS that are not in SKIP_SET. */
667 ss_cspan (struct substring ss, struct substring stop_set)
670 for (i = 0; i < ss.length; i++)
671 if (ss_find_byte (stop_set, ss.string[i]) != SIZE_MAX)
676 /* Returns the offset in SS of the first instance of C,
677 or SIZE_MAX if C does not occur in SS. */
679 ss_find_byte (struct substring ss, char c)
681 const char *p = memchr (ss.string, c, ss.length);
682 return p != NULL ? p - ss.string : SIZE_MAX;
685 /* Compares A and B and returns a strcmp()-type comparison
688 ss_compare (struct substring a, struct substring b)
690 int retval = memcmp (a.string, b.string, MIN (a.length, b.length));
692 retval = a.length < b.length ? -1 : a.length > b.length;
696 /* Compares A and B case-insensitively and returns a
697 strcmp()-type comparison result. */
699 ss_compare_case (struct substring a, struct substring b)
701 int retval = memcasecmp (a.string, b.string, MIN (a.length, b.length));
703 retval = a.length < b.length ? -1 : a.length > b.length;
707 /* Compares A and B and returns true if their contents are
708 identical, false otherwise. */
710 ss_equals (struct substring a, struct substring b)
712 return a.length == b.length && !memcmp (a.string, b.string, a.length);
715 /* Compares A and B and returns true if their contents are
716 identical except possibly for case differences, false
719 ss_equals_case (struct substring a, struct substring b)
721 return a.length == b.length && !memcasecmp (a.string, b.string, a.length);
724 /* Returns the position in SS that the byte at P occupies.
725 P must point within SS or one past its end. */
727 ss_pointer_to_position (struct substring ss, const char *p)
729 size_t pos = p - ss.string;
730 assert (pos <= ss.length);
734 /* Allocates and returns a null-terminated string that contains
737 ss_xstrdup (struct substring ss)
739 char *s = xmalloc (ss.length + 1);
740 memcpy (s, ss.string, ss.length);
746 /* Returns the character represented by the UTF-8 sequence at the start of S.
747 The return value is either a Unicode code point in the range 0 to 0x10ffff,
748 or UINT32_MAX if S is empty. */
750 ss_first_mb (struct substring s)
752 return ss_at_mb (s, 0);
755 /* Returns the number of bytes in the UTF-8 character at the beginning of S.
757 The return value is 0 if S is empty, otherwise between 1 and 4. */
759 ss_first_mblen (struct substring s)
761 return ss_at_mblen (s, 0);
764 /* Advances S past the UTF-8 character at its beginning. Returns the Unicode
765 code point that was skipped (in the range 0 to 0x10ffff), or UINT32_MAX if S
766 was not modified because it was initially empty. */
768 ss_get_mb (struct substring *s)
775 n = u8_mbtouc (&uc, CHAR_CAST (const uint8_t *, s->string), s->length);
784 /* Returns the character represented by the UTF-8 sequence starting OFS bytes
785 into S. The return value is either a Unicode code point in the range 0 to
786 0x10ffff, or UINT32_MAX if OFS is past the last byte in S.
788 (Returns 0xfffd if OFS points into the middle, not the beginning, of a UTF-8
791 ss_at_mb (struct substring s, size_t ofs)
796 u8_mbtouc (&uc, CHAR_CAST (const uint8_t *, s.string + ofs),
804 /* Returns the number of bytes represented by the UTF-8 sequence starting OFS
805 bytes into S. The return value is 0 if OFS is past the last byte in S,
806 otherwise between 1 and 4. */
808 ss_at_mblen (struct substring s, size_t ofs)
813 return u8_mbtouc (&uc, CHAR_CAST (const uint8_t *, s.string + ofs),
820 /* Initializes ST as an empty string. */
822 ds_init_empty (struct string *st)
824 st->ss = ss_empty ();
828 /* Initializes ST with initial contents S. */
830 ds_init_string (struct string *st, const struct string *s)
832 ds_init_substring (st, ds_ss (s));
835 /* Initializes ST with initial contents SS. */
837 ds_init_substring (struct string *st, struct substring ss)
839 st->capacity = MAX (8, ss.length * 2);
840 st->ss.string = xmalloc (st->capacity + 1);
841 memcpy (st->ss.string, ss.string, ss.length);
842 st->ss.length = ss.length;
845 /* Initializes ST with initial contents S. */
847 ds_init_cstr (struct string *st, const char *s)
849 ds_init_substring (st, ss_cstr (s));
854 ds_destroy (struct string *st)
858 ss_dealloc (&st->ss);
859 st->ss.string = NULL;
865 /* Swaps the contents of strings A and B. */
867 ds_swap (struct string *a, struct string *b)
869 struct string tmp = *a;
874 /* Helper function for ds_register_pool. */
876 free_string (void *st_)
878 struct string *st = st_;
882 /* Arranges for ST to be destroyed automatically as part of
885 ds_register_pool (struct string *st, struct pool *pool)
887 pool_register (pool, free_string, st);
890 /* Cancels the arrangement for ST to be destroyed automatically
893 ds_unregister_pool (struct string *st, struct pool *pool)
895 pool_unregister (pool, st);
898 /* Copies SRC into DST.
899 DST and SRC may be the same string. */
901 ds_assign_string (struct string *dst, const struct string *src)
903 ds_assign_substring (dst, ds_ss (src));
906 /* Replaces DST by SS.
907 SS may be a substring of DST. */
909 ds_assign_substring (struct string *dst, struct substring ss)
911 dst->ss.length = ss.length;
912 ds_extend (dst, ss.length);
913 memmove (dst->ss.string, ss.string, ss.length);
916 /* Replaces DST by null-terminated string SRC. SRC may overlap
919 ds_assign_cstr (struct string *dst, const char *src)
921 ds_assign_substring (dst, ss_cstr (src));
924 /* Truncates ST to zero length. */
926 ds_clear (struct string *st)
931 /* Returns a substring that contains ST. */
933 ds_ss (const struct string *st)
938 /* Returns a substring that contains CNT bytes from ST
939 starting at position START.
941 If START is greater than or equal to the length of ST, then
942 the substring will be the empty string. If START + CNT
943 exceeds the length of ST, then the substring will only be
944 ds_length(ST) - START bytes long. */
946 ds_substr (const struct string *st, size_t start, size_t cnt)
948 return ss_substr (ds_ss (st), start, cnt);
951 /* Returns a substring that contains the first CNT bytes in
952 ST. If CNT exceeds the length of ST, then the substring will
953 contain all of ST. */
955 ds_head (const struct string *st, size_t cnt)
957 return ss_head (ds_ss (st), cnt);
960 /* Returns a substring that contains the last CNT bytes in
961 ST. If CNT exceeds the length of ST, then the substring will
962 contain all of ST. */
964 ds_tail (const struct string *st, size_t cnt)
966 return ss_tail (ds_ss (st), cnt);
969 /* Ensures that ST can hold at least MIN_CAPACITY bytes plus a null
972 ds_extend (struct string *st, size_t min_capacity)
974 if (min_capacity > st->capacity)
977 if (st->capacity < min_capacity)
978 st->capacity = 2 * min_capacity;
980 st->ss.string = xrealloc (st->ss.string, st->capacity + 1);
984 /* Shrink ST to the minimum capacity need to contain its content. */
986 ds_shrink (struct string *st)
988 if (st->capacity != st->ss.length)
990 st->capacity = st->ss.length;
991 st->ss.string = xrealloc (st->ss.string, st->capacity + 1);
995 /* Truncates ST to at most LENGTH bytes long. */
997 ds_truncate (struct string *st, size_t length)
999 ss_truncate (&st->ss, length);
1002 /* Removes trailing bytes in TRIM_SET from ST.
1003 Returns number of bytes removed. */
1005 ds_rtrim (struct string *st, struct substring trim_set)
1007 return ss_rtrim (&st->ss, trim_set);
1010 /* Removes leading bytes in TRIM_SET from ST.
1011 Returns number of bytes removed. */
1013 ds_ltrim (struct string *st, struct substring trim_set)
1015 size_t cnt = ds_span (st, trim_set);
1017 ds_assign_substring (st, ds_substr (st, cnt, SIZE_MAX));
1021 /* Trims leading and trailing bytes in TRIM_SET from ST.
1022 Returns number of bytes removed. */
1024 ds_trim (struct string *st, struct substring trim_set)
1026 size_t cnt = ds_rtrim (st, trim_set);
1027 return cnt + ds_ltrim (st, trim_set);
1030 /* If the last byte in ST is C, removes it and returns true.
1031 Otherwise, returns false without modifying ST. */
1033 ds_chomp (struct string *st, char c)
1035 return ss_chomp (&st->ss, c);
1038 /* Divides ST into tokens separated by any of the DELIMITERS.
1039 Each call replaces TOKEN by the next token in ST, or by an
1040 empty string if no tokens remain. Returns true if a token was
1041 obtained, false otherwise.
1043 Before the first call, initialize *SAVE_IDX to 0. Do not
1044 modify *SAVE_IDX between calls.
1046 ST divides into exactly one more tokens than it contains
1047 delimiters. That is, a delimiter at the start or end of ST or
1048 a pair of adjacent delimiters yields an empty token, and the
1049 empty string contains a single token. */
1051 ds_separate (const struct string *st, struct substring delimiters,
1052 size_t *save_idx, struct substring *token)
1054 return ss_separate (ds_ss (st), delimiters, save_idx, token);
1057 /* Divides ST into tokens separated by any of the DELIMITERS,
1058 merging adjacent delimiters so that the empty string is never
1059 produced as a token. Each call replaces TOKEN by the next
1060 token in ST, or by an empty string if no tokens remain.
1061 Returns true if a token was obtained, false otherwise.
1063 Before the first call, initialize *SAVE_IDX to 0. Do not
1064 modify *SAVE_IDX between calls. */
1066 ds_tokenize (const struct string *st, struct substring delimiters,
1067 size_t *save_idx, struct substring *token)
1069 return ss_tokenize (ds_ss (st), delimiters, save_idx, token);
1072 /* Pad ST on the right with copies of PAD until ST is at least
1073 LENGTH bytes in size. If ST is initially LENGTH
1074 bytes or longer, this is a no-op. */
1076 ds_rpad (struct string *st, size_t length, char pad)
1078 if (length > st->ss.length)
1079 ds_put_byte_multiple (st, pad, length - st->ss.length);
1082 /* Sets the length of ST to exactly NEW_LENGTH,
1083 either by truncating bytes from the end,
1084 or by padding on the right with PAD. */
1086 ds_set_length (struct string *st, size_t new_length, char pad)
1088 if (st->ss.length < new_length)
1089 ds_rpad (st, new_length, pad);
1091 st->ss.length = new_length;
1094 /* Removes N bytes from ST starting at offset START. */
1096 ds_remove (struct string *st, size_t start, size_t n)
1098 if (n > 0 && start < st->ss.length)
1100 if (st->ss.length - start <= n)
1102 /* All bytes at or beyond START are deleted. */
1103 st->ss.length = start;
1107 /* Some bytes remain and must be shifted into
1109 memmove (st->ss.string + st->ss.length,
1110 st->ss.string + st->ss.length + n,
1111 st->ss.length - start - n);
1117 /* There are no bytes to delete or no bytes at or
1118 beyond START, hence deletion is a no-op. */
1122 /* Returns true if ST is empty, false otherwise. */
1124 ds_is_empty (const struct string *st)
1126 return ss_is_empty (st->ss);
1129 /* Returns the length of ST. */
1131 ds_length (const struct string *st)
1133 return ss_length (ds_ss (st));
1136 /* Returns the string data inside ST. */
1138 ds_data (const struct string *st)
1140 return ss_data (ds_ss (st));
1143 /* Returns a pointer to the null terminator ST.
1144 This might not be an actual null byte unless ds_c_str() has
1145 been called since the last modification to ST. */
1147 ds_end (const struct string *st)
1149 return ss_end (ds_ss (st));
1152 /* Returns the byte in position IDX in ST, as a value in the
1153 range of unsigned char. Returns EOF if IDX is out of the
1154 range of indexes for ST. */
1156 ds_at (const struct string *st, size_t idx)
1158 return ss_at (ds_ss (st), idx);
1161 /* Returns the first byte in ST as a value in the range of
1162 unsigned char. Returns EOF if ST is the empty string. */
1164 ds_first (const struct string *st)
1166 return ss_first (ds_ss (st));
1169 /* Returns the last byte in ST as a value in the range of
1170 unsigned char. Returns EOF if ST is the empty string. */
1172 ds_last (const struct string *st)
1174 return ss_last (ds_ss (st));
1177 /* Returns the number of consecutive bytes at the beginning
1178 of ST that are in SKIP_SET. */
1180 ds_span (const struct string *st, struct substring skip_set)
1182 return ss_span (ds_ss (st), skip_set);
1185 /* Returns the number of consecutive bytes at the beginning
1186 of ST that are not in STOP_SET. */
1188 ds_cspan (const struct string *st, struct substring stop_set)
1190 return ss_cspan (ds_ss (st), stop_set);
1193 /* Returns the position of the first occurrence of byte C in
1194 ST at or after position OFS, or SIZE_MAX if there is no such
1197 ds_find_byte (const struct string *st, char c)
1199 return ss_find_byte (ds_ss (st), c);
1202 /* Compares A and B and returns a strcmp()-type comparison
1205 ds_compare (const struct string *a, const struct string *b)
1207 return ss_compare (ds_ss (a), ds_ss (b));
1210 /* Returns the position in ST that the byte at P occupies.
1211 P must point within ST or one past its end. */
1213 ds_pointer_to_position (const struct string *st, const char *p)
1215 return ss_pointer_to_position (ds_ss (st), p);
1218 /* Allocates and returns a null-terminated string that contains
1221 ds_xstrdup (const struct string *st)
1223 return ss_xstrdup (ds_ss (st));
1226 /* Returns the allocation size of ST. */
1228 ds_capacity (const struct string *st)
1230 return st->capacity;
1233 /* Returns the value of ST as a null-terminated string. */
1235 ds_cstr (const struct string *st_)
1237 struct string *st = CONST_CAST (struct string *, st_);
1238 if (st->ss.string == NULL)
1240 st->ss.string[st->ss.length] = '\0';
1241 return st->ss.string;
1244 /* Returns the value of ST as a null-terminated string and then
1245 reinitialized ST as an empty string. The caller must free the
1246 returned string with free(). */
1248 ds_steal_cstr (struct string *st)
1250 char *s = ds_cstr (st);
1255 /* Reads bytes from STREAM and appends them to ST, stopping
1256 after MAX_LENGTH bytes, after appending a newline, or
1257 after an I/O error or end of file was encountered, whichever
1258 comes first. Returns true if at least one byte was added
1259 to ST, false if no bytes were read before an I/O error or
1260 end of file (or if MAX_LENGTH was 0).
1262 This function treats LF and CR LF sequences as new-line,
1263 translating each of them to a single '\n' in ST. */
1265 ds_read_line (struct string *st, FILE *stream, size_t max_length)
1269 for (length = 0; length < max_length; length++)
1271 int c = getc (stream);
1278 ds_put_byte (st, c);
1285 /* CR followed by LF is special: translate to \n. */
1286 ds_put_byte (st, '\n');
1291 /* CR followed by anything else is just CR. */
1292 ds_put_byte (st, '\r');
1300 ds_put_byte (st, c);
1307 /* Removes a comment introduced by `#' from ST,
1308 ignoring occurrences inside quoted strings. */
1310 remove_comment (struct string *st)
1315 for (cp = ds_data (st); cp < ds_end (st); cp++)
1320 else if (*cp == '\\')
1323 else if (*cp == '\'' || *cp == '"')
1325 else if (*cp == '#')
1327 ds_truncate (st, cp - ds_cstr (st));
1332 /* Reads a line from STREAM into ST, then preprocesses as follows:
1334 - Splices lines terminated with `\'.
1336 - Deletes comments introduced by `#' outside of single or double
1339 - Deletes trailing white space.
1341 Returns true if a line was successfully read, false on
1342 failure. If LINE_NUMBER is non-null, then *LINE_NUMBER is
1343 incremented by the number of lines read. */
1345 ds_read_config_line (struct string *st, int *line_number, FILE *stream)
1350 if (!ds_read_line (st, stream, SIZE_MAX))
1353 ds_rtrim (st, ss_cstr (CC_SPACES));
1355 while (ds_chomp (st, '\\'));
1357 remove_comment (st);
1361 /* Attempts to read SIZE * CNT bytes from STREAM and append them
1363 Returns true if all the requested data was read, false otherwise. */
1365 ds_read_stream (struct string *st, size_t size, size_t cnt, FILE *stream)
1369 size_t try_bytes = xtimes (cnt, size);
1370 if (size_in_bounds_p (xsum (ds_length (st), try_bytes)))
1372 char *buffer = ds_put_uninit (st, try_bytes);
1373 size_t got_bytes = fread (buffer, 1, try_bytes, stream);
1374 ds_truncate (st, ds_length (st) - (try_bytes - got_bytes));
1375 return got_bytes == try_bytes;
1387 /* Concatenates S onto ST. */
1389 ds_put_cstr (struct string *st, const char *s)
1392 ds_put_substring (st, ss_cstr (s));
1395 /* Concatenates SS to ST. */
1397 ds_put_substring (struct string *st, struct substring ss)
1399 memcpy (ds_put_uninit (st, ss_length (ss)), ss_data (ss), ss_length (ss));
1402 /* Returns ds_end(ST) and THEN increases the length by INCR. */
1404 ds_put_uninit (struct string *st, size_t incr)
1407 ds_extend (st, ds_length (st) + incr);
1409 st->ss.length += incr;
1413 /* Formats FORMAT as a printf string and appends the result to ST. */
1415 ds_put_format (struct string *st, const char *format, ...)
1419 va_start (args, format);
1420 ds_put_vformat (st, format, args);
1424 /* Formats FORMAT as a printf string and appends the result to ST. */
1426 ds_put_vformat (struct string *st, const char *format, va_list args_)
1431 va_copy (args, args_);
1432 avail = st->ss.string != NULL ? st->capacity - st->ss.length + 1 : 0;
1433 needed = vsnprintf (st->ss.string + st->ss.length, avail, format, args);
1436 if (needed >= avail)
1438 va_copy (args, args_);
1439 vsprintf (ds_put_uninit (st, needed), format, args);
1444 /* Some old libc's returned -1 when the destination string
1446 while (needed == -1)
1448 ds_extend (st, (st->capacity + 1) * 2);
1449 avail = st->capacity - st->ss.length + 1;
1451 va_copy (args, args_);
1452 needed = vsnprintf (ds_end (st), avail, format, args);
1455 st->ss.length += needed;
1459 /* Appends byte CH to ST. */
1461 ds_put_byte (struct string *st, int ch)
1463 ds_put_uninit (st, 1)[0] = ch;
1466 /* Appends CNT copies of byte CH to ST. */
1468 ds_put_byte_multiple (struct string *st, int ch, size_t cnt)
1470 memset (ds_put_uninit (st, cnt), ch, cnt);
1474 /* If relocation has been enabled, replace ST,
1475 with its relocated version */
1477 ds_relocate (struct string *st)
1479 const char *orig = ds_cstr (st);
1480 const char *rel = relocate (orig);
1485 ds_put_cstr (st, rel);
1486 /* The documentation for relocate says that casting away const
1487 and then freeing is appropriate ... */
1488 free (CONST_CAST (char *, rel));
1495 /* Operations on uint8_t "strings" */
1497 /* Copies buffer SRC, of SRC_SIZE bytes, to DST, of DST_SIZE bytes.
1498 DST is truncated to DST_SIZE bytes or padded on the right with
1499 copies of PAD as needed. */
1501 u8_buf_copy_rpad (uint8_t *dst, size_t dst_size,
1502 const uint8_t *src, size_t src_size,
1505 if (src_size >= dst_size)
1506 memmove (dst, src, dst_size);
1509 memmove (dst, src, src_size);
1510 memset (&dst[src_size], pad, dst_size - src_size);