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