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