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