0ad0e2f5899647d7b923afd1fe59e9d7f8ec6bef
[pspp-builds.git] / src / str.c
1 /* PSPP - computes sample statistics.
2    Copyright (C) 1997-9, 2000 Free Software Foundation, Inc.
3    Written by Ben Pfaff <blp@gnu.org>.
4
5    This program is free software; you can redistribute it and/or
6    modify it under the terms of the GNU General Public License as
7    published by the Free Software Foundation; either version 2 of the
8    License, or (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful, but
11    WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software
17    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
18    02110-1301, USA. */
19
20 #include <config.h>
21 #include "str.h"
22 #include "error.h"
23 #include <ctype.h>
24 #include <limits.h>
25 #include <stdlib.h>
26 #include "alloc.h"
27 #include "error.h"
28 #include "pool.h"
29 \f
30 /* sprintf() wrapper functions for convenience. */
31
32 #if !__GNUC__
33 char *
34 spprintf (char *buf, const char *format,...)
35 {
36 #if HAVE_GOOD_SPRINTF
37   int count;
38 #endif
39   va_list args;
40
41   va_start (args, format);
42 #if HAVE_GOOD_SPRINTF
43   count =
44 #endif
45     vsprintf (buf, format, args);
46   va_end (args);
47
48 #if HAVE_GOOD_SPRINTF
49   return &buf[count];
50 #else
51   return strchr (buf, 0);
52 #endif
53 }
54 #endif /* !__GNUC__ */
55
56 #if !__GNUC__ && !HAVE_GOOD_SPRINTF
57 int
58 nsprintf (char *buf, const char *format,...)
59 {
60   va_list args;
61
62   va_start (args, format);
63   vsprintf (buf, format, args);
64   va_end (args);
65
66   return strlen (buf);
67 }
68
69 int
70 nvsprintf (char *buf, const char *format, va_list args)
71 {
72   vsprintf (buf, format, args);
73   return strlen (buf);
74 }
75 #endif /* Not GNU C and not good sprintf(). */
76 \f
77 /* Reverses the order of NBYTES bytes at address P, thus converting
78    between little- and big-endian byte orders.  */
79 void
80 mm_reverse (void *p, size_t nbytes)
81 {
82   unsigned char *h = p, *t = &h[nbytes - 1];
83   unsigned char temp;
84
85   nbytes /= 2;
86   while (nbytes--)
87     {
88       temp = *h;
89       *h++ = *t;
90       *t-- = temp;
91     }
92 }
93
94 /* Finds the last NEEDLE of length NEEDLE_LEN in a HAYSTACK of length
95    HAYSTACK_LEN.  Returns a pointer to the needle found. */
96 char *
97 mm_find_reverse (const char *haystack, size_t haystack_len,
98                  const char *needle, size_t needle_len)
99 {
100   int i;
101   for (i = haystack_len - needle_len; i >= 0; i--)
102     if (!memcmp (needle, &haystack[i], needle_len))
103       return (char *) &haystack[i];
104   return 0;
105 }
106
107 /* Compares the SIZE bytes in A to those in B, disregarding case,
108    and returns a strcmp()-type result. */
109 int
110 mm_case_compare (const void *a_, const void *b_, size_t size)
111 {
112   const unsigned char *a = a_;
113   const unsigned char *b = b_;
114
115   while (size-- > 0) 
116     {
117       unsigned char ac = toupper (*a++);
118       unsigned char bc = toupper (*b++);
119
120       if (ac != bc) 
121         return ac > bc ? 1 : -1;
122     }
123
124   return 0;
125 }
126
127 /* Compares A of length A_LEN to B of length B_LEN.  The shorter
128    string is considered to be padded with spaces to the length of
129    the longer. */
130 int
131 st_compare_pad (const char *a, size_t a_len, const char *b, size_t b_len)
132 {
133   size_t min_len;
134   int result;
135
136   min_len = a_len < b_len ? a_len : b_len;
137   result = memcmp (a, b, min_len);
138   if (result != 0)
139     return result;
140   else 
141     {
142       size_t idx;
143       
144       if (a_len < b_len) 
145         {
146           for (idx = min_len; idx < b_len; idx++)
147             if (' ' != b[idx])
148               return ' ' > b[idx] ? 1 : -1;
149         }
150       else 
151         {
152           for (idx = min_len; idx < a_len; idx++)
153             if (a[idx] != ' ')
154               return a[idx] > ' ' ? 1 : -1;
155         }
156       return 0;
157     }
158 }
159
160 /* Copies SRC to DEST, truncating to N characters or right-padding
161    with spaces to N characters as necessary.  Does not append a null
162    character.  SRC must be null-terminated. */
163 void
164 st_bare_pad_copy (char *dest, const char *src, size_t n)
165 {
166   size_t len;
167
168   len = strlen (src);
169   if (len >= n)
170     memcpy (dest, src, n);
171   else
172     {
173       memcpy (dest, src, len);
174       memset (&dest[len], ' ', n - len);
175     }
176 }
177
178 /* Copies SRC to DEST, truncating SRC to N characters or right-padding
179    with spaces to N characters if necessary.  Does not append a null
180    character.  SRC must be LEN characters long but does not need to be
181    null-terminated. */
182 void
183 st_bare_pad_len_copy (char *dest, const char *src, size_t n, size_t len)
184 {
185   if (len >= n)
186     memmove (dest, src, n);
187   else
188     {
189       memmove (dest, src, len);
190       memset (&dest[len], ' ', n - len);
191     }
192 }
193
194 /* Copies SRC to DEST, truncating SRC to N-1 characters or
195    right-padding with spaces to N-1 characters if necessary.  Always
196    appends a null character. */
197 void
198 st_pad_copy (char *dest, const char *src, size_t n)
199 {
200   size_t len;
201
202   len = strlen (src);
203   if (len == n - 1)
204     strcpy (dest, src);
205   else if (len < n - 1)
206     {
207       memcpy (dest, src, len);
208       memset (&dest[len], ' ', n - 1 - len);
209       dest[n - 1] = 0;
210     }
211   else
212     {
213       memcpy (dest, src, n - 1);
214       dest[n - 1] = 0;
215     }
216 }
217
218 /* Copies SRC to DST, truncating DST to N-1 characters if
219    necessary.  Always appends a null character. */
220 void
221 st_trim_copy (char *dst, const char *src, size_t n) 
222 {
223   size_t len = strlen (src);
224   assert (n > 0);
225   if (len + 1 < n)
226     memcpy (dst, src, len + 1);
227   else 
228     {
229       memcpy (dst, src, n - 1);
230       dst[n - 1] = '\0';
231     }
232 }
233
234
235 /* Converts each character in S to uppercase. */
236 void
237 st_uppercase (char *s) 
238 {
239   for (; *s != '\0'; s++)
240     *s = toupper ((unsigned char) *s);
241 }
242 \f
243 /* Initializes ST with initial contents S. */
244 void
245 ds_create (struct string *st, const char *s)
246 {
247   st->length = strlen (s);
248   st->capacity = 8 + st->length * 2;
249   st->string = xmalloc (st->capacity + 1);
250   strcpy (st->string, s);
251 }
252
253 /* Initializes ST, making room for at least CAPACITY characters. */
254 void
255 ds_init (struct string *st, size_t capacity)
256 {
257   st->length = 0;
258   if (capacity > 8)
259     st->capacity = capacity;
260   else
261     st->capacity = 8;
262   st->string = xmalloc (st->capacity + 1);
263 }
264
265 /* Replaces the contents of ST with STRING.  STRING may overlap with
266    ST. */
267 void
268 ds_replace (struct string *st, const char *string)
269 {
270   size_t new_length = strlen (string);
271   if (new_length > st->capacity) 
272     {
273       /* The new length is longer than the allocated length, so
274          there can be no overlap. */
275       st->length = 0;
276       ds_concat (st, string, new_length);
277     }
278   else
279     {
280       /* Overlap is possible, but the new string will fit in the
281          allocated space, so we can just copy data. */
282       st->length = new_length;
283       memmove (st->string, string, st->length);
284     }
285 }
286
287 /* Frees ST. */
288 void
289 ds_destroy (struct string *st)
290 {
291   free (st->string);
292 }
293
294 /* Truncates ST to zero length. */
295 void
296 ds_clear (struct string *st)
297 {
298   st->length = 0;
299 }
300
301 /* Pad ST on the right with copies of PAD until ST is at least
302    LENGTH characters in size.  If ST is initially LENGTH
303    characters or longer, this is a no-op. */
304 void
305 ds_rpad (struct string *st, size_t length, char pad) 
306 {
307   assert (st != NULL);
308   if (st->length < length) 
309     {
310       if (st->capacity < length)
311         ds_extend (st, length);
312       memset (&st->string[st->length], pad, length - st->length);
313       st->length = length;
314     }
315 }
316
317 /* Ensures that ST can hold at least MIN_CAPACITY characters plus a null
318    terminator. */
319 void
320 ds_extend (struct string *st, size_t min_capacity)
321 {
322   if (min_capacity > st->capacity)
323     {
324       st->capacity *= 2;
325       if (st->capacity < min_capacity)
326         st->capacity = min_capacity * 2;
327       
328       st->string = xrealloc (st->string, st->capacity + 1);
329     }
330 }
331
332 /* Shrink ST to the minimum capacity need to contain its content. */
333 void
334 ds_shrink (struct string *st)
335 {
336   if (st->capacity != st->length)
337     {
338       st->capacity = st->length;
339       st->string = xrealloc (st->string, st->capacity + 1);
340     }
341 }
342
343 /* Truncates ST to at most LENGTH characters long. */
344 void
345 ds_truncate (struct string *st, size_t length)
346 {
347   if (length >= st->length)
348     return;
349   st->length = length;
350 }
351
352 /* Returns the length of ST. */
353 size_t
354 ds_length (const struct string *st)
355 {
356   return st->length;
357 }
358
359 /* Returns the allocation size of ST. */
360 size_t
361 ds_capacity (const struct string *st)
362 {
363   return st->capacity;
364 }
365
366 /* Returns the value of ST as a null-terminated string. */
367 char *
368 ds_c_str (const struct string *st)
369 {
370   ((char *) st->string)[st->length] = '\0';
371   return st->string;
372 }
373
374 /* Returns the string data inside ST. */
375 char *
376 ds_data (const struct string *st)
377 {
378   return st->string;
379 }
380
381 /* Returns a pointer to the null terminator ST.
382    This might not be an actual null character unless ds_c_str() has
383    been called since the last modification to ST. */
384 char *
385 ds_end (const struct string *st)
386 {
387   return st->string + st->length;
388 }
389
390 /* Concatenates S onto ST. */
391 void
392 ds_puts (struct string *st, const char *s)
393 {
394   size_t s_len;
395
396   if (!s) return;
397
398   s_len = strlen (s);
399   ds_extend (st, st->length + s_len);
400   strcpy (st->string + st->length, s);
401   st->length += s_len;
402 }
403
404 /* Concatenates LEN characters from BUF onto ST. */
405 void
406 ds_concat (struct string *st, const char *buf, size_t len)
407 {
408   ds_extend (st, st->length + len);
409   memcpy (st->string + st->length, buf, len);
410   st->length += len;
411 }
412
413 void ds_vprintf (struct string *st, const char *format, va_list args);
414
415
416 /* Formats FORMAT as a printf string and appends the result to ST. */
417 void
418 ds_printf (struct string *st, const char *format, ...)
419 {
420   va_list args;
421
422   va_start (args, format);
423   ds_vprintf(st,format,args);
424   va_end (args);
425
426 }
427
428 /* Formats FORMAT as a printf string and appends the result to ST. */
429 void
430 ds_vprintf (struct string *st, const char *format, va_list args)
431 {
432   /* Fscking glibc silently changed behavior between 2.0 and 2.1.
433      Fsck fsck fsck.  Before, it returned -1 on buffer overflow.  Now,
434      it returns the number of characters (not bytes) that would have
435      been written. */
436
437   int avail, needed;
438
439   avail = st->capacity - st->length + 1;
440   needed = vsnprintf (st->string + st->length, avail, format, args);
441
442
443   if (needed >= avail)
444     {
445       ds_extend (st, st->length + needed);
446       
447       vsprintf (st->string + st->length, format, args);
448     }
449   else
450     while (needed == -1)
451       {
452         ds_extend (st, (st->capacity + 1) * 2);
453         avail = st->capacity - st->length + 1;
454
455         needed = vsnprintf (st->string + st->length, avail, format, args);
456
457       }
458
459   st->length += needed;
460 }
461
462 /* Appends character CH to ST. */
463 void
464 ds_putc (struct string *st, int ch)
465 {
466   if (st->length == st->capacity)
467     ds_extend (st, st->length + 1);
468   st->string[st->length++] = ch;
469 }
470
471 /* Appends to ST a newline-terminated line read from STREAM.
472    Newline is the last character of ST on return, unless an I/O error
473    or end of file is encountered after reading some characters.
474    Returns 1 if a line is successfully read, or 0 if no characters at
475    all were read before an I/O error or end of file was
476    encountered. */
477 int
478 ds_gets (struct string *st, FILE *stream)
479 {
480   int c;
481
482   c = getc (stream);
483   if (c == EOF)
484     return 0;
485
486   for (;;)
487     {
488       ds_putc (st, c);
489       if (c == '\n')
490         return 1;
491
492       c = getc (stream);
493       if (c == EOF)
494         return 1;
495     }
496 }
497
498 /* Reads a line from STREAM into ST, then preprocesses as follows:
499
500    - Splices lines terminated with `\'.
501
502    - Deletes comments introduced by `#' outside of single or double
503      quotes.
504
505    - Trailing whitespace will be deleted.  
506
507    Increments cust_ln as appropriate.
508
509    Returns nonzero only if a line was successfully read. */
510 int
511 ds_get_config_line (FILE *stream, struct string *st, struct file_locator *where)
512 {
513   /* Read the first line. */
514   ds_clear (st);
515   where->line_number++;
516   if (!ds_gets (st, stream))
517     return 0;
518
519   /* Read additional lines, if any. */
520   for (;;)
521     {
522       /* Remove trailing whitespace. */
523       {
524         char *s = ds_c_str (st);
525         size_t len = ds_length (st);
526       
527         while (len > 0 && isspace ((unsigned char) s[len - 1]))
528           len--;
529         ds_truncate (st, len);
530       }
531
532       /* Check for trailing \.  Remove if found, bail otherwise. */
533       if (ds_length (st) == 0 || ds_c_str (st)[ds_length (st) - 1] != '\\')
534         break;
535       ds_truncate (st, ds_length (st) - 1);
536
537       /* Append another line and go around again. */
538       {
539         int success = ds_gets (st, stream);
540         where->line_number++;
541         if (!success)
542           return 1;
543       }
544     }
545
546   /* Find a comment and remove. */
547   {
548     char *cp;
549     int quote = 0;
550       
551     for (cp = ds_c_str (st); *cp; cp++)
552       if (quote)
553         {
554           if (*cp == quote)
555             quote = 0;
556           else if (*cp == '\\')
557             cp++;
558         }
559       else if (*cp == '\'' || *cp == '"')
560         quote = *cp;
561       else if (*cp == '#')
562         {
563           ds_truncate (st, cp - ds_c_str (st));
564           break;
565         }
566   }
567
568   return 1;
569 }
570 \f
571 /* Lengthed strings. */
572
573 /* Creates a new lengthed string LS with contents as a copy of
574    S. */
575 void
576 ls_create (struct fixed_string *ls, const char *s)
577 {
578   ls->length = strlen (s);
579   ls->string = xmalloc (ls->length + 1);
580   memcpy (ls->string, s, ls->length + 1);
581 }
582
583 /* Creates a new lengthed string LS with contents as a copy of
584    BUFFER with length LEN. */
585 void
586 ls_create_buffer (struct fixed_string *ls,
587                   const char *buffer, size_t len)
588 {
589   ls->length = len;
590   ls->string = xmalloc (len + 1);
591   memcpy (ls->string, buffer, len);
592   ls->string[len] = '\0';
593 }
594
595 /* Sets the fields of LS to the specified values. */
596 void
597 ls_init (struct fixed_string *ls, const char *string, size_t length)
598 {
599   ls->string = (char *) string;
600   ls->length = length;
601 }
602
603 /* Copies the fields of SRC to DST. */
604 void
605 ls_shallow_copy (struct fixed_string *dst, const struct fixed_string *src)
606 {
607   *dst = *src;
608 }
609
610 /* Frees the memory backing LS. */
611 void
612 ls_destroy (struct fixed_string *ls)
613 {
614   free (ls->string);
615 }
616
617 /* Sets LS to a null pointer value. */
618 void
619 ls_null (struct fixed_string *ls)
620 {
621   ls->string = NULL;
622 }
623
624 /* Returns nonzero only if LS has a null pointer value. */
625 int
626 ls_null_p (const struct fixed_string *ls)
627 {
628   return ls->string == NULL;
629 }
630
631 /* Returns nonzero only if LS is a null pointer or has length 0. */
632 int
633 ls_empty_p (const struct fixed_string *ls)
634 {
635   return ls->string == NULL || ls->length == 0;
636 }
637
638 /* Returns the length of LS, which must not be null. */
639 size_t
640 ls_length (const struct fixed_string *ls)
641 {
642   return ls->length;
643 }
644
645 /* Returns a pointer to the character string in LS. */
646 char *
647 ls_c_str (const struct fixed_string *ls)
648 {
649   return (char *) ls->string;
650 }
651
652 /* Returns a pointer to the null terminator of the character string in
653    LS. */
654 char *
655 ls_end (const struct fixed_string *ls)
656 {
657   return (char *) (ls->string + ls->length);
658 }