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