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