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