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