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