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