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