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