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