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