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