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