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