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