056ef6fc934a79ecf753ab06ef84fec594d3127b
[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., 59 Temple Place - Suite 330, Boston, MA
18    02111-1307, 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 A of length A_LEN to B of length B_LEN.  The shorter
108    string is considered to be padded with spaces to the length of
109    the longer. */
110 int
111 st_compare_pad (const char *a, size_t a_len, const char *b, size_t b_len)
112 {
113   size_t min_len;
114   int result;
115
116   min_len = a_len < b_len ? a_len : b_len;
117   result = memcmp (a, b, min_len);
118   if (result != 0)
119     return result;
120   else 
121     {
122       size_t idx;
123       
124       if (a_len < b_len) 
125         {
126           for (idx = min_len; idx < b_len; idx++)
127             if (' ' != b[idx])
128               return ' ' > b[idx] ? 1 : -1;
129         }
130       else 
131         {
132           for (idx = min_len; idx < a_len; idx++)
133             if (a[idx] != ' ')
134               return a[idx] > ' ' ? 1 : -1;
135         }
136       return 0;
137     }
138 }
139
140 /* Copies SRC to DEST, truncating to N characters or right-padding
141    with spaces to N characters as necessary.  Does not append a null
142    character.  SRC must be null-terminated. */
143 void
144 st_bare_pad_copy (char *dest, const char *src, size_t n)
145 {
146   size_t len;
147
148   len = strlen (src);
149   if (len >= n)
150     memcpy (dest, src, n);
151   else
152     {
153       memcpy (dest, src, len);
154       memset (&dest[len], ' ', n - len);
155     }
156 }
157
158 /* Copies SRC to DEST, truncating SRC to N characters or right-padding
159    with spaces to N characters if necessary.  Does not append a null
160    character.  SRC must be LEN characters long but does not need to be
161    null-terminated. */
162 void
163 st_bare_pad_len_copy (char *dest, const char *src, size_t n, size_t len)
164 {
165   if (len >= n)
166     memcpy (dest, src, n);
167   else
168     {
169       memcpy (dest, src, len);
170       memset (&dest[len], ' ', n - len);
171     }
172 }
173
174 /* Copies SRC to DEST, truncating SRC to N-1 characters or
175    right-padding with spaces to N-1 characters if necessary.  Always
176    appends a null character. */
177 void
178 st_pad_copy (char *dest, const char *src, size_t n)
179 {
180   size_t len;
181
182   len = strlen (src);
183   if (len == n - 1)
184     strcpy (dest, src);
185   else if (len < n - 1)
186     {
187       memcpy (dest, src, len);
188       memset (&dest[len], ' ', n - 1 - len);
189       dest[n - 1] = 0;
190     }
191   else
192     {
193       memcpy (dest, src, n - 1);
194       dest[n - 1] = 0;
195     }
196 }
197 \f
198 /* Initializes ST inside pool POOL (which may be a null pointer) with
199    initial contents S. */
200 void
201 ds_create (struct pool *pool, struct string *st, const char *s)
202 {
203   st->pool = pool;
204   st->length = strlen (s);
205   st->size = 8 + st->length * 2;
206   st->string = pool_malloc (pool, st->size + 1);
207   strcpy (st->string, s);
208 }
209
210 /* Initializes ST inside POOL (which may be null), making room for at
211    least SIZE characters. */
212 void
213 ds_init (struct pool *pool, struct string *st, size_t size)
214 {
215   st->pool = pool;
216   st->length = 0;
217   if (size > 8)
218     st->size = size;
219   else
220     st->size = 8;
221   st->string = pool_malloc (pool, st->size + 1);
222 }
223
224 /* Replaces the contents of ST with STRING.  STRING may overlap with
225    ST. */
226 void
227 ds_replace (struct string *st, const char *string)
228 {
229   char *s = st->string;
230   st->string = NULL;
231   ds_create (st->pool, st, string);
232   pool_free (st->pool, s);
233 }
234
235 /* Frees ST. */
236 void
237 ds_destroy (struct string *st)
238 {
239   pool_free (st->pool, st->string);
240 }
241
242 /* Truncates ST to zero length. */
243 void
244 ds_clear (struct string *st)
245 {
246   st->length = 0;
247 }
248
249 /* Ensures that ST can hold at least MIN_SIZE characters plus a null
250    terminator. */
251 void
252 ds_extend (struct string *st, size_t min_size)
253 {
254   if (min_size > st->size)
255     {
256       st->size *= 2;
257       if (st->size < min_size)
258         st->size = min_size * 2;
259       
260       st->string = pool_realloc (st->pool, st->string, st->size + 1);
261     }
262 }
263
264 /* Shrink ST to the minimum size need to contain its content. */
265 void
266 ds_shrink (struct string *st)
267 {
268   if (st->size != st->length)
269     {
270       st->size = st->length;
271       st->string = pool_realloc (st->pool, st->string, st->size + 1);
272     }
273 }
274
275 /* Truncates ST to at most LENGTH characters long. */
276 void
277 ds_truncate (struct string *st, size_t length)
278 {
279   if (length >= st->length)
280     return;
281   st->length = length;
282 }
283
284 /* Returns the length of ST. */
285 size_t
286 ds_length (const struct string *st)
287 {
288   return st->length;
289 }
290
291 /* Returns the allocation size of ST. */
292 size_t
293 ds_size (const struct string *st)
294 {
295   return st->size;
296 }
297
298 /* Returns the value of ST as a null-terminated string. */
299 char *
300 ds_value (const struct string *st)
301 {
302   ((char *) st->string)[st->length] = '\0';
303   return st->string;
304 }
305
306 /* Returns a pointer to the null terminator ST.
307    This might not be an actual null character unless ds_value() has
308    been called since the last modification to ST. */
309 char *
310 ds_end (const struct string *st)
311 {
312   return st->string + st->length;
313 }
314
315 /* Concatenates S onto ST. */
316 void
317 ds_concat (struct string *st, const char *s)
318 {
319   size_t s_len;
320
321   if (!s) return;
322
323   s_len = strlen (s);
324   ds_extend (st, st->length + s_len);
325   strcpy (st->string + st->length, s);
326   st->length += s_len;
327 }
328
329 /* Concatenates LEN characters from BUF onto ST. */
330 void
331 ds_concat_buffer (struct string *st, const char *buf, size_t len)
332 {
333   ds_extend (st, st->length + len);
334   memcpy (st->string + st->length, buf, len);
335   st->length += len;
336 }
337
338 void ds_vprintf (struct string *st, const char *format, va_list args);
339
340
341 /* Formats FORMAT as a printf string and appends the result to ST. */
342 void
343 ds_printf (struct string *st, const char *format, ...)
344 {
345   va_list args;
346
347   va_start (args, format);
348   ds_vprintf(st,format,args);
349   va_end (args);
350
351 }
352
353 /* Formats FORMAT as a printf string and appends the result to ST. */
354 void
355 ds_vprintf (struct string *st, const char *format, va_list args)
356 {
357   /* Fscking glibc silently changed behavior between 2.0 and 2.1.
358      Fsck fsck fsck.  Before, it returned -1 on buffer overflow.  Now,
359      it returns the number of characters (not bytes) that would have
360      been written. */
361
362   int avail, needed;
363
364   avail = st->size - st->length + 1;
365   needed = vsnprintf (st->string + st->length, avail, format, args);
366
367
368   if (needed >= avail)
369     {
370       ds_extend (st, st->length + needed);
371       
372       vsprintf (st->string + st->length, format, args);
373     }
374   else
375     while (needed == -1)
376       {
377         ds_extend (st, (st->size + 1) * 2);
378         avail = st->size - st->length + 1;
379
380         needed = vsnprintf (st->string + st->length, avail, format, args);
381
382       }
383
384   st->length += needed;
385 }
386
387 /* Appends character CH to ST. */
388 void
389 ds_putchar (struct string *st, int ch)
390 {
391   if (st->length == st->size)
392     ds_extend (st, st->length + 1);
393   st->string[st->length++] = ch;
394 }
395
396 /* Reads a newline-terminated line from STREAM into ST.
397    Newline is the last character of ST on return, unless an I/O error
398    or end of file is encountered after reading some characters.
399    Returns 1 if a line is successfully read, or 0 if no characters at
400    all were read before an I/O error or end of file was
401    encountered. */
402 int
403 ds_getline (struct string *st, FILE *stream)
404 {
405   int c;
406
407   c = getc (stream);
408   if (c == EOF)
409     return 0;
410
411   for (;;)
412     {
413       ds_putchar (st, c);
414       if (c == '\n')
415         return 1;
416
417       c = getc (stream);
418       if (c == EOF)
419         return 1;
420     }
421 }
422
423 /* Reads a line from STREAM into ST, then preprocesses as follows:
424
425    - Splices lines terminated with `\'.
426
427    - Deletes comments introduced by `#' outside of single or double
428      quotes.
429
430    - Trailing whitespace will be deleted.  
431
432    Increments cust_ln as appropriate.
433
434    Returns nonzero only if a line was successfully read. */
435 int
436 ds_get_config_line (FILE *stream, struct string *st, struct file_locator *where)
437 {
438   /* Read the first line. */
439   ds_clear (st);
440   where->line_number++;
441   if (!ds_getline (st, stream))
442     return 0;
443
444   /* Read additional lines, if any. */
445   for (;;)
446     {
447       /* Remove trailing whitespace. */
448       {
449         char *s = ds_value (st);
450         size_t len = ds_length (st);
451       
452         while (len > 0 && isspace ((unsigned char) s[len - 1]))
453           len--;
454         ds_truncate (st, len);
455       }
456
457       /* Check for trailing \.  Remove if found, bail otherwise. */
458       if (ds_length (st) == 0 || ds_value (st)[ds_length (st) - 1] != '\\')
459         break;
460       ds_truncate (st, ds_length (st) - 1);
461
462       /* Append another line and go around again. */
463       {
464         int success = ds_getline (st, stream);
465         where->line_number++;
466         if (!success)
467           return 1;
468       }
469     }
470
471   /* Find a comment and remove. */
472   {
473     char *cp;
474     int quote = 0;
475       
476     for (cp = ds_value (st); *cp; cp++)
477       if (quote)
478         {
479           if (*cp == quote)
480             quote = 0;
481           else if (*cp == '\\')
482             cp++;
483         }
484       else if (*cp == '\'' || *cp == '"')
485         quote = *cp;
486       else if (*cp == '#')
487         {
488           ds_truncate (st, cp - ds_value (st));
489           break;
490         }
491   }
492
493   return 1;
494 }
495 \f
496 /* Lengthed strings. */
497
498 /* Creates a new lengthed string LS in POOL with contents as a copy of
499    S. */
500 void
501 ls_create (struct pool *pool, struct len_string *ls, const char *s)
502 {
503   ls->length = strlen (s);
504   ls->string = pool_alloc (pool, ls->length + 1);
505   memcpy (ls->string, s, ls->length + 1);
506 }
507
508 /* Creates a new lengthed string LS in POOL with contents as a copy of
509    BUFFER with length LEN. */
510 void
511 ls_create_buffer (struct pool *pool, struct len_string *ls,
512                   const char *buffer, size_t len)
513 {
514   ls->length = len;
515   ls->string = pool_malloc (pool, len + 1);
516   memcpy (ls->string, buffer, len);
517   ls->string[len] = '\0';
518 }
519
520 /* Sets the fields of LS to the specified values. */
521 void
522 ls_init (struct len_string *ls, const char *string, size_t length)
523 {
524   ls->string = (char *) string;
525   ls->length = length;
526 }
527
528 /* Copies the fields of SRC to DST. */
529 void
530 ls_shallow_copy (struct len_string *dst, const struct len_string *src)
531 {
532   *dst = *src;
533 }
534
535 /* Frees the memory in POOL backing LS. */
536 void
537 ls_destroy (struct pool *pool, struct len_string *ls)
538 {
539   pool_free (pool, ls->string);
540 }
541
542 /* Sets LS to a null pointer value. */
543 void
544 ls_null (struct len_string *ls)
545 {
546   ls->string = NULL;
547 }
548
549 /* Returns nonzero only if LS has a null pointer value. */
550 int
551 ls_null_p (const struct len_string *ls)
552 {
553   return ls->string == NULL;
554 }
555
556 /* Returns nonzero only if LS is a null pointer or has length 0. */
557 int
558 ls_empty_p (const struct len_string *ls)
559 {
560   return ls->string == NULL || ls->length == 0;
561 }
562
563 /* Returns the length of LS, which must not be null. */
564 size_t
565 ls_length (const struct len_string *ls)
566 {
567   return ls->length;
568 }
569
570 /* Returns a pointer to the character string in LS. */
571 char *
572 ls_value (const struct len_string *ls)
573 {
574   return (char *) ls->string;
575 }
576
577 /* Returns a pointer to the null terminator of the character string in
578    LS. */
579 char *
580 ls_end (const struct len_string *ls)
581 {
582   return (char *) (ls->string + ls->length);
583 }