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