Revert accidental commit
[platform/upstream/glib.git] / glib / gstrfuncs.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library 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 GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GLib Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
25  */
26
27 /*
28  * MT safe
29  */
30
31 #include "config.h"
32
33 #define _GNU_SOURCE             /* For stpcpy */
34
35 #include <stdarg.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <locale.h>
40 #include <errno.h>
41 #include <ctype.h>              /* For tolower() */
42 #if !defined (HAVE_STRSIGNAL) || !defined(NO_SYS_SIGLIST_DECL)
43 #include <signal.h>
44 #endif
45
46 #include "glib.h"
47 #include "gprintf.h"
48 #include "gprintfint.h"
49
50 #include "galias.h"
51
52 #ifdef G_OS_WIN32
53 #include <windows.h>
54 #endif
55
56 /* do not include <unistd.h> in this place since it
57  * interferes with g_strsignal() on some OSes
58  */
59
60 static const guint16 ascii_table_data[256] = {
61   0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004,
62   0x004, 0x104, 0x104, 0x004, 0x104, 0x104, 0x004, 0x004,
63   0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004,
64   0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004,
65   0x140, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
66   0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
67   0x459, 0x459, 0x459, 0x459, 0x459, 0x459, 0x459, 0x459,
68   0x459, 0x459, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
69   0x0d0, 0x653, 0x653, 0x653, 0x653, 0x653, 0x653, 0x253,
70   0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253,
71   0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253,
72   0x253, 0x253, 0x253, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
73   0x0d0, 0x473, 0x473, 0x473, 0x473, 0x473, 0x473, 0x073,
74   0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073,
75   0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073,
76   0x073, 0x073, 0x073, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x004
77   /* the upper 128 are all zeroes */
78 };
79
80 const guint16 * const g_ascii_table = ascii_table_data;
81
82 gchar*
83 g_strdup (const gchar *str)
84 {
85   gchar *new_str;
86   gsize length;
87
88   if (str)
89     {
90       length = strlen (str) + 1;
91       new_str = g_new (char, length);
92       memcpy (new_str, str, length);
93     }
94   else
95     new_str = NULL;
96
97   return new_str;
98 }
99
100 gpointer
101 g_memdup (gconstpointer mem,
102           guint         byte_size)
103 {
104   gpointer new_mem;
105
106   if (mem)
107     {
108       new_mem = g_malloc (byte_size);
109       memcpy (new_mem, mem, byte_size);
110     }
111   else
112     new_mem = NULL;
113
114   return new_mem;
115 }
116
117 gchar*
118 g_strndup (const gchar *str,
119            gsize        n)    
120 {
121   gchar *new_str;
122
123   if (str)
124     {
125       new_str = g_new (gchar, n + 1);
126       strncpy (new_str, str, n);
127       new_str[n] = '\0';
128     }
129   else
130     new_str = NULL;
131
132   return new_str;
133 }
134
135 gchar*
136 g_strnfill (gsize length,     
137             gchar fill_char)
138 {
139   gchar *str;
140
141   str = g_new (gchar, length + 1);
142   memset (str, (guchar)fill_char, length);
143   str[length] = '\0';
144
145   return str;
146 }
147
148 /**
149  * g_stpcpy:
150  * @dest: destination buffer.
151  * @src: source string.
152  * 
153  * Copies a nul-terminated string into the dest buffer, include the
154  * trailing nul, and return a pointer to the trailing nul byte.
155  * This is useful for concatenating multiple strings together
156  * without having to repeatedly scan for the end.
157  * 
158  * Return value: a pointer to trailing nul byte.
159  **/
160 gchar *
161 g_stpcpy (gchar       *dest,
162           const gchar *src)
163 {
164 #ifdef HAVE_STPCPY
165   g_return_val_if_fail (dest != NULL, NULL);
166   g_return_val_if_fail (src != NULL, NULL);
167   return stpcpy (dest, src);
168 #else
169   register gchar *d = dest;
170   register const gchar *s = src;
171
172   g_return_val_if_fail (dest != NULL, NULL);
173   g_return_val_if_fail (src != NULL, NULL);
174   do
175     *d++ = *s;
176   while (*s++ != '\0');
177
178   return d - 1;
179 #endif
180 }
181
182 gchar*
183 g_strdup_vprintf (const gchar *format,
184                   va_list      args)
185 {
186   gchar *string = NULL;
187
188   g_vasprintf (&string, format, args);
189
190   return string;
191 }
192
193 gchar*
194 g_strdup_printf (const gchar *format,
195                  ...)
196 {
197   gchar *buffer;
198   va_list args;
199
200   va_start (args, format);
201   buffer = g_strdup_vprintf (format, args);
202   va_end (args);
203
204   return buffer;
205 }
206
207 gchar*
208 g_strconcat (const gchar *string1, ...)
209 {
210   gsize   l;     
211   va_list args;
212   gchar   *s;
213   gchar   *concat;
214   gchar   *ptr;
215
216   if (!string1)
217     return NULL;
218
219   l = 1 + strlen (string1);
220   va_start (args, string1);
221   s = va_arg (args, gchar*);
222   while (s)
223     {
224       l += strlen (s);
225       s = va_arg (args, gchar*);
226     }
227   va_end (args);
228
229   concat = g_new (gchar, l);
230   ptr = concat;
231
232   ptr = g_stpcpy (ptr, string1);
233   va_start (args, string1);
234   s = va_arg (args, gchar*);
235   while (s)
236     {
237       ptr = g_stpcpy (ptr, s);
238       s = va_arg (args, gchar*);
239     }
240   va_end (args);
241
242   return concat;
243 }
244
245 /**
246  * g_strtod:
247  * @nptr:    the string to convert to a numeric value.
248  * @endptr:  if non-%NULL, it returns the character after
249  *           the last character used in the conversion.
250  * 
251  * Converts a string to a #gdouble value.
252  * It calls the standard strtod() function to handle the conversion, but
253  * if the string is not completely converted it attempts the conversion
254  * again with g_ascii_strtod(), and returns the best match.
255  *
256  * This function should seldomly be used. The normal situation when reading
257  * numbers not for human consumption is to use g_ascii_strtod(). Only when
258  * you know that you must expect both locale formatted and C formatted numbers
259  * should you use this. Make sure that you don't pass strings such as comma
260  * separated lists of values, since the commas may be interpreted as a decimal
261  * point in some locales, causing unexpected results.
262  * 
263  * Return value: the #gdouble value.
264  **/
265 gdouble
266 g_strtod (const gchar *nptr,
267           gchar      **endptr)
268 {
269   gchar *fail_pos_1;
270   gchar *fail_pos_2;
271   gdouble val_1;
272   gdouble val_2 = 0;
273
274   g_return_val_if_fail (nptr != NULL, 0);
275
276   fail_pos_1 = NULL;
277   fail_pos_2 = NULL;
278
279   val_1 = strtod (nptr, &fail_pos_1);
280
281   if (fail_pos_1 && fail_pos_1[0] != 0)
282     val_2 = g_ascii_strtod (nptr, &fail_pos_2);
283
284   if (!fail_pos_1 || fail_pos_1[0] == 0 || fail_pos_1 >= fail_pos_2)
285     {
286       if (endptr)
287         *endptr = fail_pos_1;
288       return val_1;
289     }
290   else
291     {
292       if (endptr)
293         *endptr = fail_pos_2;
294       return val_2;
295     }
296 }
297
298 /**
299  * g_ascii_strtod:
300  * @nptr:    the string to convert to a numeric value.
301  * @endptr:  if non-%NULL, it returns the character after
302  *           the last character used in the conversion.
303  * 
304  * Converts a string to a #gdouble value.
305  * This function behaves like the standard strtod() function
306  * does in the C locale. It does this without actually
307  * changing the current locale, since that would not be
308  * thread-safe.
309  *
310  * This function is typically used when reading configuration
311  * files or other non-user input that should be locale independent.
312  * To handle input from the user you should normally use the
313  * locale-sensitive system strtod() function.
314  *
315  * To convert from a #gdouble to a string in a locale-insensitive
316  * way, use g_ascii_dtostr().
317  *
318  * If the correct value would cause overflow, plus or minus %HUGE_VAL
319  * is returned (according to the sign of the value), and %ERANGE is
320  * stored in %errno. If the correct value would cause underflow,
321  * zero is returned and %ERANGE is stored in %errno.
322  * 
323  * This function resets %errno before calling strtod() so that
324  * you can reliably detect overflow and underflow.
325  *
326  * Return value: the #gdouble value.
327  **/
328 gdouble
329 g_ascii_strtod (const gchar *nptr,
330                 gchar      **endptr)
331 {
332   gchar *fail_pos;
333   gdouble val;
334   struct lconv *locale_data;
335   const char *decimal_point;
336   int decimal_point_len;
337   const char *p, *decimal_point_pos;
338   const char *end = NULL; /* Silence gcc */
339   int strtod_errno;
340
341   g_return_val_if_fail (nptr != NULL, 0);
342
343   fail_pos = NULL;
344
345   locale_data = localeconv ();
346   decimal_point = locale_data->decimal_point;
347   decimal_point_len = strlen (decimal_point);
348
349   g_assert (decimal_point_len != 0);
350   
351   decimal_point_pos = NULL;
352   end = NULL;
353
354   if (decimal_point[0] != '.' || 
355       decimal_point[1] != 0)
356     {
357       p = nptr;
358       /* Skip leading space */
359       while (g_ascii_isspace (*p))
360         p++;
361       
362       /* Skip leading optional sign */
363       if (*p == '+' || *p == '-')
364         p++;
365       
366       if (p[0] == '0' && 
367           (p[1] == 'x' || p[1] == 'X'))
368         {
369           p += 2;
370           /* HEX - find the (optional) decimal point */
371           
372           while (g_ascii_isxdigit (*p))
373             p++;
374           
375           if (*p == '.')
376             decimal_point_pos = p++;
377               
378           while (g_ascii_isxdigit (*p))
379             p++;
380           
381           if (*p == 'p' || *p == 'P')
382             p++;
383           if (*p == '+' || *p == '-')
384             p++;
385           while (g_ascii_isdigit (*p))
386             p++;
387
388           end = p;
389         }
390       else if (g_ascii_isdigit (*p) || *p == '.')
391         {
392           while (g_ascii_isdigit (*p))
393             p++;
394           
395           if (*p == '.')
396             decimal_point_pos = p++;
397           
398           while (g_ascii_isdigit (*p))
399             p++;
400           
401           if (*p == 'e' || *p == 'E')
402             p++;
403           if (*p == '+' || *p == '-')
404             p++;
405           while (g_ascii_isdigit (*p))
406             p++;
407
408           end = p;
409         }
410       /* For the other cases, we need not convert the decimal point */
411     }
412
413   if (decimal_point_pos)
414     {
415       char *copy, *c;
416
417       /* We need to convert the '.' to the locale specific decimal point */
418       copy = g_malloc (end - nptr + 1 + decimal_point_len);
419       
420       c = copy;
421       memcpy (c, nptr, decimal_point_pos - nptr);
422       c += decimal_point_pos - nptr;
423       memcpy (c, decimal_point, decimal_point_len);
424       c += decimal_point_len;
425       memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
426       c += end - (decimal_point_pos + 1);
427       *c = 0;
428
429       errno = 0;
430       val = strtod (copy, &fail_pos);
431       strtod_errno = errno;
432
433       if (fail_pos)
434         {
435           if (fail_pos - copy > decimal_point_pos - nptr)
436             fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
437           else
438             fail_pos = (char *)nptr + (fail_pos - copy);
439         }
440       
441       g_free (copy);
442           
443     }
444   else if (end)
445     {
446       char *copy;
447       
448       copy = g_malloc (end - (char *)nptr + 1);
449       memcpy (copy, nptr, end - nptr);
450       *(copy + (end - (char *)nptr)) = 0;
451       
452       errno = 0;
453       val = strtod (copy, &fail_pos);
454       strtod_errno = errno;
455
456       if (fail_pos)
457         {
458           fail_pos = (char *)nptr + (fail_pos - copy);
459         }
460       
461       g_free (copy);
462     }
463   else
464     {
465       errno = 0;
466       val = strtod (nptr, &fail_pos);
467       strtod_errno = errno;
468     }
469
470   if (endptr)
471     *endptr = fail_pos;
472
473   errno = strtod_errno;
474
475   return val;
476 }
477
478
479 /**
480  * g_ascii_dtostr:
481  * @buffer: A buffer to place the resulting string in
482  * @buf_len: The length of the buffer.
483  * @d: The #gdouble to convert
484  *
485  * Converts a #gdouble to a string, using the '.' as
486  * decimal point. 
487  * 
488  * This functions generates enough precision that converting
489  * the string back using g_ascii_strtod() gives the same machine-number
490  * (on machines with IEEE compatible 64bit doubles). It is
491  * guaranteed that the size of the resulting string will never
492  * be larger than @G_ASCII_DTOSTR_BUF_SIZE bytes.
493  *
494  * Return value: The pointer to the buffer with the converted string.
495  **/
496 gchar *
497 g_ascii_dtostr (gchar       *buffer,
498                 gint         buf_len,
499                 gdouble      d)
500 {
501   return g_ascii_formatd (buffer, buf_len, "%.17g", d);
502 }
503
504 /**
505  * g_ascii_formatd:
506  * @buffer: A buffer to place the resulting string in
507  * @buf_len: The length of the buffer.
508  * @format: The printf()-style format to use for the
509  *          code to use for converting. 
510  * @d: The #gdouble to convert
511  *
512  * Converts a #gdouble to a string, using the '.' as
513  * decimal point. To format the number you pass in
514  * a printf()-style format string. Allowed conversion
515  * specifiers are 'e', 'E', 'f', 'F', 'g' and 'G'. 
516  * 
517  * If you just want to want to serialize the value into a
518  * string, use g_ascii_dtostr().
519  *
520  * Return value: The pointer to the buffer with the converted string.
521  **/
522 gchar *
523 g_ascii_formatd (gchar       *buffer,
524                  gint         buf_len,
525                  const gchar *format,
526                  gdouble      d)
527 {
528   struct lconv *locale_data;
529   const char *decimal_point;
530   int decimal_point_len;
531   gchar *p;
532   int rest_len;
533   gchar format_char;
534
535   g_return_val_if_fail (buffer != NULL, NULL);
536   g_return_val_if_fail (format[0] == '%', NULL);
537   g_return_val_if_fail (strpbrk (format + 1, "'l%") == NULL, NULL);
538  
539   format_char = format[strlen (format) - 1];
540   
541   g_return_val_if_fail (format_char == 'e' || format_char == 'E' ||
542                         format_char == 'f' || format_char == 'F' ||
543                         format_char == 'g' || format_char == 'G',
544                         NULL);
545
546   if (format[0] != '%')
547     return NULL;
548
549   if (strpbrk (format + 1, "'l%"))
550     return NULL;
551
552   if (!(format_char == 'e' || format_char == 'E' ||
553         format_char == 'f' || format_char == 'F' ||
554         format_char == 'g' || format_char == 'G'))
555     return NULL;
556
557       
558   _g_snprintf (buffer, buf_len, format, d);
559
560   locale_data = localeconv ();
561   decimal_point = locale_data->decimal_point;
562   decimal_point_len = strlen (decimal_point);
563
564   g_assert (decimal_point_len != 0);
565
566   if (decimal_point[0] != '.' ||
567       decimal_point[1] != 0)
568     {
569       p = buffer;
570
571       while (g_ascii_isspace (*p))
572         p++;
573
574       if (*p == '+' || *p == '-')
575         p++;
576
577       while (isdigit ((guchar)*p))
578         p++;
579
580       if (strncmp (p, decimal_point, decimal_point_len) == 0)
581         {
582           *p = '.';
583           p++;
584           if (decimal_point_len > 1) {
585             rest_len = strlen (p + (decimal_point_len-1));
586             memmove (p, p + (decimal_point_len-1),
587                      rest_len);
588             p[rest_len] = 0;
589             
590           }
591         }
592     }
593   
594   return buffer;
595 }
596
597 static guint64
598 g_parse_long_long (const gchar *nptr,
599                    gchar      **endptr,
600                    guint        base,
601                    gboolean    *negative)
602 {
603   /* this code is based on on the strtol(3) code from GNU libc released under
604    * the GNU Lesser General Public License.
605    *
606    * Copyright (C) 1991,92,94,95,96,97,98,99,2000,01,02
607    *        Free Software Foundation, Inc.
608    */
609 #define ISSPACE(c)              ((c) == ' ' || (c) == '\f' || (c) == '\n' || \
610                                  (c) == '\r' || (c) == '\t' || (c) == '\v')
611 #define ISUPPER(c)              ((c) >= 'A' && (c) <= 'Z')
612 #define ISLOWER(c)              ((c) >= 'a' && (c) <= 'z')
613 #define ISALPHA(c)              (ISUPPER (c) || ISLOWER (c))
614 #define TOUPPER(c)              (ISLOWER (c) ? (c) - 'a' + 'A' : (c))
615 #define TOLOWER(c)              (ISUPPER (c) ? (c) - 'A' + 'a' : (c))
616   gboolean overflow;
617   guint64 cutoff;
618   guint64 cutlim;
619   guint64 ui64;
620   const gchar *s, *save;
621   guchar c;
622   
623   g_return_val_if_fail (nptr != NULL, 0);
624   
625   if (base == 1 || base > 36)
626     {
627       errno = EINVAL;
628       return 0;
629     }
630   
631   save = s = nptr;
632   
633   /* Skip white space.  */
634   while (ISSPACE (*s))
635     ++s;
636
637   if (G_UNLIKELY (!*s))
638     goto noconv;
639   
640   /* Check for a sign.  */
641   *negative = FALSE;
642   if (*s == '-')
643     {
644       *negative = TRUE;
645       ++s;
646     }
647   else if (*s == '+')
648     ++s;
649   
650   /* Recognize number prefix and if BASE is zero, figure it out ourselves.  */
651   if (*s == '0')
652     {
653       if ((base == 0 || base == 16) && TOUPPER (s[1]) == 'X')
654         {
655           s += 2;
656           base = 16;
657         }
658       else if (base == 0)
659         base = 8;
660     }
661   else if (base == 0)
662     base = 10;
663   
664   /* Save the pointer so we can check later if anything happened.  */
665   save = s;
666   cutoff = G_MAXUINT64 / base;
667   cutlim = G_MAXUINT64 % base;
668   
669   overflow = FALSE;
670   ui64 = 0;
671   c = *s;
672   for (; c; c = *++s)
673     {
674       if (c >= '0' && c <= '9')
675         c -= '0';
676       else if (ISALPHA (c))
677         c = TOUPPER (c) - 'A' + 10;
678       else
679         break;
680       if (c >= base)
681         break;
682       /* Check for overflow.  */
683       if (ui64 > cutoff || (ui64 == cutoff && c > cutlim))
684         overflow = TRUE;
685       else
686         {
687           ui64 *= base;
688           ui64 += c;
689         }
690     }
691   
692   /* Check if anything actually happened.  */
693   if (s == save)
694     goto noconv;
695   
696   /* Store in ENDPTR the address of one character
697      past the last character we converted.  */
698   if (endptr)
699     *endptr = (gchar*) s;
700   
701   if (G_UNLIKELY (overflow))
702     {
703       errno = ERANGE;
704       return G_MAXUINT64;
705     }
706
707   return ui64;
708   
709  noconv:
710   /* We must handle a special case here: the base is 0 or 16 and the
711      first two characters are '0' and 'x', but the rest are no
712      hexadecimal digits.  This is no error case.  We return 0 and
713      ENDPTR points to the `x`.  */
714   if (endptr)
715     {
716       if (save - nptr >= 2 && TOUPPER (save[-1]) == 'X'
717           && save[-2] == '0')
718         *endptr = (gchar*) &save[-1];
719       else
720         /*  There was no number to convert.  */
721         *endptr = (gchar*) nptr;
722     }
723   return 0;
724 }
725
726 /**
727  * g_ascii_strtoull:
728  * @nptr:    the string to convert to a numeric value.
729  * @endptr:  if non-%NULL, it returns the character after
730  *           the last character used in the conversion.
731  * @base:    to be used for the conversion, 2..36 or 0
732  *
733  * Converts a string to a #guint64 value.
734  * This function behaves like the standard strtoull() function
735  * does in the C locale. It does this without actually
736  * changing the current locale, since that would not be
737  * thread-safe.
738  *
739  * This function is typically used when reading configuration
740  * files or other non-user input that should be locale independent.
741  * To handle input from the user you should normally use the
742  * locale-sensitive system strtoull() function.
743  *
744  * If the correct value would cause overflow, %G_MAXUINT64
745  * is returned, and %ERANGE is stored in %errno.  If the base is
746  * outside the valid range, zero is returned, and %EINVAL is stored
747  * in %errno.  If the string conversion fails, zero is returned, and
748  * @endptr returns @nptr (if @endptr is non-%NULL).
749  *
750  * Return value: the #guint64 value or zero on error.
751  *
752  * Since: 2.2
753  **/
754 guint64
755 g_ascii_strtoull (const gchar *nptr,
756                   gchar      **endptr,
757                   guint        base)
758 {
759   gboolean negative;
760   guint64 result;
761
762   result = g_parse_long_long (nptr, endptr, base, &negative);
763
764   /* Return the result of the appropriate sign.  */
765   return negative ? -result : result;
766 }
767
768 /**
769  * g_ascii_strtoll:
770  * @nptr:    the string to convert to a numeric value.
771  * @endptr:  if non-%NULL, it returns the character after
772  *           the last character used in the conversion.
773  * @base:    to be used for the conversion, 2..36 or 0
774  *
775  * Converts a string to a #gint64 value.
776  * This function behaves like the standard strtoll() function
777  * does in the C locale. It does this without actually
778  * changing the current locale, since that would not be
779  * thread-safe.
780  *
781  * This function is typically used when reading configuration
782  * files or other non-user input that should be locale independent.
783  * To handle input from the user you should normally use the
784  * locale-sensitive system strtoll() function.
785  *
786  * If the correct value would cause overflow, %G_MAXINT64 or %G_MININT64
787  * is returned, and %ERANGE is stored in %errno.  If the base is
788  * outside the valid range, zero is returned, and %EINVAL is stored
789  * in %errno.  If the string conversion fails, zero is returned, and
790  * @endptr returns @nptr (if @endptr is non-%NULL).
791  *
792  * Return value: the #gint64 value or zero on error.
793  *
794  * Since: 2.12
795  **/
796 gint64 
797 g_ascii_strtoll (const gchar *nptr,
798                  gchar      **endptr,
799                  guint        base)
800 {
801   gboolean negative;
802   guint64 result;
803
804   result = g_parse_long_long (nptr, endptr, base, &negative);
805
806   if (negative && result > (guint64) G_MININT64)
807     {
808       errno = ERANGE;
809       return G_MININT64;
810     }
811   else if (!negative && result > (guint64) G_MAXINT64)
812     {
813       errno = ERANGE;
814       return G_MAXINT64;
815     }
816   else
817     return (gint64) result;
818 }
819
820 G_CONST_RETURN gchar*
821 g_strerror (gint errnum)
822 {
823   static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
824   char *msg;
825   int saved_errno = errno;
826
827 #ifdef HAVE_STRERROR
828   const char *msg_locale;
829
830   msg_locale = strerror (errnum);
831   if (g_get_charset (NULL))
832     {
833       errno = saved_errno;
834       return msg_locale;
835     }
836   else
837     {
838       gchar *msg_utf8 = g_locale_to_utf8 (msg_locale, -1, NULL, NULL, NULL);
839       if (msg_utf8)
840         {
841           /* Stick in the quark table so that we can return a static result
842            */
843           GQuark msg_quark = g_quark_from_string (msg_utf8);
844           g_free (msg_utf8);
845           
846           msg_utf8 = (gchar *) g_quark_to_string (msg_quark);
847           errno = saved_errno;
848           return msg_utf8;
849         }
850     }
851 #elif NO_SYS_ERRLIST
852   switch (errnum)
853     {
854 #ifdef E2BIG
855     case E2BIG: return "argument list too long";
856 #endif
857 #ifdef EACCES
858     case EACCES: return "permission denied";
859 #endif
860 #ifdef EADDRINUSE
861     case EADDRINUSE: return "address already in use";
862 #endif
863 #ifdef EADDRNOTAVAIL
864     case EADDRNOTAVAIL: return "can't assign requested address";
865 #endif
866 #ifdef EADV
867     case EADV: return "advertise error";
868 #endif
869 #ifdef EAFNOSUPPORT
870     case EAFNOSUPPORT: return "address family not supported by protocol family";
871 #endif
872 #ifdef EAGAIN
873     case EAGAIN: return "try again";
874 #endif
875 #ifdef EALIGN
876     case EALIGN: return "EALIGN";
877 #endif
878 #ifdef EALREADY
879     case EALREADY: return "operation already in progress";
880 #endif
881 #ifdef EBADE
882     case EBADE: return "bad exchange descriptor";
883 #endif
884 #ifdef EBADF
885     case EBADF: return "bad file number";
886 #endif
887 #ifdef EBADFD
888     case EBADFD: return "file descriptor in bad state";
889 #endif
890 #ifdef EBADMSG
891     case EBADMSG: return "not a data message";
892 #endif
893 #ifdef EBADR
894     case EBADR: return "bad request descriptor";
895 #endif
896 #ifdef EBADRPC
897     case EBADRPC: return "RPC structure is bad";
898 #endif
899 #ifdef EBADRQC
900     case EBADRQC: return "bad request code";
901 #endif
902 #ifdef EBADSLT
903     case EBADSLT: return "invalid slot";
904 #endif
905 #ifdef EBFONT
906     case EBFONT: return "bad font file format";
907 #endif
908 #ifdef EBUSY
909     case EBUSY: return "mount device busy";
910 #endif
911 #ifdef ECHILD
912     case ECHILD: return "no children";
913 #endif
914 #ifdef ECHRNG
915     case ECHRNG: return "channel number out of range";
916 #endif
917 #ifdef ECOMM
918     case ECOMM: return "communication error on send";
919 #endif
920 #ifdef ECONNABORTED
921     case ECONNABORTED: return "software caused connection abort";
922 #endif
923 #ifdef ECONNREFUSED
924     case ECONNREFUSED: return "connection refused";
925 #endif
926 #ifdef ECONNRESET
927     case ECONNRESET: return "connection reset by peer";
928 #endif
929 #if defined(EDEADLK) && (!defined(EWOULDBLOCK) || (EDEADLK != EWOULDBLOCK))
930     case EDEADLK: return "resource deadlock avoided";
931 #endif
932 #ifdef EDEADLOCK
933     case EDEADLOCK: return "resource deadlock avoided";
934 #endif
935 #ifdef EDESTADDRREQ
936     case EDESTADDRREQ: return "destination address required";
937 #endif
938 #ifdef EDIRTY
939     case EDIRTY: return "mounting a dirty fs w/o force";
940 #endif
941 #ifdef EDOM
942     case EDOM: return "math argument out of range";
943 #endif
944 #ifdef EDOTDOT
945     case EDOTDOT: return "cross mount point";
946 #endif
947 #ifdef EDQUOT
948     case EDQUOT: return "disk quota exceeded";
949 #endif
950 #ifdef EDUPPKG
951     case EDUPPKG: return "duplicate package name";
952 #endif
953 #ifdef EEXIST
954     case EEXIST: return "file already exists";
955 #endif
956 #ifdef EFAULT
957     case EFAULT: return "bad address in system call argument";
958 #endif
959 #ifdef EFBIG
960     case EFBIG: return "file too large";
961 #endif
962 #ifdef EHOSTDOWN
963     case EHOSTDOWN: return "host is down";
964 #endif
965 #ifdef EHOSTUNREACH
966     case EHOSTUNREACH: return "host is unreachable";
967 #endif
968 #ifdef EIDRM
969     case EIDRM: return "identifier removed";
970 #endif
971 #ifdef EINIT
972     case EINIT: return "initialization error";
973 #endif
974 #ifdef EINPROGRESS
975     case EINPROGRESS: return "operation now in progress";
976 #endif
977 #ifdef EINTR
978     case EINTR: return "interrupted system call";
979 #endif
980 #ifdef EINVAL
981     case EINVAL: return "invalid argument";
982 #endif
983 #ifdef EIO
984     case EIO: return "I/O error";
985 #endif
986 #ifdef EISCONN
987     case EISCONN: return "socket is already connected";
988 #endif
989 #ifdef EISDIR
990     case EISDIR: return "is a directory";
991 #endif
992 #ifdef EISNAME
993     case EISNAM: return "is a name file";
994 #endif
995 #ifdef ELBIN
996     case ELBIN: return "ELBIN";
997 #endif
998 #ifdef EL2HLT
999     case EL2HLT: return "level 2 halted";
1000 #endif
1001 #ifdef EL2NSYNC
1002     case EL2NSYNC: return "level 2 not synchronized";
1003 #endif
1004 #ifdef EL3HLT
1005     case EL3HLT: return "level 3 halted";
1006 #endif
1007 #ifdef EL3RST
1008     case EL3RST: return "level 3 reset";
1009 #endif
1010 #ifdef ELIBACC
1011     case ELIBACC: return "can not access a needed shared library";
1012 #endif
1013 #ifdef ELIBBAD
1014     case ELIBBAD: return "accessing a corrupted shared library";
1015 #endif
1016 #ifdef ELIBEXEC
1017     case ELIBEXEC: return "can not exec a shared library directly";
1018 #endif
1019 #ifdef ELIBMAX
1020     case ELIBMAX: return "attempting to link in more shared libraries than system limit";
1021 #endif
1022 #ifdef ELIBSCN
1023     case ELIBSCN: return ".lib section in a.out corrupted";
1024 #endif
1025 #ifdef ELNRNG
1026     case ELNRNG: return "link number out of range";
1027 #endif
1028 #ifdef ELOOP
1029     case ELOOP: return "too many levels of symbolic links";
1030 #endif
1031 #ifdef EMFILE
1032     case EMFILE: return "too many open files";
1033 #endif
1034 #ifdef EMLINK
1035     case EMLINK: return "too many links";
1036 #endif
1037 #ifdef EMSGSIZE
1038     case EMSGSIZE: return "message too long";
1039 #endif
1040 #ifdef EMULTIHOP
1041     case EMULTIHOP: return "multihop attempted";
1042 #endif
1043 #ifdef ENAMETOOLONG
1044     case ENAMETOOLONG: return "file name too long";
1045 #endif
1046 #ifdef ENAVAIL
1047     case ENAVAIL: return "not available";
1048 #endif
1049 #ifdef ENET
1050     case ENET: return "ENET";
1051 #endif
1052 #ifdef ENETDOWN
1053     case ENETDOWN: return "network is down";
1054 #endif
1055 #ifdef ENETRESET
1056     case ENETRESET: return "network dropped connection on reset";
1057 #endif
1058 #ifdef ENETUNREACH
1059     case ENETUNREACH: return "network is unreachable";
1060 #endif
1061 #ifdef ENFILE
1062     case ENFILE: return "file table overflow";
1063 #endif
1064 #ifdef ENOANO
1065     case ENOANO: return "anode table overflow";
1066 #endif
1067 #if defined(ENOBUFS) && (!defined(ENOSR) || (ENOBUFS != ENOSR))
1068     case ENOBUFS: return "no buffer space available";
1069 #endif
1070 #ifdef ENOCSI
1071     case ENOCSI: return "no CSI structure available";
1072 #endif
1073 #ifdef ENODATA
1074     case ENODATA: return "no data available";
1075 #endif
1076 #ifdef ENODEV
1077     case ENODEV: return "no such device";
1078 #endif
1079 #ifdef ENOENT
1080     case ENOENT: return "no such file or directory";
1081 #endif
1082 #ifdef ENOEXEC
1083     case ENOEXEC: return "exec format error";
1084 #endif
1085 #ifdef ENOLCK
1086     case ENOLCK: return "no locks available";
1087 #endif
1088 #ifdef ENOLINK
1089     case ENOLINK: return "link has be severed";
1090 #endif
1091 #ifdef ENOMEM
1092     case ENOMEM: return "not enough memory";
1093 #endif
1094 #ifdef ENOMSG
1095     case ENOMSG: return "no message of desired type";
1096 #endif
1097 #ifdef ENONET
1098     case ENONET: return "machine is not on the network";
1099 #endif
1100 #ifdef ENOPKG
1101     case ENOPKG: return "package not installed";
1102 #endif
1103 #ifdef ENOPROTOOPT
1104     case ENOPROTOOPT: return "bad proocol option";
1105 #endif
1106 #ifdef ENOSPC
1107     case ENOSPC: return "no space left on device";
1108 #endif
1109 #ifdef ENOSR
1110     case ENOSR: return "out of stream resources";
1111 #endif
1112 #ifdef ENOSTR
1113     case ENOSTR: return "not a stream device";
1114 #endif
1115 #ifdef ENOSYM
1116     case ENOSYM: return "unresolved symbol name";
1117 #endif
1118 #ifdef ENOSYS
1119     case ENOSYS: return "function not implemented";
1120 #endif
1121 #ifdef ENOTBLK
1122     case ENOTBLK: return "block device required";
1123 #endif
1124 #ifdef ENOTCONN
1125     case ENOTCONN: return "socket is not connected";
1126 #endif
1127 #ifdef ENOTDIR
1128     case ENOTDIR: return "not a directory";
1129 #endif
1130 #ifdef ENOTEMPTY
1131     case ENOTEMPTY: return "directory not empty";
1132 #endif
1133 #ifdef ENOTNAM
1134     case ENOTNAM: return "not a name file";
1135 #endif
1136 #ifdef ENOTSOCK
1137     case ENOTSOCK: return "socket operation on non-socket";
1138 #endif
1139 #ifdef ENOTTY
1140     case ENOTTY: return "inappropriate device for ioctl";
1141 #endif
1142 #ifdef ENOTUNIQ
1143     case ENOTUNIQ: return "name not unique on network";
1144 #endif
1145 #ifdef ENXIO
1146     case ENXIO: return "no such device or address";
1147 #endif
1148 #ifdef EOPNOTSUPP
1149     case EOPNOTSUPP: return "operation not supported on socket";
1150 #endif
1151 #ifdef EPERM
1152     case EPERM: return "not owner";
1153 #endif
1154 #ifdef EPFNOSUPPORT
1155     case EPFNOSUPPORT: return "protocol family not supported";
1156 #endif
1157 #ifdef EPIPE
1158     case EPIPE: return "broken pipe";
1159 #endif
1160 #ifdef EPROCLIM
1161     case EPROCLIM: return "too many processes";
1162 #endif
1163 #ifdef EPROCUNAVAIL
1164     case EPROCUNAVAIL: return "bad procedure for program";
1165 #endif
1166 #ifdef EPROGMISMATCH
1167     case EPROGMISMATCH: return "program version wrong";
1168 #endif
1169 #ifdef EPROGUNAVAIL
1170     case EPROGUNAVAIL: return "RPC program not available";
1171 #endif
1172 #ifdef EPROTO
1173     case EPROTO: return "protocol error";
1174 #endif
1175 #ifdef EPROTONOSUPPORT
1176     case EPROTONOSUPPORT: return "protocol not suppored";
1177 #endif
1178 #ifdef EPROTOTYPE
1179     case EPROTOTYPE: return "protocol wrong type for socket";
1180 #endif
1181 #ifdef ERANGE
1182     case ERANGE: return "math result unrepresentable";
1183 #endif
1184 #if defined(EREFUSED) && (!defined(ECONNREFUSED) || (EREFUSED != ECONNREFUSED))
1185     case EREFUSED: return "EREFUSED";
1186 #endif
1187 #ifdef EREMCHG
1188     case EREMCHG: return "remote address changed";
1189 #endif
1190 #ifdef EREMDEV
1191     case EREMDEV: return "remote device";
1192 #endif
1193 #ifdef EREMOTE
1194     case EREMOTE: return "pathname hit remote file system";
1195 #endif
1196 #ifdef EREMOTEIO
1197     case EREMOTEIO: return "remote i/o error";
1198 #endif
1199 #ifdef EREMOTERELEASE
1200     case EREMOTERELEASE: return "EREMOTERELEASE";
1201 #endif
1202 #ifdef EROFS
1203     case EROFS: return "read-only file system";
1204 #endif
1205 #ifdef ERPCMISMATCH
1206     case ERPCMISMATCH: return "RPC version is wrong";
1207 #endif
1208 #ifdef ERREMOTE
1209     case ERREMOTE: return "object is remote";
1210 #endif
1211 #ifdef ESHUTDOWN
1212     case ESHUTDOWN: return "can't send afer socket shutdown";
1213 #endif
1214 #ifdef ESOCKTNOSUPPORT
1215     case ESOCKTNOSUPPORT: return "socket type not supported";
1216 #endif
1217 #ifdef ESPIPE
1218     case ESPIPE: return "invalid seek";
1219 #endif
1220 #ifdef ESRCH
1221     case ESRCH: return "no such process";
1222 #endif
1223 #ifdef ESRMNT
1224     case ESRMNT: return "srmount error";
1225 #endif
1226 #ifdef ESTALE
1227     case ESTALE: return "stale remote file handle";
1228 #endif
1229 #ifdef ESUCCESS
1230     case ESUCCESS: return "Error 0";
1231 #endif
1232 #ifdef ETIME
1233     case ETIME: return "timer expired";
1234 #endif
1235 #ifdef ETIMEDOUT
1236     case ETIMEDOUT: return "connection timed out";
1237 #endif
1238 #ifdef ETOOMANYREFS
1239     case ETOOMANYREFS: return "too many references: can't splice";
1240 #endif
1241 #ifdef ETXTBSY
1242     case ETXTBSY: return "text file or pseudo-device busy";
1243 #endif
1244 #ifdef EUCLEAN
1245     case EUCLEAN: return "structure needs cleaning";
1246 #endif
1247 #ifdef EUNATCH
1248     case EUNATCH: return "protocol driver not attached";
1249 #endif
1250 #ifdef EUSERS
1251     case EUSERS: return "too many users";
1252 #endif
1253 #ifdef EVERSION
1254     case EVERSION: return "version mismatch";
1255 #endif
1256 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1257     case EWOULDBLOCK: return "operation would block";
1258 #endif
1259 #ifdef EXDEV
1260     case EXDEV: return "cross-domain link";
1261 #endif
1262 #ifdef EXFULL
1263     case EXFULL: return "message tables full";
1264 #endif
1265     }
1266 #else /* NO_SYS_ERRLIST */
1267   extern int sys_nerr;
1268   extern char *sys_errlist[];
1269
1270   if ((errnum > 0) && (errnum <= sys_nerr))
1271     return sys_errlist [errnum];
1272 #endif /* NO_SYS_ERRLIST */
1273
1274   msg = g_static_private_get (&msg_private);
1275   if (!msg)
1276     {
1277       msg = g_new (gchar, 64);
1278       g_static_private_set (&msg_private, msg, g_free);
1279     }
1280
1281   _g_sprintf (msg, "unknown error (%d)", errnum);
1282
1283   errno = saved_errno;
1284   return msg;
1285 }
1286
1287 G_CONST_RETURN gchar*
1288 g_strsignal (gint signum)
1289 {
1290   static GStaticPrivate msg_private = G_STATIC_PRIVATE_INIT;
1291   char *msg;
1292
1293 #ifdef HAVE_STRSIGNAL
1294   const char *msg_locale;
1295   
1296 #if defined(G_OS_BEOS) || defined(G_WITH_CYGWIN)
1297 extern const char *strsignal(int);
1298 #else
1299   /* this is declared differently (const) in string.h on BeOS */
1300   extern char *strsignal (int sig);
1301 #endif /* !G_OS_BEOS && !G_WITH_CYGWIN */
1302   msg_locale = strsignal (signum);
1303   if (g_get_charset (NULL))
1304     return msg_locale;
1305   else
1306     {
1307       gchar *msg_utf8 = g_locale_to_utf8 (msg_locale, -1, NULL, NULL, NULL);
1308       if (msg_utf8)
1309         {
1310           /* Stick in the quark table so that we can return a static result
1311            */
1312           GQuark msg_quark = g_quark_from_string (msg_utf8);
1313           g_free (msg_utf8);
1314           
1315           return g_quark_to_string (msg_quark);
1316         }
1317     }
1318 #elif NO_SYS_SIGLIST
1319   switch (signum)
1320     {
1321 #ifdef SIGHUP
1322     case SIGHUP: return "Hangup";
1323 #endif
1324 #ifdef SIGINT
1325     case SIGINT: return "Interrupt";
1326 #endif
1327 #ifdef SIGQUIT
1328     case SIGQUIT: return "Quit";
1329 #endif
1330 #ifdef SIGILL
1331     case SIGILL: return "Illegal instruction";
1332 #endif
1333 #ifdef SIGTRAP
1334     case SIGTRAP: return "Trace/breakpoint trap";
1335 #endif
1336 #ifdef SIGABRT
1337     case SIGABRT: return "IOT trap/Abort";
1338 #endif
1339 #ifdef SIGBUS
1340     case SIGBUS: return "Bus error";
1341 #endif
1342 #ifdef SIGFPE
1343     case SIGFPE: return "Floating point exception";
1344 #endif
1345 #ifdef SIGKILL
1346     case SIGKILL: return "Killed";
1347 #endif
1348 #ifdef SIGUSR1
1349     case SIGUSR1: return "User defined signal 1";
1350 #endif
1351 #ifdef SIGSEGV
1352     case SIGSEGV: return "Segmentation fault";
1353 #endif
1354 #ifdef SIGUSR2
1355     case SIGUSR2: return "User defined signal 2";
1356 #endif
1357 #ifdef SIGPIPE
1358     case SIGPIPE: return "Broken pipe";
1359 #endif
1360 #ifdef SIGALRM
1361     case SIGALRM: return "Alarm clock";
1362 #endif
1363 #ifdef SIGTERM
1364     case SIGTERM: return "Terminated";
1365 #endif
1366 #ifdef SIGSTKFLT
1367     case SIGSTKFLT: return "Stack fault";
1368 #endif
1369 #ifdef SIGCHLD
1370     case SIGCHLD: return "Child exited";
1371 #endif
1372 #ifdef SIGCONT
1373     case SIGCONT: return "Continued";
1374 #endif
1375 #ifdef SIGSTOP
1376     case SIGSTOP: return "Stopped (signal)";
1377 #endif
1378 #ifdef SIGTSTP
1379     case SIGTSTP: return "Stopped";
1380 #endif
1381 #ifdef SIGTTIN
1382     case SIGTTIN: return "Stopped (tty input)";
1383 #endif
1384 #ifdef SIGTTOU
1385     case SIGTTOU: return "Stopped (tty output)";
1386 #endif
1387 #ifdef SIGURG
1388     case SIGURG: return "Urgent condition";
1389 #endif
1390 #ifdef SIGXCPU
1391     case SIGXCPU: return "CPU time limit exceeded";
1392 #endif
1393 #ifdef SIGXFSZ
1394     case SIGXFSZ: return "File size limit exceeded";
1395 #endif
1396 #ifdef SIGVTALRM
1397     case SIGVTALRM: return "Virtual time alarm";
1398 #endif
1399 #ifdef SIGPROF
1400     case SIGPROF: return "Profile signal";
1401 #endif
1402 #ifdef SIGWINCH
1403     case SIGWINCH: return "Window size changed";
1404 #endif
1405 #ifdef SIGIO
1406     case SIGIO: return "Possible I/O";
1407 #endif
1408 #ifdef SIGPWR
1409     case SIGPWR: return "Power failure";
1410 #endif
1411 #ifdef SIGUNUSED
1412     case SIGUNUSED: return "Unused signal";
1413 #endif
1414     }
1415 #else /* NO_SYS_SIGLIST */
1416
1417 #ifdef NO_SYS_SIGLIST_DECL
1418   extern char *sys_siglist[];   /*(see Tue Jan 19 00:44:24 1999 in changelog)*/
1419 #endif
1420
1421   return (char*) /* this function should return const --josh */ sys_siglist [signum];
1422 #endif /* NO_SYS_SIGLIST */
1423
1424   msg = g_static_private_get (&msg_private);
1425   if (!msg)
1426     {
1427       msg = g_new (gchar, 64);
1428       g_static_private_set (&msg_private, msg, g_free);
1429     }
1430
1431   _g_sprintf (msg, "unknown signal (%d)", signum);
1432   
1433   return msg;
1434 }
1435
1436 /* Functions g_strlcpy and g_strlcat were originally developed by
1437  * Todd C. Miller <Todd.Miller@courtesan.com> to simplify writing secure code.
1438  * See ftp://ftp.openbsd.org/pub/OpenBSD/src/lib/libc/string/strlcpy.3
1439  * for more information.
1440  */
1441
1442 #ifdef HAVE_STRLCPY
1443 /* Use the native ones, if available; they might be implemented in assembly */
1444 gsize
1445 g_strlcpy (gchar       *dest,
1446            const gchar *src,
1447            gsize        dest_size)
1448 {
1449   g_return_val_if_fail (dest != NULL, 0);
1450   g_return_val_if_fail (src  != NULL, 0);
1451   
1452   return strlcpy (dest, src, dest_size);
1453 }
1454
1455 gsize
1456 g_strlcat (gchar       *dest,
1457            const gchar *src,
1458            gsize        dest_size)
1459 {
1460   g_return_val_if_fail (dest != NULL, 0);
1461   g_return_val_if_fail (src  != NULL, 0);
1462   
1463   return strlcat (dest, src, dest_size);
1464 }
1465
1466 #else /* ! HAVE_STRLCPY */
1467 /* g_strlcpy
1468  *
1469  * Copy string src to buffer dest (of buffer size dest_size).  At most
1470  * dest_size-1 characters will be copied.  Always NUL terminates
1471  * (unless dest_size == 0).  This function does NOT allocate memory.
1472  * Unlike strncpy, this function doesn't pad dest (so it's often faster).
1473  * Returns size of attempted result, strlen(src),
1474  * so if retval >= dest_size, truncation occurred.
1475  */
1476 gsize
1477 g_strlcpy (gchar       *dest,
1478            const gchar *src,
1479            gsize        dest_size)
1480 {
1481   register gchar *d = dest;
1482   register const gchar *s = src;
1483   register gsize n = dest_size;
1484   
1485   g_return_val_if_fail (dest != NULL, 0);
1486   g_return_val_if_fail (src  != NULL, 0);
1487   
1488   /* Copy as many bytes as will fit */
1489   if (n != 0 && --n != 0)
1490     do
1491       {
1492         register gchar c = *s++;
1493         
1494         *d++ = c;
1495         if (c == 0)
1496           break;
1497       }
1498     while (--n != 0);
1499   
1500   /* If not enough room in dest, add NUL and traverse rest of src */
1501   if (n == 0)
1502     {
1503       if (dest_size != 0)
1504         *d = 0;
1505       while (*s++)
1506         ;
1507     }
1508   
1509   return s - src - 1;  /* count does not include NUL */
1510 }
1511
1512 /* g_strlcat
1513  *
1514  * Appends string src to buffer dest (of buffer size dest_size).
1515  * At most dest_size-1 characters will be copied.
1516  * Unlike strncat, dest_size is the full size of dest, not the space left over.
1517  * This function does NOT allocate memory.
1518  * This always NUL terminates (unless siz == 0 or there were no NUL characters
1519  * in the dest_size characters of dest to start with).
1520  * Returns size of attempted result, which is
1521  * MIN (dest_size, strlen (original dest)) + strlen (src),
1522  * so if retval >= dest_size, truncation occurred.
1523  */
1524 gsize
1525 g_strlcat (gchar       *dest,
1526            const gchar *src,
1527            gsize        dest_size)
1528 {
1529   register gchar *d = dest;
1530   register const gchar *s = src;
1531   register gsize bytes_left = dest_size;
1532   gsize dlength;  /* Logically, MIN (strlen (d), dest_size) */
1533   
1534   g_return_val_if_fail (dest != NULL, 0);
1535   g_return_val_if_fail (src  != NULL, 0);
1536   
1537   /* Find the end of dst and adjust bytes left but don't go past end */
1538   while (*d != 0 && bytes_left-- != 0)
1539     d++;
1540   dlength = d - dest;
1541   bytes_left = dest_size - dlength;
1542   
1543   if (bytes_left == 0)
1544     return dlength + strlen (s);
1545   
1546   while (*s != 0)
1547     {
1548       if (bytes_left != 1)
1549         {
1550           *d++ = *s;
1551           bytes_left--;
1552         }
1553       s++;
1554     }
1555   *d = 0;
1556   
1557   return dlength + (s - src);  /* count does not include NUL */
1558 }
1559 #endif /* ! HAVE_STRLCPY */
1560
1561 /**
1562  * g_ascii_strdown:
1563  * @str: a string.
1564  * @len: length of @str in bytes, or -1 if @str is nul-terminated.
1565  * 
1566  * Converts all upper case ASCII letters to lower case ASCII letters.
1567  * 
1568  * Return value: a newly-allocated string, with all the upper case
1569  *               characters in @str converted to lower case, with
1570  *               semantics that exactly match g_ascii_tolower(). (Note
1571  *               that this is unlike the old g_strdown(), which modified
1572  *               the string in place.)
1573  **/
1574 gchar*
1575 g_ascii_strdown (const gchar *str,
1576                  gssize       len)
1577 {
1578   gchar *result, *s;
1579   
1580   g_return_val_if_fail (str != NULL, NULL);
1581
1582   if (len < 0)
1583     len = strlen (str);
1584
1585   result = g_strndup (str, len);
1586   for (s = result; *s; s++)
1587     *s = g_ascii_tolower (*s);
1588   
1589   return result;
1590 }
1591
1592 /**
1593  * g_ascii_strup:
1594  * @str: a string.
1595  * @len: length of @str in bytes, or -1 if @str is nul-terminated.
1596  * 
1597  * Converts all lower case ASCII letters to upper case ASCII letters.
1598  * 
1599  * Return value: a newly allocated string, with all the lower case
1600  *               characters in @str converted to upper case, with
1601  *               semantics that exactly match g_ascii_toupper(). (Note
1602  *               that this is unlike the old g_strup(), which modified
1603  *               the string in place.)
1604  **/
1605 gchar*
1606 g_ascii_strup (const gchar *str,
1607                gssize       len)
1608 {
1609   gchar *result, *s;
1610
1611   g_return_val_if_fail (str != NULL, NULL);
1612
1613   if (len < 0)
1614     len = strlen (str);
1615
1616   result = g_strndup (str, len);
1617   for (s = result; *s; s++)
1618     *s = g_ascii_toupper (*s);
1619
1620   return result;
1621 }
1622
1623 /**
1624  * g_strdown:
1625  * @string: the string to convert.
1626  * 
1627  * Converts a string to lower case.  
1628  * 
1629  * Return value: the string 
1630  *
1631  * Deprecated:2.2: This function is totally broken for the reasons discussed 
1632  * in the g_strncasecmp() docs - use g_ascii_strdown() or g_utf8_strdown() 
1633  * instead.
1634  **/
1635 gchar*
1636 g_strdown (gchar *string)
1637 {
1638   register guchar *s;
1639   
1640   g_return_val_if_fail (string != NULL, NULL);
1641   
1642   s = (guchar *) string;
1643   
1644   while (*s)
1645     {
1646       if (isupper (*s))
1647         *s = tolower (*s);
1648       s++;
1649     }
1650   
1651   return (gchar *) string;
1652 }
1653
1654 /**
1655  * g_strup:
1656  * @string: the string to convert.
1657  * 
1658  * Converts a string to upper case. 
1659  * 
1660  * Return value: the string
1661  *
1662  * Deprecated:2.2: This function is totally broken for the reasons discussed 
1663  * in the g_strncasecmp() docs - use g_ascii_strup() or g_utf8_strup() instead.
1664  **/
1665 gchar*
1666 g_strup (gchar *string)
1667 {
1668   register guchar *s;
1669
1670   g_return_val_if_fail (string != NULL, NULL);
1671
1672   s = (guchar *) string;
1673
1674   while (*s)
1675     {
1676       if (islower (*s))
1677         *s = toupper (*s);
1678       s++;
1679     }
1680
1681   return (gchar *) string;
1682 }
1683
1684 gchar*
1685 g_strreverse (gchar *string)
1686 {
1687   g_return_val_if_fail (string != NULL, NULL);
1688
1689   if (*string)
1690     {
1691       register gchar *h, *t;
1692
1693       h = string;
1694       t = string + strlen (string) - 1;
1695
1696       while (h < t)
1697         {
1698           register gchar c;
1699
1700           c = *h;
1701           *h = *t;
1702           h++;
1703           *t = c;
1704           t--;
1705         }
1706     }
1707
1708   return string;
1709 }
1710
1711 /**
1712  * g_ascii_tolower:
1713  * @c: any character.
1714  * 
1715  * Convert a character to ASCII lower case.
1716  *
1717  * Unlike the standard C library tolower() function, this only
1718  * recognizes standard ASCII letters and ignores the locale, returning
1719  * all non-ASCII characters unchanged, even if they are lower case
1720  * letters in a particular character set. Also unlike the standard
1721  * library function, this takes and returns a char, not an int, so
1722  * don't call it on %EOF but no need to worry about casting to #guchar
1723  * before passing a possibly non-ASCII character in.
1724  * 
1725  * Return value: the result of converting @c to lower case.
1726  *               If @c is not an ASCII upper case letter,
1727  *               @c is returned unchanged.
1728  **/
1729 gchar
1730 g_ascii_tolower (gchar c)
1731 {
1732   return g_ascii_isupper (c) ? c - 'A' + 'a' : c;
1733 }
1734
1735 /**
1736  * g_ascii_toupper:
1737  * @c: any character.
1738  * 
1739  * Convert a character to ASCII upper case.
1740  *
1741  * Unlike the standard C library toupper() function, this only
1742  * recognizes standard ASCII letters and ignores the locale, returning
1743  * all non-ASCII characters unchanged, even if they are upper case
1744  * letters in a particular character set. Also unlike the standard
1745  * library function, this takes and returns a char, not an int, so
1746  * don't call it on %EOF but no need to worry about casting to #guchar
1747  * before passing a possibly non-ASCII character in.
1748  * 
1749  * Return value: the result of converting @c to upper case.
1750  *               If @c is not an ASCII lower case letter,
1751  *               @c is returned unchanged.
1752  **/
1753 gchar
1754 g_ascii_toupper (gchar c)
1755 {
1756   return g_ascii_islower (c) ? c - 'a' + 'A' : c;
1757 }
1758
1759 /**
1760  * g_ascii_digit_value:
1761  * @c: an ASCII character.
1762  *
1763  * Determines the numeric value of a character as a decimal
1764  * digit. Differs from g_unichar_digit_value() because it takes
1765  * a char, so there's no worry about sign extension if characters
1766  * are signed.
1767  *
1768  * Return value: If @c is a decimal digit (according to
1769  * g_ascii_isdigit()), its numeric value. Otherwise, -1.
1770  **/
1771 int
1772 g_ascii_digit_value (gchar c)
1773 {
1774   if (g_ascii_isdigit (c))
1775     return c - '0';
1776   return -1;
1777 }
1778
1779 /**
1780  * g_ascii_xdigit_value:
1781  * @c: an ASCII character.
1782  *
1783  * Determines the numeric value of a character as a hexidecimal
1784  * digit. Differs from g_unichar_xdigit_value() because it takes
1785  * a char, so there's no worry about sign extension if characters
1786  * are signed.
1787  *
1788  * Return value: If @c is a hex digit (according to
1789  * g_ascii_isxdigit()), its numeric value. Otherwise, -1.
1790  **/
1791 int
1792 g_ascii_xdigit_value (gchar c)
1793 {
1794   if (c >= 'A' && c <= 'F')
1795     return c - 'A' + 10;
1796   if (c >= 'a' && c <= 'f')
1797     return c - 'a' + 10;
1798   return g_ascii_digit_value (c);
1799 }
1800
1801 /**
1802  * g_ascii_strcasecmp:
1803  * @s1: string to compare with @s2.
1804  * @s2: string to compare with @s1.
1805  * 
1806  * Compare two strings, ignoring the case of ASCII characters.
1807  *
1808  * Unlike the BSD strcasecmp() function, this only recognizes standard
1809  * ASCII letters and ignores the locale, treating all non-ASCII
1810  * bytes as if they are not letters.
1811  *
1812  * This function should be used only on strings that are known to be
1813  * in encodings where the bytes corresponding to ASCII letters always
1814  * represent themselves. This includes UTF-8 and the ISO-8859-*
1815  * charsets, but not for instance double-byte encodings like the
1816  * Windows Codepage 932, where the trailing bytes of double-byte
1817  * characters include all ASCII letters. If you compare two CP932
1818  * strings using this function, you will get false matches.
1819  *
1820  * Return value: 0 if the strings match, a negative value if @s1 &lt; @s2, 
1821  *   or a positive value if @s1 &gt; @s2.
1822  **/
1823 gint
1824 g_ascii_strcasecmp (const gchar *s1,
1825                     const gchar *s2)
1826 {
1827   gint c1, c2;
1828
1829   g_return_val_if_fail (s1 != NULL, 0);
1830   g_return_val_if_fail (s2 != NULL, 0);
1831
1832   while (*s1 && *s2)
1833     {
1834       c1 = (gint)(guchar) TOLOWER (*s1);
1835       c2 = (gint)(guchar) TOLOWER (*s2);
1836       if (c1 != c2)
1837         return (c1 - c2);
1838       s1++; s2++;
1839     }
1840
1841   return (((gint)(guchar) *s1) - ((gint)(guchar) *s2));
1842 }
1843
1844 /**
1845  * g_ascii_strncasecmp:
1846  * @s1: string to compare with @s2.
1847  * @s2: string to compare with @s1.
1848  * @n:  number of characters to compare.
1849  * 
1850  * Compare @s1 and @s2, ignoring the case of ASCII characters and any
1851  * characters after the first @n in each string.
1852  *
1853  * Unlike the BSD strcasecmp() function, this only recognizes standard
1854  * ASCII letters and ignores the locale, treating all non-ASCII
1855  * characters as if they are not letters.
1856  * 
1857  * The same warning as in g_ascii_strcasecmp() applies: Use this
1858  * function only on strings known to be in encodings where bytes
1859  * corresponding to ASCII letters always represent themselves.
1860  *
1861  * Return value: 0 if the strings match, a negative value if @s1 &lt; @s2, 
1862  *   or a positive value if @s1 &gt; @s2.
1863  **/
1864 gint
1865 g_ascii_strncasecmp (const gchar *s1,
1866                      const gchar *s2,
1867                      gsize n)
1868 {
1869   gint c1, c2;
1870
1871   g_return_val_if_fail (s1 != NULL, 0);
1872   g_return_val_if_fail (s2 != NULL, 0);
1873
1874   while (n && *s1 && *s2)
1875     {
1876       n -= 1;
1877       c1 = (gint)(guchar) TOLOWER (*s1);
1878       c2 = (gint)(guchar) TOLOWER (*s2);
1879       if (c1 != c2)
1880         return (c1 - c2);
1881       s1++; s2++;
1882     }
1883
1884   if (n)
1885     return (((gint) (guchar) *s1) - ((gint) (guchar) *s2));
1886   else
1887     return 0;
1888 }
1889
1890 /**
1891  * g_strcasecmp:
1892  * @s1: a string.
1893  * @s2: a string to compare with @s1.
1894  * 
1895  * A case-insensitive string comparison, corresponding to the standard
1896  * strcasecmp() function on platforms which support it.
1897  *
1898  * Return value: 0 if the strings match, a negative value if @s1 &lt; @s2, 
1899  *   or a positive value if @s1 &gt; @s2.
1900  *
1901  * Deprecated:2.2: See g_strncasecmp() for a discussion of why this function 
1902  *   is deprecated and how to replace it.
1903  **/
1904 gint
1905 g_strcasecmp (const gchar *s1,
1906               const gchar *s2)
1907 {
1908 #ifdef HAVE_STRCASECMP
1909   g_return_val_if_fail (s1 != NULL, 0);
1910   g_return_val_if_fail (s2 != NULL, 0);
1911
1912   return strcasecmp (s1, s2);
1913 #else
1914   gint c1, c2;
1915
1916   g_return_val_if_fail (s1 != NULL, 0);
1917   g_return_val_if_fail (s2 != NULL, 0);
1918
1919   while (*s1 && *s2)
1920     {
1921       /* According to A. Cox, some platforms have islower's that
1922        * don't work right on non-uppercase
1923        */
1924       c1 = isupper ((guchar)*s1) ? tolower ((guchar)*s1) : *s1;
1925       c2 = isupper ((guchar)*s2) ? tolower ((guchar)*s2) : *s2;
1926       if (c1 != c2)
1927         return (c1 - c2);
1928       s1++; s2++;
1929     }
1930
1931   return (((gint)(guchar) *s1) - ((gint)(guchar) *s2));
1932 #endif
1933 }
1934
1935 /**
1936  * g_strncasecmp:
1937  * @s1: a string.
1938  * @s2: a string to compare with @s1.
1939  * @n: the maximum number of characters to compare.
1940  * 
1941  * A case-insensitive string comparison, corresponding to the standard
1942  * strncasecmp() function on platforms which support it.
1943  * It is similar to g_strcasecmp() except it only compares the first @n 
1944  * characters of the strings.
1945  * 
1946  * Return value: 0 if the strings match, a negative value if @s1 &lt; @s2, 
1947  *   or a positive value if @s1 &gt; @s2.
1948  *
1949  * Deprecated:2.2: The problem with g_strncasecmp() is that it does the 
1950  * comparison by calling toupper()/tolower(). These functions are
1951  * locale-specific and operate on single bytes. However, it is impossible
1952  * to handle things correctly from an I18N standpoint by operating on
1953  * bytes, since characters may be multibyte. Thus g_strncasecmp() is
1954  * broken if your string is guaranteed to be ASCII, since it's
1955  * locale-sensitive, and it's broken if your string is localized, since
1956  * it doesn't work on many encodings at all, including UTF-8, EUC-JP,
1957  * etc.
1958  *
1959  * There are therefore two replacement functions: g_ascii_strncasecmp(),
1960  * which only works on ASCII and is not locale-sensitive, and
1961  * g_utf8_casefold(), which is good for case-insensitive sorting of UTF-8.
1962  **/
1963 gint
1964 g_strncasecmp (const gchar *s1,
1965                const gchar *s2,
1966                guint n)     
1967 {
1968 #ifdef HAVE_STRNCASECMP
1969   return strncasecmp (s1, s2, n);
1970 #else
1971   gint c1, c2;
1972
1973   g_return_val_if_fail (s1 != NULL, 0);
1974   g_return_val_if_fail (s2 != NULL, 0);
1975
1976   while (n && *s1 && *s2)
1977     {
1978       n -= 1;
1979       /* According to A. Cox, some platforms have islower's that
1980        * don't work right on non-uppercase
1981        */
1982       c1 = isupper ((guchar)*s1) ? tolower ((guchar)*s1) : *s1;
1983       c2 = isupper ((guchar)*s2) ? tolower ((guchar)*s2) : *s2;
1984       if (c1 != c2)
1985         return (c1 - c2);
1986       s1++; s2++;
1987     }
1988
1989   if (n)
1990     return (((gint) (guchar) *s1) - ((gint) (guchar) *s2));
1991   else
1992     return 0;
1993 #endif
1994 }
1995
1996 gchar*
1997 g_strdelimit (gchar       *string,
1998               const gchar *delimiters,
1999               gchar        new_delim)
2000 {
2001   register gchar *c;
2002
2003   g_return_val_if_fail (string != NULL, NULL);
2004
2005   if (!delimiters)
2006     delimiters = G_STR_DELIMITERS;
2007
2008   for (c = string; *c; c++)
2009     {
2010       if (strchr (delimiters, *c))
2011         *c = new_delim;
2012     }
2013
2014   return string;
2015 }
2016
2017 gchar*
2018 g_strcanon (gchar       *string,
2019             const gchar *valid_chars,
2020             gchar        substitutor)
2021 {
2022   register gchar *c;
2023
2024   g_return_val_if_fail (string != NULL, NULL);
2025   g_return_val_if_fail (valid_chars != NULL, NULL);
2026
2027   for (c = string; *c; c++)
2028     {
2029       if (!strchr (valid_chars, *c))
2030         *c = substitutor;
2031     }
2032
2033   return string;
2034 }
2035
2036 gchar*
2037 g_strcompress (const gchar *source)
2038 {
2039   const gchar *p = source, *octal;
2040   gchar *dest = g_malloc (strlen (source) + 1);
2041   gchar *q = dest;
2042   
2043   while (*p)
2044     {
2045       if (*p == '\\')
2046         {
2047           p++;
2048           switch (*p)
2049             {
2050             case '\0':
2051               g_warning ("g_strcompress: trailing \\");
2052               goto out;
2053             case '0':  case '1':  case '2':  case '3':  case '4':
2054             case '5':  case '6':  case '7':
2055               *q = 0;
2056               octal = p;
2057               while ((p < octal + 3) && (*p >= '0') && (*p <= '7'))
2058                 {
2059                   *q = (*q * 8) + (*p - '0');
2060                   p++;
2061                 }
2062               q++;
2063               p--;
2064               break;
2065             case 'b':
2066               *q++ = '\b';
2067               break;
2068             case 'f':
2069               *q++ = '\f';
2070               break;
2071             case 'n':
2072               *q++ = '\n';
2073               break;
2074             case 'r':
2075               *q++ = '\r';
2076               break;
2077             case 't':
2078               *q++ = '\t';
2079               break;
2080             default:            /* Also handles \" and \\ */
2081               *q++ = *p;
2082               break;
2083             }
2084         }
2085       else
2086         *q++ = *p;
2087       p++;
2088     }
2089 out:
2090   *q = 0;
2091   
2092   return dest;
2093 }
2094
2095 gchar *
2096 g_strescape (const gchar *source,
2097              const gchar *exceptions)
2098 {
2099   const guchar *p;
2100   gchar *dest;
2101   gchar *q;
2102   guchar excmap[256];
2103   
2104   g_return_val_if_fail (source != NULL, NULL);
2105
2106   p = (guchar *) source;
2107   /* Each source byte needs maximally four destination chars (\777) */
2108   q = dest = g_malloc (strlen (source) * 4 + 1);
2109
2110   memset (excmap, 0, 256);
2111   if (exceptions)
2112     {
2113       guchar *e = (guchar *) exceptions;
2114
2115       while (*e)
2116         {
2117           excmap[*e] = 1;
2118           e++;
2119         }
2120     }
2121
2122   while (*p)
2123     {
2124       if (excmap[*p])
2125         *q++ = *p;
2126       else
2127         {
2128           switch (*p)
2129             {
2130             case '\b':
2131               *q++ = '\\';
2132               *q++ = 'b';
2133               break;
2134             case '\f':
2135               *q++ = '\\';
2136               *q++ = 'f';
2137               break;
2138             case '\n':
2139               *q++ = '\\';
2140               *q++ = 'n';
2141               break;
2142             case '\r':
2143               *q++ = '\\';
2144               *q++ = 'r';
2145               break;
2146             case '\t':
2147               *q++ = '\\';
2148               *q++ = 't';
2149               break;
2150             case '\\':
2151               *q++ = '\\';
2152               *q++ = '\\';
2153               break;
2154             case '"':
2155               *q++ = '\\';
2156               *q++ = '"';
2157               break;
2158             default:
2159               if ((*p < ' ') || (*p >= 0177))
2160                 {
2161                   *q++ = '\\';
2162                   *q++ = '0' + (((*p) >> 6) & 07);
2163                   *q++ = '0' + (((*p) >> 3) & 07);
2164                   *q++ = '0' + ((*p) & 07);
2165                 }
2166               else
2167                 *q++ = *p;
2168               break;
2169             }
2170         }
2171       p++;
2172     }
2173   *q = 0;
2174   return dest;
2175 }
2176
2177 gchar*
2178 g_strchug (gchar *string)
2179 {
2180   guchar *start;
2181
2182   g_return_val_if_fail (string != NULL, NULL);
2183
2184   for (start = (guchar*) string; *start && g_ascii_isspace (*start); start++)
2185     ;
2186
2187   g_memmove (string, start, strlen ((gchar *) start) + 1);
2188
2189   return string;
2190 }
2191
2192 gchar*
2193 g_strchomp (gchar *string)
2194 {
2195   gsize len;
2196
2197   g_return_val_if_fail (string != NULL, NULL);
2198
2199   len = strlen (string);
2200   while (len--)
2201     {
2202       if (g_ascii_isspace ((guchar) string[len]))
2203         string[len] = '\0';
2204       else
2205         break;
2206     }
2207
2208   return string;
2209 }
2210
2211 /**
2212  * g_strsplit:
2213  * @string: a string to split.
2214  * @delimiter: a string which specifies the places at which to split the string.
2215  *     The delimiter is not included in any of the resulting strings, unless
2216  *     @max_tokens is reached.
2217  * @max_tokens: the maximum number of pieces to split @string into. If this is
2218  *              less than 1, the string is split completely.
2219  * 
2220  * Splits a string into a maximum of @max_tokens pieces, using the given
2221  * @delimiter. If @max_tokens is reached, the remainder of @string is appended
2222  * to the last token. 
2223  *
2224  * As a special case, the result of splitting the empty string "" is an empty
2225  * vector, not a vector containing a single string. The reason for this
2226  * special case is that being able to represent a empty vector is typically
2227  * more useful than consistent handling of empty elements. If you do need
2228  * to represent empty elements, you'll need to check for the empty string
2229  * before calling g_strsplit().
2230  * 
2231  * Return value: a newly-allocated %NULL-terminated array of strings. Use 
2232  *    g_strfreev() to free it.
2233  **/
2234 gchar**
2235 g_strsplit (const gchar *string,
2236             const gchar *delimiter,
2237             gint         max_tokens)
2238 {
2239   GSList *string_list = NULL, *slist;
2240   gchar **str_array, *s;
2241   guint n = 0;
2242   const gchar *remainder;
2243
2244   g_return_val_if_fail (string != NULL, NULL);
2245   g_return_val_if_fail (delimiter != NULL, NULL);
2246   g_return_val_if_fail (delimiter[0] != '\0', NULL);
2247
2248   if (max_tokens < 1)
2249     max_tokens = G_MAXINT;
2250
2251   remainder = string;
2252   s = strstr (remainder, delimiter);
2253   if (s)
2254     {
2255       gsize delimiter_len = strlen (delimiter);   
2256
2257       while (--max_tokens && s)
2258         {
2259           gsize len;     
2260           gchar *new_string;
2261
2262           len = s - remainder;
2263           new_string = g_new (gchar, len + 1);
2264           strncpy (new_string, remainder, len);
2265           new_string[len] = 0;
2266           string_list = g_slist_prepend (string_list, new_string);
2267           n++;
2268           remainder = s + delimiter_len;
2269           s = strstr (remainder, delimiter);
2270         }
2271     }
2272   if (*string)
2273     {
2274       n++;
2275       string_list = g_slist_prepend (string_list, g_strdup (remainder));
2276     }
2277
2278   str_array = g_new (gchar*, n + 1);
2279
2280   str_array[n--] = NULL;
2281   for (slist = string_list; slist; slist = slist->next)
2282     str_array[n--] = slist->data;
2283
2284   g_slist_free (string_list);
2285
2286   return str_array;
2287 }
2288
2289 /**
2290  * g_strsplit_set:
2291  * @string: The string to be tokenized
2292  * @delimiters: A nul-terminated string containing bytes that are used
2293  *              to split the string.
2294  * @max_tokens: The maximum number of tokens to split @string into. 
2295  *              If this is less than 1, the string is split completely
2296  * 
2297  * Splits @string into a number of tokens not containing any of the characters
2298  * in @delimiter. A token is the (possibly empty) longest string that does not
2299  * contain any of the characters in @delimiters. If @max_tokens is reached, the
2300  * remainder is appended to the last token.
2301  *
2302  * For example the result of g_strsplit_set ("abc:def/ghi", ":/", -1) is a
2303  * %NULL-terminated vector containing the three strings "abc", "def", 
2304  * and "ghi".
2305  *
2306  * The result if g_strsplit_set (":def/ghi:", ":/", -1) is a %NULL-terminated
2307  * vector containing the four strings "", "def", "ghi", and "".
2308  * 
2309  * As a special case, the result of splitting the empty string "" is an empty
2310  * vector, not a vector containing a single string. The reason for this
2311  * special case is that being able to represent a empty vector is typically
2312  * more useful than consistent handling of empty elements. If you do need
2313  * to represent empty elements, you'll need to check for the empty string
2314  * before calling g_strsplit_set().
2315  *
2316  * Note that this function works on bytes not characters, so it can't be used 
2317  * to delimit UTF-8 strings for anything but ASCII characters.
2318  * 
2319  * Return value: a newly-allocated %NULL-terminated array of strings. Use 
2320  *    g_strfreev() to free it.
2321  * 
2322  * Since: 2.4
2323  **/
2324 gchar **
2325 g_strsplit_set (const gchar *string,
2326                 const gchar *delimiters,
2327                 gint         max_tokens)
2328 {
2329   gboolean delim_table[256];
2330   GSList *tokens, *list;
2331   gint n_tokens;
2332   const gchar *s;
2333   const gchar *current;
2334   gchar *token;
2335   gchar **result;
2336   
2337   g_return_val_if_fail (string != NULL, NULL);
2338   g_return_val_if_fail (delimiters != NULL, NULL);
2339
2340   if (max_tokens < 1)
2341     max_tokens = G_MAXINT;
2342
2343   if (*string == '\0')
2344     {
2345       result = g_new (char *, 1);
2346       result[0] = NULL;
2347       return result;
2348     }
2349   
2350   memset (delim_table, FALSE, sizeof (delim_table));
2351   for (s = delimiters; *s != '\0'; ++s)
2352     delim_table[*(guchar *)s] = TRUE;
2353
2354   tokens = NULL;
2355   n_tokens = 0;
2356
2357   s = current = string;
2358   while (*s != '\0')
2359     {
2360       if (delim_table[*(guchar *)s] && n_tokens + 1 < max_tokens)
2361         {
2362           gchar *token;
2363
2364           token = g_strndup (current, s - current);
2365           tokens = g_slist_prepend (tokens, token);
2366           ++n_tokens;
2367
2368           current = s + 1;
2369         }
2370       
2371       ++s;
2372     }
2373
2374   token = g_strndup (current, s - current);
2375   tokens = g_slist_prepend (tokens, token);
2376   ++n_tokens;
2377
2378   result = g_new (gchar *, n_tokens + 1);
2379
2380   result[n_tokens] = NULL;
2381   for (list = tokens; list != NULL; list = list->next)
2382     result[--n_tokens] = list->data;
2383
2384   g_slist_free (tokens);
2385   
2386   return result;
2387 }
2388
2389 /**
2390  * g_strfreev:
2391  * @str_array: a %NULL-terminated array of strings to free.
2392
2393  * Frees a %NULL-terminated array of strings, and the array itself.
2394  * If called on a %NULL value, g_strfreev() simply returns. 
2395  **/
2396 void
2397 g_strfreev (gchar **str_array)
2398 {
2399   if (str_array)
2400     {
2401       int i;
2402
2403       for(i = 0; str_array[i] != NULL; i++)
2404         g_free(str_array[i]);
2405
2406       g_free (str_array);
2407     }
2408 }
2409
2410 /**
2411  * g_strdupv:
2412  * @str_array: %NULL-terminated array of strings.
2413  * 
2414  * Copies %NULL-terminated array of strings. The copy is a deep copy;
2415  * the new array should be freed by first freeing each string, then
2416  * the array itself. g_strfreev() does this for you. If called
2417  * on a %NULL value, g_strdupv() simply returns %NULL.
2418  * 
2419  * Return value: a new %NULL-terminated array of strings.
2420  **/
2421 gchar**
2422 g_strdupv (gchar **str_array)
2423 {
2424   if (str_array)
2425     {
2426       gint i;
2427       gchar **retval;
2428
2429       i = 0;
2430       while (str_array[i])
2431         ++i;
2432           
2433       retval = g_new (gchar*, i + 1);
2434
2435       i = 0;
2436       while (str_array[i])
2437         {
2438           retval[i] = g_strdup (str_array[i]);
2439           ++i;
2440         }
2441       retval[i] = NULL;
2442
2443       return retval;
2444     }
2445   else
2446     return NULL;
2447 }
2448
2449 gchar*
2450 g_strjoinv (const gchar  *separator,
2451             gchar       **str_array)
2452 {
2453   gchar *string;
2454   gchar *ptr;
2455
2456   g_return_val_if_fail (str_array != NULL, NULL);
2457
2458   if (separator == NULL)
2459     separator = "";
2460
2461   if (*str_array)
2462     {
2463       gint i;
2464       gsize len;
2465       gsize separator_len;     
2466
2467       separator_len = strlen (separator);
2468       /* First part, getting length */
2469       len = 1 + strlen (str_array[0]);
2470       for (i = 1; str_array[i] != NULL; i++)
2471         len += strlen (str_array[i]);
2472       len += separator_len * (i - 1);
2473
2474       /* Second part, building string */
2475       string = g_new (gchar, len);
2476       ptr = g_stpcpy (string, *str_array);
2477       for (i = 1; str_array[i] != NULL; i++)
2478         {
2479           ptr = g_stpcpy (ptr, separator);
2480           ptr = g_stpcpy (ptr, str_array[i]);
2481         }
2482       }
2483   else
2484     string = g_strdup ("");
2485
2486   return string;
2487 }
2488
2489 gchar*
2490 g_strjoin (const gchar  *separator,
2491            ...)
2492 {
2493   gchar *string, *s;
2494   va_list args;
2495   gsize len;               
2496   gsize separator_len;     
2497   gchar *ptr;
2498
2499   if (separator == NULL)
2500     separator = "";
2501
2502   separator_len = strlen (separator);
2503
2504   va_start (args, separator);
2505
2506   s = va_arg (args, gchar*);
2507
2508   if (s)
2509     {
2510       /* First part, getting length */
2511       len = 1 + strlen (s);
2512
2513       s = va_arg (args, gchar*);
2514       while (s)
2515         {
2516           len += separator_len + strlen (s);
2517           s = va_arg (args, gchar*);
2518         }
2519       va_end (args);
2520
2521       /* Second part, building string */
2522       string = g_new (gchar, len);
2523
2524       va_start (args, separator);
2525
2526       s = va_arg (args, gchar*);
2527       ptr = g_stpcpy (string, s);
2528
2529       s = va_arg (args, gchar*);
2530       while (s)
2531         {
2532           ptr = g_stpcpy (ptr, separator);
2533           ptr = g_stpcpy (ptr, s);
2534           s = va_arg (args, gchar*);
2535         }
2536     }
2537   else
2538     string = g_strdup ("");
2539
2540   va_end (args);
2541
2542   return string;
2543 }
2544
2545
2546 /**
2547  * g_strstr_len:
2548  * @haystack: a string.
2549  * @haystack_len: the maximum length of @haystack.
2550  * @needle: the string to search for.
2551  *
2552  * Searches the string @haystack for the first occurrence
2553  * of the string @needle, limiting the length of the search
2554  * to @haystack_len. 
2555  *
2556  * Return value: a pointer to the found occurrence, or
2557  *    %NULL if not found.
2558  **/
2559 gchar *
2560 g_strstr_len (const gchar *haystack,
2561               gssize       haystack_len,
2562               const gchar *needle)
2563 {
2564   g_return_val_if_fail (haystack != NULL, NULL);
2565   g_return_val_if_fail (needle != NULL, NULL);
2566   
2567   if (haystack_len < 0)
2568     return strstr (haystack, needle);
2569   else
2570     {
2571       const gchar *p = haystack;
2572       gsize needle_len = strlen (needle);
2573       const gchar *end;
2574       gsize i;
2575
2576       if (needle_len == 0)
2577         return (gchar *)haystack;
2578
2579       if (haystack_len < needle_len)
2580         return NULL;
2581       
2582       end = haystack + haystack_len - needle_len;
2583       
2584       while (*p && p <= end)
2585         {
2586           for (i = 0; i < needle_len; i++)
2587             if (p[i] != needle[i])
2588               goto next;
2589           
2590           return (gchar *)p;
2591           
2592         next:
2593           p++;
2594         }
2595       
2596       return NULL;
2597     }
2598 }
2599
2600 /**
2601  * g_strrstr:
2602  * @haystack: a nul-terminated string.
2603  * @needle: the nul-terminated string to search for.
2604  *
2605  * Searches the string @haystack for the last occurrence
2606  * of the string @needle.
2607  *
2608  * Return value: a pointer to the found occurrence, or
2609  *    %NULL if not found.
2610  **/
2611 gchar *
2612 g_strrstr (const gchar *haystack,
2613            const gchar *needle)
2614 {
2615   gsize i;
2616   gsize needle_len;
2617   gsize haystack_len;
2618   const gchar *p;
2619       
2620   g_return_val_if_fail (haystack != NULL, NULL);
2621   g_return_val_if_fail (needle != NULL, NULL);
2622
2623   needle_len = strlen (needle);
2624   haystack_len = strlen (haystack);
2625
2626   if (needle_len == 0)
2627     return (gchar *)haystack;
2628
2629   if (haystack_len < needle_len)
2630     return NULL;
2631   
2632   p = haystack + haystack_len - needle_len;
2633
2634   while (p >= haystack)
2635     {
2636       for (i = 0; i < needle_len; i++)
2637         if (p[i] != needle[i])
2638           goto next;
2639       
2640       return (gchar *)p;
2641       
2642     next:
2643       p--;
2644     }
2645   
2646   return NULL;
2647 }
2648
2649 /**
2650  * g_strrstr_len:
2651  * @haystack: a nul-terminated string.
2652  * @haystack_len: the maximum length of @haystack.
2653  * @needle: the nul-terminated string to search for.
2654  *
2655  * Searches the string @haystack for the last occurrence
2656  * of the string @needle, limiting the length of the search
2657  * to @haystack_len. 
2658  *
2659  * Return value: a pointer to the found occurrence, or
2660  *    %NULL if not found.
2661  **/
2662 gchar *
2663 g_strrstr_len (const gchar *haystack,
2664                gssize        haystack_len,
2665                const gchar *needle)
2666 {
2667   g_return_val_if_fail (haystack != NULL, NULL);
2668   g_return_val_if_fail (needle != NULL, NULL);
2669   
2670   if (haystack_len < 0)
2671     return g_strrstr (haystack, needle);
2672   else
2673     {
2674       gsize needle_len = strlen (needle);
2675       const gchar *haystack_max = haystack + haystack_len;
2676       const gchar *p = haystack;
2677       gsize i;
2678
2679       while (p < haystack_max && *p)
2680         p++;
2681
2682       if (p < haystack + needle_len)
2683         return NULL;
2684         
2685       p -= needle_len;
2686
2687       while (p >= haystack)
2688         {
2689           for (i = 0; i < needle_len; i++)
2690             if (p[i] != needle[i])
2691               goto next;
2692           
2693           return (gchar *)p;
2694           
2695         next:
2696           p--;
2697         }
2698
2699       return NULL;
2700     }
2701 }
2702
2703
2704 /**
2705  * g_str_has_suffix:
2706  * @str: a nul-terminated string.
2707  * @suffix: the nul-terminated suffix to look for.
2708  *
2709  * Looks whether the string @str ends with @suffix.
2710  *
2711  * Return value: %TRUE if @str end with @suffix, %FALSE otherwise.
2712  *
2713  * Since: 2.2
2714  **/
2715 gboolean
2716 g_str_has_suffix (const gchar  *str,
2717                   const gchar  *suffix)
2718 {
2719   int str_len;
2720   int suffix_len;
2721   
2722   g_return_val_if_fail (str != NULL, FALSE);
2723   g_return_val_if_fail (suffix != NULL, FALSE);
2724
2725   str_len = strlen (str);
2726   suffix_len = strlen (suffix);
2727
2728   if (str_len < suffix_len)
2729     return FALSE;
2730
2731   return strcmp (str + str_len - suffix_len, suffix) == 0;
2732 }
2733
2734 /**
2735  * g_str_has_prefix:
2736  * @str: a nul-terminated string.
2737  * @prefix: the nul-terminated prefix to look for.
2738  *
2739  * Looks whether the string @str begins with @prefix.
2740  *
2741  * Return value: %TRUE if @str begins with @prefix, %FALSE otherwise.
2742  *
2743  * Since: 2.2
2744  **/
2745 gboolean
2746 g_str_has_prefix (const gchar  *str,
2747                   const gchar  *prefix)
2748 {
2749   int str_len;
2750   int prefix_len;
2751   
2752   g_return_val_if_fail (str != NULL, FALSE);
2753   g_return_val_if_fail (prefix != NULL, FALSE);
2754
2755   str_len = strlen (str);
2756   prefix_len = strlen (prefix);
2757
2758   if (str_len < prefix_len)
2759     return FALSE;
2760   
2761   return strncmp (str, prefix, prefix_len) == 0;
2762 }
2763
2764
2765 /**
2766  * g_strip_context:
2767  * @msgid: a string
2768  * @msgval: another string
2769  * 
2770  * An auxiliary function for gettext() support (see Q_()).
2771  * 
2772  * Return value: @msgval, unless @msgval is identical to @msgid and contains
2773  *   a '|' character, in which case a pointer to the substring of msgid after
2774  *   the first '|' character is returned. 
2775  *
2776  * Since: 2.4
2777  **/
2778 G_CONST_RETURN gchar *
2779 g_strip_context  (const gchar *msgid, 
2780                   const gchar *msgval)
2781 {
2782   if (msgval == msgid)
2783     {
2784       const char *c = strchr (msgid, '|');
2785       if (c != NULL)
2786         return c + 1;
2787     }
2788   
2789   return msgval;
2790 }
2791
2792
2793 /**
2794  * g_strv_length:
2795  * @str_array: a %NULL-terminated array of strings.
2796  * 
2797  * Returns the length of the given %NULL-terminated 
2798  * string array @str_array.
2799  * 
2800  * Return value: length of @str_array.
2801  *
2802  * Since: 2.6
2803  **/
2804 guint
2805 g_strv_length (gchar **str_array)
2806 {
2807   guint i = 0;
2808
2809   g_return_val_if_fail (str_array != NULL, 0);
2810
2811   while (str_array[i])
2812     ++i;
2813
2814   return i;
2815 }
2816
2817 #define __G_STRFUNCS_C__
2818 #include "galiasdef.c"