Fixed issues which arose on x86_64 architecture
[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 buf_reverse (char *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 buf_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 buf_compare_case (const char *a_, const char *b_, size_t size)
111 {
112   const unsigned char *a = (unsigned char *) a_;
113   const unsigned char *b = (unsigned char *) 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 buf_compare_rpad (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 /* Compares strin A to string B.  The shorter string is
161    considered to be padded with spaces to the length of the
162    longer. */
163 int
164 str_compare_rpad (const char *a, const char *b)
165 {
166   return buf_compare_rpad (a, strlen (a), b, strlen (b));
167 }
168
169 /* Copies string SRC to buffer DST, of size DST_SIZE bytes.
170    DST is truncated to DST_SIZE bytes or padded on the right with
171    spaces as needed. */
172 void
173 buf_copy_str_rpad (char *dst, size_t dst_size, const char *src)
174 {
175   size_t src_len = strlen (src);
176   if (src_len >= dst_size)
177     memcpy (dst, src, dst_size);
178   else
179     {
180       memcpy (dst, src, src_len);
181       memset (&dst[src_len], ' ', dst_size - src_len);
182     }
183 }
184
185 /* Copies string SRC to buffer DST, of size DST_SIZE bytes.
186    DST is truncated to DST_SIZE bytes or padded on the left with
187    spaces as needed. */
188 void
189 buf_copy_str_lpad (char *dst, size_t dst_size, const char *src)
190 {
191   size_t src_len = strlen (src);
192   if (src_len >= dst_size)
193     memcpy (dst, src, dst_size);
194   else
195     {
196       size_t pad_cnt = dst_size - src_len;
197       memset (&dst[0], ' ', pad_cnt);
198       memcpy (dst + pad_cnt, src, src_len);
199     }
200 }
201
202 /* Copies buffer SRC, of SRC_SIZE bytes, to DST, of DST_SIZE bytes.
203    DST is truncated to DST_SIZE bytes or padded on the right with
204    spaces as needed. */
205 void
206 buf_copy_rpad (char *dst, size_t dst_size,
207                const char *src, size_t src_size)
208 {
209   if (src_size >= dst_size)
210     memmove (dst, src, dst_size);
211   else
212     {
213       memmove (dst, src, src_size);
214       memset (&dst[src_size], ' ', dst_size - src_size);
215     }
216 }
217
218 /* Copies string SRC to string DST, which is in a buffer DST_SIZE
219    bytes long.
220    Truncates DST to DST_SIZE - 1 characters or right-pads with
221    spaces to DST_SIZE - 1 characters if necessary. */
222 void
223 str_copy_rpad (char *dst, size_t dst_size, const char *src)
224 {
225   size_t src_len = strlen (src);
226   if (src_len < dst_size - 1)
227     {
228       memcpy (dst, src, src_len);
229       memset (&dst[src_len], ' ', dst_size - 1 - src_len);
230     }
231   else
232     memcpy (dst, src, dst_size - 1);
233   dst[dst_size - 1] = 0;
234 }
235
236 /* Copies SRC to DST, which is in a buffer DST_SIZE bytes long.
237    Truncates DST to DST_SIZE - 1 characters, if necessary. */
238 void
239 str_copy_trunc (char *dst, size_t dst_size, const char *src) 
240 {
241   size_t src_len = strlen (src);
242   assert (dst_size > 0);
243   if (src_len + 1 < dst_size)
244     memcpy (dst, src, src_len + 1);
245   else 
246     {
247       memcpy (dst, src, dst_size - 1);
248       dst[dst_size - 1] = '\0';
249     }
250 }
251
252 /* Converts each character in S to uppercase. */
253 void
254 str_uppercase (char *s) 
255 {
256   for (; *s != '\0'; s++)
257     *s = toupper ((unsigned char) *s);
258 }
259 \f
260 /* Initializes ST with initial contents S. */
261 void
262 ds_create (struct string *st, const char *s)
263 {
264   st->length = strlen (s);
265   st->capacity = 8 + st->length * 2;
266   st->string = xmalloc (st->capacity + 1);
267   strcpy (st->string, s);
268 }
269
270 /* Initializes ST, making room for at least CAPACITY characters. */
271 void
272 ds_init (struct string *st, size_t capacity)
273 {
274   st->length = 0;
275   if (capacity > 8)
276     st->capacity = capacity;
277   else
278     st->capacity = 8;
279   st->string = xmalloc (st->capacity + 1);
280 }
281
282 /* Replaces the contents of ST with STRING.  STRING may overlap with
283    ST. */
284 void
285 ds_replace (struct string *st, const char *string)
286 {
287   size_t new_length = strlen (string);
288   if (new_length > st->capacity) 
289     {
290       /* The new length is longer than the allocated length, so
291          there can be no overlap. */
292       st->length = 0;
293       ds_concat (st, string, new_length);
294     }
295   else
296     {
297       /* Overlap is possible, but the new string will fit in the
298          allocated space, so we can just copy data. */
299       st->length = new_length;
300       memmove (st->string, string, st->length);
301     }
302 }
303
304 /* Frees ST. */
305 void
306 ds_destroy (struct string *st)
307 {
308   free (st->string);
309   st->string = NULL;
310 }
311
312 /* Truncates ST to zero length. */
313 void
314 ds_clear (struct string *st)
315 {
316   st->length = 0;
317 }
318
319 /* Pad ST on the right with copies of PAD until ST is at least
320    LENGTH characters in size.  If ST is initially LENGTH
321    characters or longer, this is a no-op. */
322 void
323 ds_rpad (struct string *st, size_t length, char pad) 
324 {
325   assert (st != NULL);
326   if (st->length < length) 
327     {
328       if (st->capacity < length)
329         ds_extend (st, length);
330       memset (&st->string[st->length], pad, length - st->length);
331       st->length = length;
332     }
333 }
334
335 /* Ensures that ST can hold at least MIN_CAPACITY characters plus a null
336    terminator. */
337 void
338 ds_extend (struct string *st, size_t min_capacity)
339 {
340   if (min_capacity > st->capacity)
341     {
342       st->capacity *= 2;
343       if (st->capacity < min_capacity)
344         st->capacity = min_capacity * 2;
345       
346       st->string = xrealloc (st->string, st->capacity + 1);
347     }
348 }
349
350 /* Shrink ST to the minimum capacity need to contain its content. */
351 void
352 ds_shrink (struct string *st)
353 {
354   if (st->capacity != st->length)
355     {
356       st->capacity = st->length;
357       st->string = xrealloc (st->string, st->capacity + 1);
358     }
359 }
360
361 /* Truncates ST to at most LENGTH characters long. */
362 void
363 ds_truncate (struct string *st, size_t length)
364 {
365   if (length >= st->length)
366     return;
367   st->length = length;
368 }
369
370 /* Returns the length of ST. */
371 size_t
372 ds_length (const struct string *st)
373 {
374   return st->length;
375 }
376
377 /* Returns the allocation size of ST. */
378 size_t
379 ds_capacity (const struct string *st)
380 {
381   return st->capacity;
382 }
383
384 /* Returns the value of ST as a null-terminated string. */
385 char *
386 ds_c_str (const struct string *st)
387 {
388   ((char *) st->string)[st->length] = '\0';
389   return st->string;
390 }
391
392 /* Returns the string data inside ST. */
393 char *
394 ds_data (const struct string *st)
395 {
396   return st->string;
397 }
398
399 /* Returns a pointer to the null terminator ST.
400    This might not be an actual null character unless ds_c_str() has
401    been called since the last modification to ST. */
402 char *
403 ds_end (const struct string *st)
404 {
405   return st->string + st->length;
406 }
407
408 /* Concatenates S onto ST. */
409 void
410 ds_puts (struct string *st, const char *s)
411 {
412   size_t s_len;
413
414   if (!s) return;
415
416   s_len = strlen (s);
417   ds_extend (st, st->length + s_len);
418   strcpy (st->string + st->length, s);
419   st->length += s_len;
420 }
421
422 /* Concatenates LEN characters from BUF onto ST. */
423 void
424 ds_concat (struct string *st, const char *buf, size_t len)
425 {
426   ds_extend (st, st->length + len);
427   memcpy (st->string + st->length, buf, len);
428   st->length += len;
429 }
430
431 void ds_vprintf (struct string *st, const char *format, va_list args);
432
433
434 /* Formats FORMAT as a printf string and appends the result to ST. */
435 void
436 ds_printf (struct string *st, const char *format, ...)
437 {
438   va_list args;
439
440   va_start (args, format);
441   ds_vprintf(st,format,args);
442   va_end (args);
443
444 }
445
446 /* Formats FORMAT as a printf string and appends the result to ST. */
447 void
448 ds_vprintf (struct string *st, const char *format, va_list args)
449 {
450   /* Fscking glibc silently changed behavior between 2.0 and 2.1.
451      Fsck fsck fsck.  Before, it returned -1 on buffer overflow.  Now,
452      it returns the number of characters (not bytes) that would have
453      been written. */
454
455   int avail, needed;
456   va_list a1;
457
458   va_copy(a1, args);
459   avail = st->capacity - st->length + 1;
460   needed = vsnprintf (st->string + st->length, avail, format, args);
461
462
463   if (needed >= avail)
464     {
465       ds_extend (st, st->length + needed);
466       
467       vsprintf (st->string + st->length, format, a1);
468     }
469   else
470     while (needed == -1)
471       {
472         va_list a2;
473         va_copy(a2, a1);
474
475         ds_extend (st, (st->capacity + 1) * 2);
476         avail = st->capacity - st->length + 1;
477
478         needed = vsnprintf (st->string + st->length, avail, format, a2);
479         va_end(a2);
480
481       }
482   va_end(a1);
483
484   st->length += needed;
485 }
486
487 /* Appends character CH to ST. */
488 void
489 ds_putc (struct string *st, int ch)
490 {
491   if (st->length == st->capacity)
492     ds_extend (st, st->length + 1);
493   st->string[st->length++] = ch;
494 }
495
496 /* Appends to ST a newline-terminated line read from STREAM.
497    Newline is the last character of ST on return, unless an I/O error
498    or end of file is encountered after reading some characters.
499    Returns 1 if a line is successfully read, or 0 if no characters at
500    all were read before an I/O error or end of file was
501    encountered. */
502 int
503 ds_gets (struct string *st, FILE *stream)
504 {
505   int c;
506
507   c = getc (stream);
508   if (c == EOF)
509     return 0;
510
511   for (;;)
512     {
513       ds_putc (st, c);
514       if (c == '\n')
515         return 1;
516
517       c = getc (stream);
518       if (c == EOF)
519         return 1;
520     }
521 }
522
523 /* Reads a line from STREAM into ST, then preprocesses as follows:
524
525    - Splices lines terminated with `\'.
526
527    - Deletes comments introduced by `#' outside of single or double
528      quotes.
529
530    - Trailing whitespace will be deleted.  
531
532    Increments cust_ln as appropriate.
533
534    Returns nonzero only if a line was successfully read. */
535 int
536 ds_get_config_line (FILE *stream, struct string *st, struct file_locator *where)
537 {
538   /* Read the first line. */
539   ds_clear (st);
540   where->line_number++;
541   if (!ds_gets (st, stream))
542     return 0;
543
544   /* Read additional lines, if any. */
545   for (;;)
546     {
547       /* Remove trailing whitespace. */
548       {
549         char *s = ds_c_str (st);
550         size_t len = ds_length (st);
551       
552         while (len > 0 && isspace ((unsigned char) s[len - 1]))
553           len--;
554         ds_truncate (st, len);
555       }
556
557       /* Check for trailing \.  Remove if found, bail otherwise. */
558       if (ds_length (st) == 0 || ds_c_str (st)[ds_length (st) - 1] != '\\')
559         break;
560       ds_truncate (st, ds_length (st) - 1);
561
562       /* Append another line and go around again. */
563       {
564         int success = ds_gets (st, stream);
565         where->line_number++;
566         if (!success)
567           return 1;
568       }
569     }
570
571   /* Find a comment and remove. */
572   {
573     char *cp;
574     int quote = 0;
575       
576     for (cp = ds_c_str (st); *cp; cp++)
577       if (quote)
578         {
579           if (*cp == quote)
580             quote = 0;
581           else if (*cp == '\\')
582             cp++;
583         }
584       else if (*cp == '\'' || *cp == '"')
585         quote = *cp;
586       else if (*cp == '#')
587         {
588           ds_truncate (st, cp - ds_c_str (st));
589           break;
590         }
591   }
592
593   return 1;
594 }
595 \f
596 /* Lengthed strings. */
597
598 /* Creates a new lengthed string LS with contents as a copy of
599    S. */
600 void
601 ls_create (struct fixed_string *ls, const char *s)
602 {
603   ls->length = strlen (s);
604   ls->string = xmalloc (ls->length + 1);
605   memcpy (ls->string, s, ls->length + 1);
606 }
607
608 /* Creates a new lengthed string LS with contents as a copy of
609    BUFFER with length LEN. */
610 void
611 ls_create_buffer (struct fixed_string *ls,
612                   const char *buffer, size_t len)
613 {
614   ls->length = len;
615   ls->string = xmalloc (len + 1);
616   memcpy (ls->string, buffer, len);
617   ls->string[len] = '\0';
618 }
619
620 /* Sets the fields of LS to the specified values. */
621 void
622 ls_init (struct fixed_string *ls, const char *string, size_t length)
623 {
624   ls->string = (char *) string;
625   ls->length = length;
626 }
627
628 /* Copies the fields of SRC to DST. */
629 void
630 ls_shallow_copy (struct fixed_string *dst, const struct fixed_string *src)
631 {
632   *dst = *src;
633 }
634
635 /* Frees the memory backing LS. */
636 void
637 ls_destroy (struct fixed_string *ls)
638 {
639   free (ls->string);
640 }
641
642 /* Sets LS to a null pointer value. */
643 void
644 ls_null (struct fixed_string *ls)
645 {
646   ls->string = NULL;
647 }
648
649 /* Returns nonzero only if LS has a null pointer value. */
650 int
651 ls_null_p (const struct fixed_string *ls)
652 {
653   return ls->string == NULL;
654 }
655
656 /* Returns nonzero only if LS is a null pointer or has length 0. */
657 int
658 ls_empty_p (const struct fixed_string *ls)
659 {
660   return ls->string == NULL || ls->length == 0;
661 }
662
663 /* Returns the length of LS, which must not be null. */
664 size_t
665 ls_length (const struct fixed_string *ls)
666 {
667   return ls->length;
668 }
669
670 /* Returns a pointer to the character string in LS. */
671 char *
672 ls_c_str (const struct fixed_string *ls)
673 {
674   return (char *) ls->string;
675 }
676
677 /* Returns a pointer to the null terminator of the character string in
678    LS. */
679 char *
680 ls_end (const struct fixed_string *ls)
681 {
682   return (char *) (ls->string + ls->length);
683 }