Fixed memory leaks resulting from fn_interp_vars et. al.
[pspp-builds.git] / src / libpspp / str.c
1 /* PSPP - computes sample statistics.
2    Copyright (C) 1997-9, 2000, 2006 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 "message.h"
23 #include <ctype.h>
24 #include <limits.h>
25 #include <stdlib.h>
26 #include "alloc.h"
27 #include "message.h"
28 \f
29 /* Reverses the order of NBYTES bytes at address P, thus converting
30    between little- and big-endian byte orders.  */
31 void
32 buf_reverse (char *p, size_t nbytes)
33 {
34   char *h = p, *t = &h[nbytes - 1];
35   char temp;
36
37   nbytes /= 2;
38   while (nbytes--)
39     {
40       temp = *h;
41       *h++ = *t;
42       *t-- = temp;
43     }
44 }
45
46 /* Finds the last NEEDLE of length NEEDLE_LEN in a HAYSTACK of length
47    HAYSTACK_LEN.  Returns a pointer to the needle found. */
48 char *
49 buf_find_reverse (const char *haystack, size_t haystack_len,
50                  const char *needle, size_t needle_len)
51 {
52   int i;
53   for (i = haystack_len - needle_len; i >= 0; i--)
54     if (!memcmp (needle, &haystack[i], needle_len))
55       return (char *) &haystack[i];
56   return 0;
57 }
58
59 /* Compares the SIZE bytes in A to those in B, disregarding case,
60    and returns a strcmp()-type result. */
61 int
62 buf_compare_case (const char *a_, const char *b_, size_t size)
63 {
64   const unsigned char *a = (unsigned char *) a_;
65   const unsigned char *b = (unsigned char *) b_;
66
67   while (size-- > 0) 
68     {
69       unsigned char ac = toupper (*a++);
70       unsigned char bc = toupper (*b++);
71
72       if (ac != bc) 
73         return ac > bc ? 1 : -1;
74     }
75
76   return 0;
77 }
78
79 /* Compares A of length A_LEN to B of length B_LEN.  The shorter
80    string is considered to be padded with spaces to the length of
81    the longer. */
82 int
83 buf_compare_rpad (const char *a, size_t a_len, const char *b, size_t b_len)
84 {
85   size_t min_len;
86   int result;
87
88   min_len = a_len < b_len ? a_len : b_len;
89   result = memcmp (a, b, min_len);
90   if (result != 0)
91     return result;
92   else 
93     {
94       size_t idx;
95       
96       if (a_len < b_len) 
97         {
98           for (idx = min_len; idx < b_len; idx++)
99             if (' ' != b[idx])
100               return ' ' > b[idx] ? 1 : -1;
101         }
102       else 
103         {
104           for (idx = min_len; idx < a_len; idx++)
105             if (a[idx] != ' ')
106               return a[idx] > ' ' ? 1 : -1;
107         }
108       return 0;
109     }
110 }
111
112 /* Compares strin A to string B.  The shorter string is
113    considered to be padded with spaces to the length of the
114    longer. */
115 int
116 str_compare_rpad (const char *a, const char *b)
117 {
118   return buf_compare_rpad (a, strlen (a), b, strlen (b));
119 }
120
121 /* Copies string SRC to buffer DST, of size DST_SIZE bytes.
122    DST is truncated to DST_SIZE bytes or padded on the right with
123    spaces as needed. */
124 void
125 buf_copy_str_rpad (char *dst, size_t dst_size, const char *src)
126 {
127   size_t src_len = strlen (src);
128   if (src_len >= dst_size)
129     memcpy (dst, src, dst_size);
130   else
131     {
132       memcpy (dst, src, src_len);
133       memset (&dst[src_len], ' ', dst_size - src_len);
134     }
135 }
136
137 /* Copies string SRC to buffer DST, of size DST_SIZE bytes.
138    DST is truncated to DST_SIZE bytes or padded on the left with
139    spaces as needed. */
140 void
141 buf_copy_str_lpad (char *dst, size_t dst_size, const char *src)
142 {
143   size_t src_len = strlen (src);
144   if (src_len >= dst_size)
145     memcpy (dst, src, dst_size);
146   else
147     {
148       size_t pad_cnt = dst_size - src_len;
149       memset (&dst[0], ' ', pad_cnt);
150       memcpy (dst + pad_cnt, src, src_len);
151     }
152 }
153
154 /* Copies buffer SRC, of SRC_SIZE bytes, to DST, of DST_SIZE bytes.
155    DST is truncated to DST_SIZE bytes or padded on the right with
156    spaces as needed. */
157 void
158 buf_copy_rpad (char *dst, size_t dst_size,
159                const char *src, size_t src_size)
160 {
161   if (src_size >= dst_size)
162     memmove (dst, src, dst_size);
163   else
164     {
165       memmove (dst, src, src_size);
166       memset (&dst[src_size], ' ', dst_size - src_size);
167     }
168 }
169
170 /* Copies string SRC to string DST, which is in a buffer DST_SIZE
171    bytes long.
172    Truncates DST to DST_SIZE - 1 characters or right-pads with
173    spaces to DST_SIZE - 1 characters if necessary. */
174 void
175 str_copy_rpad (char *dst, size_t dst_size, const char *src)
176 {
177   size_t src_len = strlen (src);
178   if (src_len < dst_size - 1)
179     {
180       memcpy (dst, src, src_len);
181       memset (&dst[src_len], ' ', dst_size - 1 - src_len);
182     }
183   else
184     memcpy (dst, src, dst_size - 1);
185   dst[dst_size - 1] = 0;
186 }
187
188 /* Copies SRC to DST, which is in a buffer DST_SIZE bytes long.
189    Truncates DST to DST_SIZE - 1 characters, if necessary. */
190 void
191 str_copy_trunc (char *dst, size_t dst_size, const char *src) 
192 {
193   size_t src_len = strlen (src);
194   assert (dst_size > 0);
195   if (src_len + 1 < dst_size)
196     memcpy (dst, src, src_len + 1);
197   else 
198     {
199       memcpy (dst, src, dst_size - 1);
200       dst[dst_size - 1] = '\0';
201     }
202 }
203
204 /* Copies buffer SRC, of SRC_LEN bytes,
205    to DST, which is in a buffer DST_SIZE bytes long.
206    Truncates DST to DST_SIZE - 1 characters, if necessary. */
207 void
208 str_copy_buf_trunc (char *dst, size_t dst_size,
209                     const char *src, size_t src_size) 
210 {
211   size_t dst_len;
212   assert (dst_size > 0);
213
214   dst_len = src_size < dst_size ? src_size : dst_size - 1;
215   memcpy (dst, src, dst_len);
216   dst[dst_len] = '\0';
217 }
218
219 /* Converts each character in S to uppercase. */
220 void
221 str_uppercase (char *s) 
222 {
223   for (; *s != '\0'; s++)
224     *s = toupper ((unsigned char) *s);
225 }
226
227 /* Converts each character in S to lowercase. */
228 void
229 str_lowercase (char *s) 
230 {
231   for (; *s != '\0'; s++)
232     *s = tolower ((unsigned char) *s);
233 }
234 \f
235 /* Initializes ST with initial contents S. */
236 void
237 ds_create (struct string *st, const char *s)
238 {
239   st->length = strlen (s);
240   st->capacity = 8 + st->length * 2;
241   st->string = xmalloc (st->capacity + 1);
242   strcpy (st->string, s);
243 }
244
245 /* Initializes DST with the contents of SRC between characters FIRST and LAST 
246    inclusive */
247 void
248 ds_create_substr(struct string *dst, const struct string *src, 
249                  int first, int last)
250 {
251   assert(last >= first);
252   dst->length = last - first + 1;
253   dst->capacity = 8 + dst->length * 2;
254   dst->string = xmalloc (dst->capacity + 1);
255
256   memcpy (dst->string, &src->string[first], dst->length);
257 }
258
259
260 /* Initializes ST, making room for at least CAPACITY characters. */
261 void
262 ds_init (struct string *st, size_t capacity)
263 {
264   st->length = 0;
265   if (capacity > 8)
266     st->capacity = capacity;
267   else
268     st->capacity = 8;
269   st->string = xmalloc (st->capacity + 1);
270 }
271
272 /* Replaces the contents of ST with STRING.  STRING may overlap with
273    ST. */
274 void
275 ds_replace (struct string *st, const char *string)
276 {
277   size_t new_length = strlen (string);
278   if (new_length > st->capacity) 
279     {
280       /* The new length is longer than the allocated length, so
281          there can be no overlap. */
282       st->length = 0;
283       ds_concat (st, string, new_length);
284     }
285   else
286     {
287       /* Overlap is possible, but the new string will fit in the
288          allocated space, so we can just copy data. */
289       st->length = new_length;
290       memmove (st->string, string, st->length);
291     }
292 }
293
294 /* Frees ST. */
295 void
296 ds_destroy (struct string *st)
297 {
298   free (st->string);
299   st->string = NULL;
300 }
301
302 /* Swaps the contents of strings A and B. */
303 void
304 ds_swap (struct string *a, struct string *b) 
305 {
306   struct string tmp = *a;
307   *a = *b;
308   *b = tmp;
309 }
310
311 /* Truncates ST to zero length. */
312 void
313 ds_clear (struct string *st)
314 {
315   st->length = 0;
316 }
317
318 /* Pad ST on the right with copies of PAD until ST is at least
319    LENGTH characters in size.  If ST is initially LENGTH
320    characters or longer, this is a no-op. */
321 void
322 ds_rpad (struct string *st, size_t length, char pad) 
323 {
324   assert (st != NULL);
325   if (st->length < length) 
326     {
327       if (st->capacity < length)
328         ds_extend (st, length);
329       memset (&st->string[st->length], pad, length - st->length);
330       st->length = length;
331     }
332 }
333
334 /* Removes trailing spaces from ST.
335    Returns number of spaces removed. */
336 int
337 ds_rtrim_spaces (struct string *st) 
338 {
339   int cnt = 0;
340   while (isspace (ds_last (st))) 
341     {
342       st->length--;
343       cnt++;
344     }
345   return cnt;
346 }
347
348 /* Removes leading spaces from ST.
349    Returns number of spaces removed. */
350 int
351 ds_ltrim_spaces (struct string *st) 
352 {
353   int idx = ds_n_find(st, "\t ");
354   if (0 == idx)
355     return 0;
356
357   if (idx < 0 ) 
358     {
359       int len = ds_length(st);
360       ds_clear(st);
361       return len;
362     }
363   
364   ds_replace(st, &ds_c_str(st)[idx]);
365     
366   return idx;
367 }
368
369
370 /* If the last character in ST is C, removes it and returns true.
371    Otherwise, returns false without modifying ST. */
372 bool
373 ds_chomp (struct string *st, char c_) 
374 {
375   unsigned char c = c_;
376   if (ds_last (st) == c)
377     {
378       st->length--;
379       return true;
380     }
381   else
382     return false;
383 }
384
385 /* Ensures that ST can hold at least MIN_CAPACITY characters plus a null
386    terminator. */
387 void
388 ds_extend (struct string *st, size_t min_capacity)
389 {
390   if (min_capacity > st->capacity)
391     {
392       st->capacity *= 2;
393       if (st->capacity < min_capacity)
394         st->capacity = min_capacity * 2;
395       
396       st->string = xrealloc (st->string, st->capacity + 1);
397     }
398 }
399
400 /* Shrink ST to the minimum capacity need to contain its content. */
401 void
402 ds_shrink (struct string *st)
403 {
404   if (st->capacity != st->length)
405     {
406       st->capacity = st->length;
407       st->string = xrealloc (st->string, st->capacity + 1);
408     }
409 }
410
411 /* Truncates ST to at most LENGTH characters long. */
412 void
413 ds_truncate (struct string *st, size_t length)
414 {
415   if (length >= st->length)
416     return;
417   st->length = length;
418 }
419
420 /* Returns true if ST is empty, false otherwise. */
421 bool
422 ds_is_empty (const struct string *st) 
423 {
424   return st->length == 0;
425 }
426
427 /* Returns the length of ST. */
428 size_t
429 ds_length (const struct string *st)
430 {
431   return st->length;
432 }
433
434 /* Returns the allocation size of ST. */
435 size_t
436 ds_capacity (const struct string *st)
437 {
438   return st->capacity;
439 }
440
441
442 /* Returns the index of the first character in ST which 
443    is an element of the set CS.
444    Returns -1 if no characters are found.
445 */
446 int
447 ds_find(const struct string *st, const char cs[])
448 {
449   int i;
450   int j;
451   for(i = 0; i < st->length ;  ++i)
452     {
453       if ('\0' == st->string[i]) 
454         break;
455       for (j = 0 ; j < strlen(cs) ; ++j)
456         {
457           if ( st->string[i] == cs[j])
458             return i;
459         }
460     }
461   return -1;
462 }
463
464 /* Returns the index of the first character in ST which 
465    is NOT an element of the set CS.
466    Returns -1 if no such character is found.
467 */
468 int
469 ds_n_find(const struct string *st, const char cs[])
470 {
471   int i;
472   int j;
473   for(i = 0; i < st->length ;  ++i)
474     {
475       bool found = false;
476       if ('\0' == st->string[i]) 
477         break;
478       for (j = 0 ; j < strlen(cs) ; ++j)
479         {
480           if ( st->string[i] == cs[j])
481             {
482               found = true;
483               break;
484             }
485         }
486       if ( !found )
487         return i;
488     }
489   return -1;
490 }
491
492
493
494 /* Returns the first character in ST as a value in the range of
495    unsigned char.  Returns EOF if ST is the empty string. */
496 int
497 ds_first (const struct string *st) 
498 {
499   return st->length > 0 ? (unsigned char) st->string[0] : EOF;
500 }
501
502 /* Returns the last character in ST as a value in the range of
503    unsigned char.  Returns EOF if ST is the empty string. */
504 int
505 ds_last (const struct string *st) 
506 {
507   return st->length > 0 ? (unsigned char) st->string[st->length - 1] : EOF;
508 }
509
510 /* Returns the value of ST as a null-terminated string. */
511 char *
512 ds_c_str (const struct string *st)
513 {
514   ((char *) st->string)[st->length] = '\0';
515   return st->string;
516 }
517
518 /* Returns the string data inside ST. */
519 char *
520 ds_data (const struct string *st)
521 {
522   return st->string;
523 }
524
525 /* Returns a pointer to the null terminator ST.
526    This might not be an actual null character unless ds_c_str() has
527    been called since the last modification to ST. */
528 char *
529 ds_end (const struct string *st)
530 {
531   return st->string + st->length;
532 }
533
534 /* Concatenates S onto ST. */
535 void
536 ds_puts (struct string *st, const char *s)
537 {
538   size_t s_len;
539
540   if (!s) return;
541
542   s_len = strlen (s);
543   ds_extend (st, st->length + s_len);
544   strcpy (st->string + st->length, s);
545   st->length += s_len;
546 }
547
548 /* Concatenates LEN characters from BUF onto ST. */
549 void
550 ds_concat (struct string *st, const char *buf, size_t len)
551 {
552   ds_extend (st, st->length + len);
553   memcpy (st->string + st->length, buf, len);
554   st->length += len;
555 }
556
557 void ds_vprintf (struct string *st, const char *format, va_list args);
558
559
560 /* Formats FORMAT as a printf string and appends the result to ST. */
561 void
562 ds_printf (struct string *st, const char *format, ...)
563 {
564   va_list args;
565
566   va_start (args, format);
567   ds_vprintf(st,format,args);
568   va_end (args);
569
570 }
571
572 /* Formats FORMAT as a printf string and appends the result to ST. */
573 void
574 ds_vprintf (struct string *st, const char *format, va_list args)
575 {
576   /* Fscking glibc silently changed behavior between 2.0 and 2.1.
577      Fsck fsck fsck.  Before, it returned -1 on buffer overflow.  Now,
578      it returns the number of characters (not bytes) that would have
579      been written. */
580
581   int avail, needed;
582   va_list a1;
583
584   va_copy(a1, args);
585   avail = st->capacity - st->length + 1;
586   needed = vsnprintf (st->string + st->length, avail, format, args);
587
588
589   if (needed >= avail)
590     {
591       ds_extend (st, st->length + needed);
592       
593       vsprintf (st->string + st->length, format, a1);
594     }
595   else
596     while (needed == -1)
597       {
598         va_list a2;
599         va_copy(a2, a1);
600
601         ds_extend (st, (st->capacity + 1) * 2);
602         avail = st->capacity - st->length + 1;
603
604         needed = vsnprintf (st->string + st->length, avail, format, a2);
605         va_end(a2);
606
607       }
608   va_end(a1);
609
610   st->length += needed;
611 }
612
613 /* Appends character CH to ST. */
614 void
615 ds_putc (struct string *st, int ch)
616 {
617   if (st->length == st->capacity)
618     ds_extend (st, st->length + 1);
619   st->string[st->length++] = ch;
620 }
621
622 /* Appends to ST a newline-terminated line read from STREAM.
623    Newline is the last character of ST on return, unless an I/O error
624    or end of file is encountered after reading some characters.
625    Returns 1 if a line is successfully read, or 0 if no characters at
626    all were read before an I/O error or end of file was
627    encountered. */
628 int
629 ds_gets (struct string *st, FILE *stream)
630 {
631   int c;
632
633   c = getc (stream);
634   if (c == EOF)
635     return 0;
636
637   for (;;)
638     {
639       ds_putc (st, c);
640       if (c == '\n')
641         return 1;
642
643       c = getc (stream);
644       if (c == EOF)
645         return 1;
646     }
647 }
648
649 /* Reads a line from STREAM into ST, then preprocesses as follows:
650
651    - Splices lines terminated with `\'.
652
653    - Deletes comments introduced by `#' outside of single or double
654      quotes.
655
656    - Trailing whitespace will be deleted.  
657
658    Increments cust_ln as appropriate.
659
660    Returns nonzero only if a line was successfully read. */
661 int
662 ds_get_config_line (FILE *stream, struct string *st, struct file_locator *where)
663 {
664   /* Read the first line. */
665   ds_clear (st);
666   where->line_number++;
667   if (!ds_gets (st, stream))
668     return 0;
669
670   /* Read additional lines, if any. */
671   for (;;)
672     {
673       /* Remove trailing whitespace. */
674       {
675         char *s = ds_c_str (st);
676         size_t len = ds_length (st);
677       
678         while (len > 0 && isspace ((unsigned char) s[len - 1]))
679           len--;
680         ds_truncate (st, len);
681       }
682
683       /* Check for trailing \.  Remove if found, bail otherwise. */
684       if (ds_length (st) == 0 || ds_c_str (st)[ds_length (st) - 1] != '\\')
685         break;
686       ds_truncate (st, ds_length (st) - 1);
687
688       /* Append another line and go around again. */
689       {
690         int success = ds_gets (st, stream);
691         where->line_number++;
692         if (!success)
693           return 1;
694       }
695     }
696
697   /* Find a comment and remove. */
698   {
699     char *cp;
700     int quote = 0;
701       
702     for (cp = ds_c_str (st); *cp; cp++)
703       if (quote)
704         {
705           if (*cp == quote)
706             quote = 0;
707           else if (*cp == '\\')
708             cp++;
709         }
710       else if (*cp == '\'' || *cp == '"')
711         quote = *cp;
712       else if (*cp == '#')
713         {
714           ds_truncate (st, cp - ds_c_str (st));
715           break;
716         }
717   }
718
719   return 1;
720 }
721 \f
722 /* Lengthed strings. */
723
724 /* Creates a new lengthed string LS with contents as a copy of
725    S. */
726 void
727 ls_create (struct fixed_string *ls, const char *s)
728 {
729   ls->length = strlen (s);
730   ls->string = xmalloc (ls->length + 1);
731   memcpy (ls->string, s, ls->length + 1);
732 }
733
734 /* Creates a new lengthed string LS with contents as a copy of
735    BUFFER with length LEN. */
736 void
737 ls_create_buffer (struct fixed_string *ls,
738                   const char *buffer, size_t len)
739 {
740   ls->length = len;
741   ls->string = xmalloc (len + 1);
742   memcpy (ls->string, buffer, len);
743   ls->string[len] = '\0';
744 }
745
746 /* Sets the fields of LS to the specified values. */
747 void
748 ls_init (struct fixed_string *ls, const char *string, size_t length)
749 {
750   ls->string = (char *) string;
751   ls->length = length;
752 }
753
754 /* Copies the fields of SRC to DST. */
755 void
756 ls_shallow_copy (struct fixed_string *dst, const struct fixed_string *src)
757 {
758   *dst = *src;
759 }
760
761 /* Frees the memory backing LS. */
762 void
763 ls_destroy (struct fixed_string *ls)
764 {
765   free (ls->string);
766 }
767
768 /* Sets LS to a null pointer value. */
769 void
770 ls_null (struct fixed_string *ls)
771 {
772   ls->string = NULL;
773 }
774
775 /* Returns nonzero only if LS has a null pointer value. */
776 int
777 ls_null_p (const struct fixed_string *ls)
778 {
779   return ls->string == NULL;
780 }
781
782 /* Returns nonzero only if LS is a null pointer or has length 0. */
783 int
784 ls_empty_p (const struct fixed_string *ls)
785 {
786   return ls->string == NULL || ls->length == 0;
787 }
788
789 /* Returns the length of LS, which must not be null. */
790 size_t
791 ls_length (const struct fixed_string *ls)
792 {
793   return ls->length;
794 }
795
796 /* Returns a pointer to the character string in LS. */
797 char *
798 ls_c_str (const struct fixed_string *ls)
799 {
800   return (char *) ls->string;
801 }
802
803 /* Returns a pointer to the null terminator of the character string in
804    LS. */
805 char *
806 ls_end (const struct fixed_string *ls)
807 {
808   return (char *) (ls->string + ls->length);
809 }