1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the
16 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 * Boston, MA 02111-1307, USA.
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/.
40 #include <ctype.h> /* For tolower() */
43 /* Needed on BSD/OS X for e.g. strtod_l */
51 /* do not include <unistd.h> here, it may interfere with g_strsignal() */
53 #include "gstrfuncs.h"
56 #include "gprintfint.h"
61 * SECTION:string_utils
62 * @title: String Utility Functions
63 * @short_description: various string-related functions
65 * This section describes a number of utility functions for creating,
66 * duplicating, and manipulating strings.
68 * Note that the functions g_printf(), g_fprintf(), g_sprintf(),
69 * g_snprintf(), g_vprintf(), g_vfprintf(), g_vsprintf() and g_vsnprintf()
70 * are declared in the header <filename>gprintf.h</filename> which is
71 * <emphasis>not</emphasis> included in <filename>glib.h</filename>
72 * (otherwise using <filename>glib.h</filename> would drag in
73 * <filename>stdio.h</filename>), so you'll have to explicitly include
74 * <literal><glib/gprintf.h></literal> in order to use the GLib
77 * <para id="string-precision">While you may use the printf() functions
78 * to format UTF-8 strings, notice that the precision of a
79 * <literal>%Ns</literal> parameter is interpreted as the
80 * number of <emphasis>bytes</emphasis>, not <emphasis>characters</emphasis>
81 * to print. On top of that, the GNU libc implementation of the printf()
82 * functions has the "feature" that it checks that the string given for
83 * the <literal>%Ns</literal> parameter consists of a whole number
84 * of characters in the current encoding. So, unless you are sure you are
85 * always going to be in an UTF-8 locale or your know your text is restricted
86 * to ASCII, avoid using <literal>%Ns</literal>. If your intention is
87 * to format strings for a certain number of columns, then
88 * <literal>%Ns</literal> is not a correct solution anyway, since it
89 * fails to take wide characters (see g_unichar_iswide()) into account.
97 * Determines whether a character is alphanumeric.
99 * Unlike the standard C library isalnum() function, this only
100 * recognizes standard ASCII letters and ignores the locale,
101 * returning %FALSE for all non-ASCII characters. Also, unlike
102 * the standard library function, this takes a char, not an int,
103 * so don't call it on %EOF, but no need to cast to #guchar before
104 * passing a possibly non-ASCII character in.
106 * Returns: %TRUE if @c is an ASCII alphanumeric character
113 * Determines whether a character is alphabetic (i.e. a letter).
115 * Unlike the standard C library isalpha() function, this only
116 * recognizes standard ASCII letters and ignores the locale,
117 * returning %FALSE for all non-ASCII characters. Also, unlike
118 * the standard library function, this takes a char, not an int,
119 * so don't call it on %EOF, but no need to cast to #guchar before
120 * passing a possibly non-ASCII character in.
122 * Returns: %TRUE if @c is an ASCII alphabetic character
129 * Determines whether a character is a control character.
131 * Unlike the standard C library iscntrl() function, this only
132 * recognizes standard ASCII control characters and ignores the
133 * locale, returning %FALSE for all non-ASCII characters. Also,
134 * unlike the standard library function, this takes a char, not
135 * an int, so don't call it on %EOF, but no need to cast to #guchar
136 * before passing a possibly non-ASCII character in.
138 * Returns: %TRUE if @c is an ASCII control character.
145 * Determines whether a character is digit (0-9).
147 * Unlike the standard C library isdigit() function, this takes
148 * a char, not an int, so don't call it on %EOF, but no need to
149 * cast to #guchar before passing a possibly non-ASCII character in.
151 * Returns: %TRUE if @c is an ASCII digit.
158 * Determines whether a character is a printing character and not a space.
160 * Unlike the standard C library isgraph() function, this only
161 * recognizes standard ASCII characters and ignores the locale,
162 * returning %FALSE for all non-ASCII characters. Also, unlike
163 * the standard library function, this takes a char, not an int,
164 * so don't call it on %EOF, but no need to cast to #guchar before
165 * passing a possibly non-ASCII character in.
167 * Returns: %TRUE if @c is an ASCII printing character other than space.
174 * Determines whether a character is an ASCII lower case letter.
176 * Unlike the standard C library islower() function, this only
177 * recognizes standard ASCII letters and ignores the locale,
178 * returning %FALSE for all non-ASCII characters. Also, unlike
179 * the standard library function, this takes a char, not an int,
180 * so don't call it on %EOF, but no need to worry about casting
181 * to #guchar before passing a possibly non-ASCII character in.
183 * Returns: %TRUE if @c is an ASCII lower case letter
190 * Determines whether a character is a printing character.
192 * Unlike the standard C library isprint() function, this only
193 * recognizes standard ASCII characters and ignores the locale,
194 * returning %FALSE for all non-ASCII characters. Also, unlike
195 * the standard library function, this takes a char, not an int,
196 * so don't call it on %EOF, but no need to cast to #guchar before
197 * passing a possibly non-ASCII character in.
199 * Returns: %TRUE if @c is an ASCII printing character.
206 * Determines whether a character is a punctuation character.
208 * Unlike the standard C library ispunct() function, this only
209 * recognizes standard ASCII letters and ignores the locale,
210 * returning %FALSE for all non-ASCII characters. Also, unlike
211 * the standard library function, this takes a char, not an int,
212 * so don't call it on %EOF, but no need to cast to #guchar before
213 * passing a possibly non-ASCII character in.
215 * Returns: %TRUE if @c is an ASCII punctuation character.
222 * Determines whether a character is a white-space character.
224 * Unlike the standard C library isspace() function, this only
225 * recognizes standard ASCII white-space and ignores the locale,
226 * returning %FALSE for all non-ASCII characters. Also, unlike
227 * the standard library function, this takes a char, not an int,
228 * so don't call it on %EOF, but no need to cast to #guchar before
229 * passing a possibly non-ASCII character in.
231 * Returns: %TRUE if @c is an ASCII white-space character
238 * Determines whether a character is an ASCII upper case letter.
240 * Unlike the standard C library isupper() function, this only
241 * recognizes standard ASCII letters and ignores the locale,
242 * returning %FALSE for all non-ASCII characters. Also, unlike
243 * the standard library function, this takes a char, not an int,
244 * so don't call it on %EOF, but no need to worry about casting
245 * to #guchar before passing a possibly non-ASCII character in.
247 * Returns: %TRUE if @c is an ASCII upper case letter
254 * Determines whether a character is a hexadecimal-digit character.
256 * Unlike the standard C library isxdigit() function, this takes
257 * a char, not an int, so don't call it on %EOF, but no need to
258 * cast to #guchar before passing a possibly non-ASCII character in.
260 * Returns: %TRUE if @c is an ASCII hexadecimal-digit character.
264 * G_ASCII_DTOSTR_BUF_SIZE:
266 * A good size for a buffer to be passed into g_ascii_dtostr().
267 * It is guaranteed to be enough for all output of that function
268 * on systems with 64bit IEEE-compatible doubles.
270 * The typical usage would be something like:
272 * char buf[G_ASCII_DTOSTR_BUF_SIZE];
274 * fprintf (out, "value=%s\n", g_ascii_dtostr (buf, sizeof (buf), value));
280 * @string: a string to remove the leading and trailing whitespace from
282 * Removes leading and trailing whitespace from a string.
283 * See g_strchomp() and g_strchug().
291 * The standard delimiters, used in g_strdelimit().
294 static const guint16 ascii_table_data[256] = {
295 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004,
296 0x004, 0x104, 0x104, 0x004, 0x104, 0x104, 0x004, 0x004,
297 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004,
298 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004, 0x004,
299 0x140, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
300 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
301 0x459, 0x459, 0x459, 0x459, 0x459, 0x459, 0x459, 0x459,
302 0x459, 0x459, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
303 0x0d0, 0x653, 0x653, 0x653, 0x653, 0x653, 0x653, 0x253,
304 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253,
305 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253, 0x253,
306 0x253, 0x253, 0x253, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x0d0,
307 0x0d0, 0x473, 0x473, 0x473, 0x473, 0x473, 0x473, 0x073,
308 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073,
309 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073, 0x073,
310 0x073, 0x073, 0x073, 0x0d0, 0x0d0, 0x0d0, 0x0d0, 0x004
311 /* the upper 128 are all zeroes */
314 const guint16 * const g_ascii_table = ascii_table_data;
316 #if defined (HAVE_NEWLOCALE) && \
317 defined (HAVE_USELOCALE) && \
318 defined (HAVE_STRTOD_L) && \
319 defined (HAVE_STRTOULL_L) && \
320 defined (HAVE_STRTOLL_L)
321 #define USE_XLOCALE 1
328 static gsize initialized = FALSE;
329 static locale_t C_locale = NULL;
331 if (g_once_init_enter (&initialized))
333 C_locale = newlocale (LC_ALL_MASK, "C", NULL);
334 g_once_init_leave (&initialized, TRUE);
343 * @str: the string to duplicate
345 * Duplicates a string. If @str is %NULL it returns %NULL.
346 * The returned string should be freed with g_free()
347 * when no longer needed.
349 * Returns: a newly-allocated copy of @str
352 g_strdup (const gchar *str)
359 length = strlen (str) + 1;
360 new_str = g_new (char, length);
361 memcpy (new_str, str, length);
371 * @mem: the memory to copy.
372 * @byte_size: the number of bytes to copy.
374 * Allocates @byte_size bytes of memory, and copies @byte_size bytes into it
375 * from @mem. If @mem is %NULL it returns %NULL.
377 * Returns: a pointer to the newly-allocated copy of the memory, or %NULL if @mem
381 g_memdup (gconstpointer mem,
388 new_mem = g_malloc (byte_size);
389 memcpy (new_mem, mem, byte_size);
399 * @str: the string to duplicate
400 * @n: the maximum number of bytes to copy from @str
402 * Duplicates the first @n bytes of a string, returning a newly-allocated
403 * buffer @n + 1 bytes long which will always be nul-terminated.
404 * If @str is less than @n bytes long the buffer is padded with nuls.
405 * If @str is %NULL it returns %NULL.
406 * The returned value should be freed when no longer needed.
409 * To copy a number of characters from a UTF-8 encoded string, use
410 * g_utf8_strncpy() instead.
413 * Returns: a newly-allocated buffer containing the first @n bytes
414 * of @str, nul-terminated
417 g_strndup (const gchar *str,
424 new_str = g_new (gchar, n + 1);
425 strncpy (new_str, str, n);
436 * @length: the length of the new string
437 * @fill_char: the byte to fill the string with
439 * Creates a new string @length bytes long filled with @fill_char.
440 * The returned string should be freed when no longer needed.
442 * Returns: a newly-allocated string filled the @fill_char
445 g_strnfill (gsize length,
450 str = g_new (gchar, length + 1);
451 memset (str, (guchar)fill_char, length);
459 * @dest: destination buffer.
460 * @src: source string.
462 * Copies a nul-terminated string into the dest buffer, include the
463 * trailing nul, and return a pointer to the trailing nul byte.
464 * This is useful for concatenating multiple strings together
465 * without having to repeatedly scan for the end.
467 * Return value: a pointer to trailing nul byte.
470 g_stpcpy (gchar *dest,
474 g_return_val_if_fail (dest != NULL, NULL);
475 g_return_val_if_fail (src != NULL, NULL);
476 return stpcpy (dest, src);
478 register gchar *d = dest;
479 register const gchar *s = src;
481 g_return_val_if_fail (dest != NULL, NULL);
482 g_return_val_if_fail (src != NULL, NULL);
485 while (*s++ != '\0');
493 * @format: a standard printf() format string, but notice
494 * <link linkend="string-precision">string precision pitfalls</link>
495 * @args: the list of parameters to insert into the format string
497 * Similar to the standard C vsprintf() function but safer, since it
498 * calculates the maximum space required and allocates memory to hold
499 * the result. The returned string should be freed with g_free() when
502 * See also g_vasprintf(), which offers the same functionality, but
503 * additionally returns the length of the allocated string.
505 * Returns: a newly-allocated string holding the result
508 g_strdup_vprintf (const gchar *format,
511 gchar *string = NULL;
513 g_vasprintf (&string, format, args);
520 * @format: a standard printf() format string, but notice
521 * <link linkend="string-precision">string precision pitfalls</link>
522 * @...: the parameters to insert into the format string
524 * Similar to the standard C sprintf() function but safer, since it
525 * calculates the maximum space required and allocates memory to hold
526 * the result. The returned string should be freed with g_free() when no
529 * Returns: a newly-allocated string holding the result
532 g_strdup_printf (const gchar *format,
538 va_start (args, format);
539 buffer = g_strdup_vprintf (format, args);
547 * @string1: the first string to add, which must not be %NULL
548 * @...: a %NULL-terminated list of strings to append to the string
550 * Concatenates all of the given strings into one long string.
551 * The returned string should be freed with g_free() when no longer needed.
553 * Note that this function is usually not the right function to use to
554 * assemble a translated message from pieces, since proper translation
555 * often requires the pieces to be reordered.
557 * <warning><para>The variable argument list <emphasis>must</emphasis> end
558 * with %NULL. If you forget the %NULL, g_strconcat() will start appending
559 * random memory junk to your string.</para></warning>
561 * Returns: a newly-allocated string containing all the string arguments
564 g_strconcat (const gchar *string1, ...)
575 l = 1 + strlen (string1);
576 va_start (args, string1);
577 s = va_arg (args, gchar*);
581 s = va_arg (args, gchar*);
585 concat = g_new (gchar, l);
588 ptr = g_stpcpy (ptr, string1);
589 va_start (args, string1);
590 s = va_arg (args, gchar*);
593 ptr = g_stpcpy (ptr, s);
594 s = va_arg (args, gchar*);
603 * @nptr: the string to convert to a numeric value.
604 * @endptr: if non-%NULL, it returns the character after
605 * the last character used in the conversion.
607 * Converts a string to a #gdouble value.
608 * It calls the standard strtod() function to handle the conversion, but
609 * if the string is not completely converted it attempts the conversion
610 * again with g_ascii_strtod(), and returns the best match.
612 * This function should seldom be used. The normal situation when reading
613 * numbers not for human consumption is to use g_ascii_strtod(). Only when
614 * you know that you must expect both locale formatted and C formatted numbers
615 * should you use this. Make sure that you don't pass strings such as comma
616 * separated lists of values, since the commas may be interpreted as a decimal
617 * point in some locales, causing unexpected results.
619 * Return value: the #gdouble value.
622 g_strtod (const gchar *nptr,
630 g_return_val_if_fail (nptr != NULL, 0);
635 val_1 = strtod (nptr, &fail_pos_1);
637 if (fail_pos_1 && fail_pos_1[0] != 0)
638 val_2 = g_ascii_strtod (nptr, &fail_pos_2);
640 if (!fail_pos_1 || fail_pos_1[0] == 0 || fail_pos_1 >= fail_pos_2)
643 *endptr = fail_pos_1;
649 *endptr = fail_pos_2;
656 * @nptr: the string to convert to a numeric value.
657 * @endptr: if non-%NULL, it returns the character after
658 * the last character used in the conversion.
660 * Converts a string to a #gdouble value.
662 * This function behaves like the standard strtod() function
663 * does in the C locale. It does this without actually changing
664 * the current locale, since that would not be thread-safe.
665 * A limitation of the implementation is that this function
666 * will still accept localized versions of infinities and NANs.
668 * This function is typically used when reading configuration
669 * files or other non-user input that should be locale independent.
670 * To handle input from the user you should normally use the
671 * locale-sensitive system strtod() function.
673 * To convert from a #gdouble to a string in a locale-insensitive
674 * way, use g_ascii_dtostr().
676 * If the correct value would cause overflow, plus or minus <literal>HUGE_VAL</literal>
677 * is returned (according to the sign of the value), and <literal>ERANGE</literal> is
678 * stored in <literal>errno</literal>. If the correct value would cause underflow,
679 * zero is returned and <literal>ERANGE</literal> is stored in <literal>errno</literal>.
681 * This function resets <literal>errno</literal> before calling strtod() so that
682 * you can reliably detect overflow and underflow.
684 * Return value: the #gdouble value.
687 g_ascii_strtod (const gchar *nptr,
692 g_return_val_if_fail (nptr != NULL, 0);
696 return strtod_l (nptr, endptr, get_C_locale ());
703 struct lconv *locale_data;
705 const char *decimal_point;
706 int decimal_point_len;
707 const char *p, *decimal_point_pos;
708 const char *end = NULL; /* Silence gcc */
711 g_return_val_if_fail (nptr != NULL, 0);
716 locale_data = localeconv ();
717 decimal_point = locale_data->decimal_point;
718 decimal_point_len = strlen (decimal_point);
721 decimal_point_len = 1;
724 g_assert (decimal_point_len != 0);
726 decimal_point_pos = NULL;
729 if (decimal_point[0] != '.' ||
730 decimal_point[1] != 0)
733 /* Skip leading space */
734 while (g_ascii_isspace (*p))
737 /* Skip leading optional sign */
738 if (*p == '+' || *p == '-')
742 (p[1] == 'x' || p[1] == 'X'))
745 /* HEX - find the (optional) decimal point */
747 while (g_ascii_isxdigit (*p))
751 decimal_point_pos = p++;
753 while (g_ascii_isxdigit (*p))
756 if (*p == 'p' || *p == 'P')
758 if (*p == '+' || *p == '-')
760 while (g_ascii_isdigit (*p))
765 else if (g_ascii_isdigit (*p) || *p == '.')
767 while (g_ascii_isdigit (*p))
771 decimal_point_pos = p++;
773 while (g_ascii_isdigit (*p))
776 if (*p == 'e' || *p == 'E')
778 if (*p == '+' || *p == '-')
780 while (g_ascii_isdigit (*p))
785 /* For the other cases, we need not convert the decimal point */
788 if (decimal_point_pos)
792 /* We need to convert the '.' to the locale specific decimal point */
793 copy = g_malloc (end - nptr + 1 + decimal_point_len);
796 memcpy (c, nptr, decimal_point_pos - nptr);
797 c += decimal_point_pos - nptr;
798 memcpy (c, decimal_point, decimal_point_len);
799 c += decimal_point_len;
800 memcpy (c, decimal_point_pos + 1, end - (decimal_point_pos + 1));
801 c += end - (decimal_point_pos + 1);
805 val = strtod (copy, &fail_pos);
806 strtod_errno = errno;
810 if (fail_pos - copy > decimal_point_pos - nptr)
811 fail_pos = (char *)nptr + (fail_pos - copy) - (decimal_point_len - 1);
813 fail_pos = (char *)nptr + (fail_pos - copy);
823 copy = g_malloc (end - (char *)nptr + 1);
824 memcpy (copy, nptr, end - nptr);
825 *(copy + (end - (char *)nptr)) = 0;
828 val = strtod (copy, &fail_pos);
829 strtod_errno = errno;
833 fail_pos = (char *)nptr + (fail_pos - copy);
841 val = strtod (nptr, &fail_pos);
842 strtod_errno = errno;
848 errno = strtod_errno;
857 * @buffer: A buffer to place the resulting string in
858 * @buf_len: The length of the buffer.
859 * @d: The #gdouble to convert
861 * Converts a #gdouble to a string, using the '.' as
864 * This function generates enough precision that converting
865 * the string back using g_ascii_strtod() gives the same machine-number
866 * (on machines with IEEE compatible 64bit doubles). It is
867 * guaranteed that the size of the resulting string will never
868 * be larger than @G_ASCII_DTOSTR_BUF_SIZE bytes.
870 * Return value: The pointer to the buffer with the converted string.
873 g_ascii_dtostr (gchar *buffer,
877 return g_ascii_formatd (buffer, buf_len, "%.17g", d);
880 #pragma GCC diagnostic push
881 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
885 * @buffer: A buffer to place the resulting string in
886 * @buf_len: The length of the buffer.
887 * @format: The printf()-style format to use for the
888 * code to use for converting.
889 * @d: The #gdouble to convert
891 * Converts a #gdouble to a string, using the '.' as
892 * decimal point. To format the number you pass in
893 * a printf()-style format string. Allowed conversion
894 * specifiers are 'e', 'E', 'f', 'F', 'g' and 'G'.
896 * If you just want to want to serialize the value into a
897 * string, use g_ascii_dtostr().
899 * Return value: The pointer to the buffer with the converted string.
902 g_ascii_formatd (gchar *buffer,
910 old_locale = uselocale (get_C_locale ());
911 _g_snprintf (buffer, buf_len, format, d);
912 uselocale (old_locale);
917 struct lconv *locale_data;
919 const char *decimal_point;
920 int decimal_point_len;
925 g_return_val_if_fail (buffer != NULL, NULL);
926 g_return_val_if_fail (format[0] == '%', NULL);
927 g_return_val_if_fail (strpbrk (format + 1, "'l%") == NULL, NULL);
929 format_char = format[strlen (format) - 1];
931 g_return_val_if_fail (format_char == 'e' || format_char == 'E' ||
932 format_char == 'f' || format_char == 'F' ||
933 format_char == 'g' || format_char == 'G',
936 if (format[0] != '%')
939 if (strpbrk (format + 1, "'l%"))
942 if (!(format_char == 'e' || format_char == 'E' ||
943 format_char == 'f' || format_char == 'F' ||
944 format_char == 'g' || format_char == 'G'))
947 _g_snprintf (buffer, buf_len, format, d);
950 locale_data = localeconv ();
951 decimal_point = locale_data->decimal_point;
952 decimal_point_len = strlen (decimal_point);
955 decimal_point_len = 1;
958 g_assert (decimal_point_len != 0);
960 if (decimal_point[0] != '.' ||
961 decimal_point[1] != 0)
965 while (g_ascii_isspace (*p))
968 if (*p == '+' || *p == '-')
971 while (isdigit ((guchar)*p))
974 if (strncmp (p, decimal_point, decimal_point_len) == 0)
978 if (decimal_point_len > 1)
980 rest_len = strlen (p + (decimal_point_len-1));
981 memmove (p, p + (decimal_point_len-1), rest_len);
990 #pragma GCC diagnostic pop
992 #define ISSPACE(c) ((c) == ' ' || (c) == '\f' || (c) == '\n' || \
993 (c) == '\r' || (c) == '\t' || (c) == '\v')
994 #define ISUPPER(c) ((c) >= 'A' && (c) <= 'Z')
995 #define ISLOWER(c) ((c) >= 'a' && (c) <= 'z')
996 #define ISALPHA(c) (ISUPPER (c) || ISLOWER (c))
997 #define TOUPPER(c) (ISLOWER (c) ? (c) - 'a' + 'A' : (c))
998 #define TOLOWER(c) (ISUPPER (c) ? (c) - 'A' + 'a' : (c))
1003 g_parse_long_long (const gchar *nptr,
1004 const gchar **endptr,
1008 /* this code is based on on the strtol(3) code from GNU libc released under
1009 * the GNU Lesser General Public License.
1011 * Copyright (C) 1991,92,94,95,96,97,98,99,2000,01,02
1012 * Free Software Foundation, Inc.
1018 const gchar *s, *save;
1021 g_return_val_if_fail (nptr != NULL, 0);
1024 if (base == 1 || base > 36)
1034 /* Skip white space. */
1035 while (ISSPACE (*s))
1038 if (G_UNLIKELY (!*s))
1041 /* Check for a sign. */
1050 /* Recognize number prefix and if BASE is zero, figure it out ourselves. */
1053 if ((base == 0 || base == 16) && TOUPPER (s[1]) == 'X')
1064 /* Save the pointer so we can check later if anything happened. */
1066 cutoff = G_MAXUINT64 / base;
1067 cutlim = G_MAXUINT64 % base;
1074 if (c >= '0' && c <= '9')
1076 else if (ISALPHA (c))
1077 c = TOUPPER (c) - 'A' + 10;
1082 /* Check for overflow. */
1083 if (ui64 > cutoff || (ui64 == cutoff && c > cutlim))
1092 /* Check if anything actually happened. */
1096 /* Store in ENDPTR the address of one character
1097 past the last character we converted. */
1101 if (G_UNLIKELY (overflow))
1110 /* We must handle a special case here: the base is 0 or 16 and the
1111 first two characters are '0' and 'x', but the rest are no
1112 hexadecimal digits. This is no error case. We return 0 and
1113 ENDPTR points to the `x`. */
1116 if (save - nptr >= 2 && TOUPPER (save[-1]) == 'X'
1118 *endptr = &save[-1];
1120 /* There was no number to convert. */
1125 #endif /* !USE_XLOCALE */
1129 * @nptr: the string to convert to a numeric value.
1130 * @endptr: if non-%NULL, it returns the character after
1131 * the last character used in the conversion.
1132 * @base: to be used for the conversion, 2..36 or 0
1134 * Converts a string to a #guint64 value.
1135 * This function behaves like the standard strtoull() function
1136 * does in the C locale. It does this without actually
1137 * changing the current locale, since that would not be
1140 * This function is typically used when reading configuration
1141 * files or other non-user input that should be locale independent.
1142 * To handle input from the user you should normally use the
1143 * locale-sensitive system strtoull() function.
1145 * If the correct value would cause overflow, %G_MAXUINT64
1146 * is returned, and <literal>ERANGE</literal> is stored in <literal>errno</literal>.
1147 * If the base is outside the valid range, zero is returned, and
1148 * <literal>EINVAL</literal> is stored in <literal>errno</literal>.
1149 * If the string conversion fails, zero is returned, and @endptr returns
1150 * @nptr (if @endptr is non-%NULL).
1152 * Return value: the #guint64 value or zero on error.
1157 g_ascii_strtoull (const gchar *nptr,
1162 return strtoull_l (nptr, endptr, base, get_C_locale ());
1167 result = g_parse_long_long (nptr, (const gchar **) endptr, base, &negative);
1169 /* Return the result of the appropriate sign. */
1170 return negative ? -result : result;
1176 * @nptr: the string to convert to a numeric value.
1177 * @endptr: if non-%NULL, it returns the character after
1178 * the last character used in the conversion.
1179 * @base: to be used for the conversion, 2..36 or 0
1181 * Converts a string to a #gint64 value.
1182 * This function behaves like the standard strtoll() function
1183 * does in the C locale. It does this without actually
1184 * changing the current locale, since that would not be
1187 * This function is typically used when reading configuration
1188 * files or other non-user input that should be locale independent.
1189 * To handle input from the user you should normally use the
1190 * locale-sensitive system strtoll() function.
1192 * If the correct value would cause overflow, %G_MAXINT64 or %G_MININT64
1193 * is returned, and <literal>ERANGE</literal> is stored in <literal>errno</literal>.
1194 * If the base is outside the valid range, zero is returned, and
1195 * <literal>EINVAL</literal> is stored in <literal>errno</literal>. If the
1196 * string conversion fails, zero is returned, and @endptr returns @nptr
1197 * (if @endptr is non-%NULL).
1199 * Return value: the #gint64 value or zero on error.
1204 g_ascii_strtoll (const gchar *nptr,
1209 return strtoll_l (nptr, endptr, base, get_C_locale ());
1214 result = g_parse_long_long (nptr, (const gchar **) endptr, base, &negative);
1216 if (negative && result > (guint64) G_MININT64)
1221 else if (!negative && result > (guint64) G_MAXINT64)
1227 return - (gint64) result;
1229 return (gint64) result;
1235 * @errnum: the system error number. See the standard C %errno
1238 * Returns a string corresponding to the given error code, e.g.
1239 * "no such process". You should use this function in preference to
1240 * strerror(), because it returns a string in UTF-8 encoding, and since
1241 * not all platforms support the strerror() function.
1243 * Returns: a UTF-8 string describing the error code. If the error code
1244 * is unknown, it returns "unknown error (<code>)".
1247 g_strerror (gint errnum)
1250 gchar *tofree = NULL;
1252 gint saved_errno = errno;
1254 msg = strerror (errnum);
1255 if (!g_get_charset (NULL))
1256 msg = tofree = g_locale_to_utf8 (msg, -1, NULL, NULL, NULL);
1258 ret = g_intern_string (msg);
1260 errno = saved_errno;
1266 * @signum: the signal number. See the <literal>signal</literal>
1269 * Returns a string describing the given signal, e.g. "Segmentation fault".
1270 * You should use this function in preference to strsignal(), because it
1271 * returns a string in UTF-8 encoding, and since not all platforms support
1272 * the strsignal() function.
1274 * Returns: a UTF-8 string describing the signal. If the signal is unknown,
1275 * it returns "unknown signal (<signum>)".
1278 g_strsignal (gint signum)
1284 msg = tofree = NULL;
1286 #ifdef HAVE_STRSIGNAL
1287 msg = strsignal (signum);
1288 if (!g_get_charset (NULL))
1289 msg = tofree = g_locale_to_utf8 (msg, -1, NULL, NULL, NULL);
1293 msg = tofree = g_strdup_printf ("unknown signal (%d)", signum);
1294 ret = g_intern_string (msg);
1300 /* Functions g_strlcpy and g_strlcat were originally developed by
1301 * Todd C. Miller <Todd.Miller@courtesan.com> to simplify writing secure code.
1302 * See http://www.openbsd.org/cgi-bin/man.cgi?query=strlcpy
1303 * for more information.
1307 /* Use the native ones, if available; they might be implemented in assembly */
1309 g_strlcpy (gchar *dest,
1313 g_return_val_if_fail (dest != NULL, 0);
1314 g_return_val_if_fail (src != NULL, 0);
1316 return strlcpy (dest, src, dest_size);
1320 g_strlcat (gchar *dest,
1324 g_return_val_if_fail (dest != NULL, 0);
1325 g_return_val_if_fail (src != NULL, 0);
1327 return strlcat (dest, src, dest_size);
1330 #else /* ! HAVE_STRLCPY */
1333 * @dest: destination buffer
1334 * @src: source buffer
1335 * @dest_size: length of @dest in bytes
1337 * Portability wrapper that calls strlcpy() on systems which have it,
1338 * and emulates strlcpy() otherwise. Copies @src to @dest; @dest is
1339 * guaranteed to be nul-terminated; @src must be nul-terminated;
1340 * @dest_size is the buffer size, not the number of chars to copy.
1342 * At most dest_size - 1 characters will be copied. Always nul-terminates
1343 * (unless dest_size == 0). This function does <emphasis>not</emphasis>
1344 * allocate memory. Unlike strncpy(), this function doesn't pad dest (so
1345 * it's often faster). It returns the size of the attempted result,
1346 * strlen (src), so if @retval >= @dest_size, truncation occurred.
1348 * <note><para>Caveat: strlcpy() is supposedly more secure than
1349 * strcpy() or strncpy(), but if you really want to avoid screwups,
1350 * g_strdup() is an even better idea.</para></note>
1352 * Returns: length of @src
1355 g_strlcpy (gchar *dest,
1359 register gchar *d = dest;
1360 register const gchar *s = src;
1361 register gsize n = dest_size;
1363 g_return_val_if_fail (dest != NULL, 0);
1364 g_return_val_if_fail (src != NULL, 0);
1366 /* Copy as many bytes as will fit */
1367 if (n != 0 && --n != 0)
1370 register gchar c = *s++;
1378 /* If not enough room in dest, add NUL and traverse rest of src */
1387 return s - src - 1; /* count does not include NUL */
1392 * @dest: destination buffer, already containing one nul-terminated string
1393 * @src: source buffer
1394 * @dest_size: length of @dest buffer in bytes (not length of existing string
1397 * Portability wrapper that calls strlcat() on systems which have it,
1398 * and emulates it otherwise. Appends nul-terminated @src string to @dest,
1399 * guaranteeing nul-termination for @dest. The total size of @dest won't
1400 * exceed @dest_size.
1402 * At most dest_size - 1 characters will be copied.
1403 * Unlike strncat, dest_size is the full size of dest, not the space left over.
1404 * This function does NOT allocate memory.
1405 * This always NUL terminates (unless siz == 0 or there were no NUL characters
1406 * in the dest_size characters of dest to start with).
1408 * <note><para>Caveat: this is supposedly a more secure alternative to
1409 * strcat() or strncat(), but for real security g_strconcat() is harder
1410 * to mess up.</para></note>
1412 * Returns: size of attempted result, which is MIN (dest_size, strlen
1413 * (original dest)) + strlen (src), so if retval >= dest_size,
1414 * truncation occurred.
1417 g_strlcat (gchar *dest,
1421 register gchar *d = dest;
1422 register const gchar *s = src;
1423 register gsize bytes_left = dest_size;
1424 gsize dlength; /* Logically, MIN (strlen (d), dest_size) */
1426 g_return_val_if_fail (dest != NULL, 0);
1427 g_return_val_if_fail (src != NULL, 0);
1429 /* Find the end of dst and adjust bytes left but don't go past end */
1430 while (*d != 0 && bytes_left-- != 0)
1433 bytes_left = dest_size - dlength;
1435 if (bytes_left == 0)
1436 return dlength + strlen (s);
1440 if (bytes_left != 1)
1449 return dlength + (s - src); /* count does not include NUL */
1451 #endif /* ! HAVE_STRLCPY */
1456 * @len: length of @str in bytes, or -1 if @str is nul-terminated.
1458 * Converts all upper case ASCII letters to lower case ASCII letters.
1460 * Return value: a newly-allocated string, with all the upper case
1461 * characters in @str converted to lower case, with
1462 * semantics that exactly match g_ascii_tolower(). (Note
1463 * that this is unlike the old g_strdown(), which modified
1464 * the string in place.)
1467 g_ascii_strdown (const gchar *str,
1472 g_return_val_if_fail (str != NULL, NULL);
1477 result = g_strndup (str, len);
1478 for (s = result; *s; s++)
1479 *s = g_ascii_tolower (*s);
1487 * @len: length of @str in bytes, or -1 if @str is nul-terminated.
1489 * Converts all lower case ASCII letters to upper case ASCII letters.
1491 * Return value: a newly allocated string, with all the lower case
1492 * characters in @str converted to upper case, with
1493 * semantics that exactly match g_ascii_toupper(). (Note
1494 * that this is unlike the old g_strup(), which modified
1495 * the string in place.)
1498 g_ascii_strup (const gchar *str,
1503 g_return_val_if_fail (str != NULL, NULL);
1508 result = g_strndup (str, len);
1509 for (s = result; *s; s++)
1510 *s = g_ascii_toupper (*s);
1517 * @string: a string.
1519 * Determines if a string is pure ASCII. A string is pure ASCII if it
1520 * contains no bytes with the high bit set.
1522 * Returns: %TRUE if @string is ascii
1527 g_str_is_ascii (const gchar *string)
1531 for (i = 0; string[i]; i++)
1532 if (string[i] & 0x80)
1540 * @string: the string to convert.
1542 * Converts a string to lower case.
1544 * Return value: the string
1546 * Deprecated:2.2: This function is totally broken for the reasons discussed
1547 * in the g_strncasecmp() docs - use g_ascii_strdown() or g_utf8_strdown()
1551 g_strdown (gchar *string)
1555 g_return_val_if_fail (string != NULL, NULL);
1557 s = (guchar *) string;
1566 return (gchar *) string;
1571 * @string: the string to convert.
1573 * Converts a string to upper case.
1575 * Return value: the string
1577 * Deprecated:2.2: This function is totally broken for the reasons discussed
1578 * in the g_strncasecmp() docs - use g_ascii_strup() or g_utf8_strup() instead.
1581 g_strup (gchar *string)
1585 g_return_val_if_fail (string != NULL, NULL);
1587 s = (guchar *) string;
1596 return (gchar *) string;
1601 * @string: the string to reverse
1603 * Reverses all of the bytes in a string. For example,
1604 * <literal>g_strreverse ("abcdef")</literal> will result
1607 * Note that g_strreverse() doesn't work on UTF-8 strings
1608 * containing multibyte characters. For that purpose, use
1609 * g_utf8_strreverse().
1611 * Returns: the same pointer passed in as @string
1614 g_strreverse (gchar *string)
1616 g_return_val_if_fail (string != NULL, NULL);
1620 register gchar *h, *t;
1623 t = string + strlen (string) - 1;
1642 * @c: any character.
1644 * Convert a character to ASCII lower case.
1646 * Unlike the standard C library tolower() function, this only
1647 * recognizes standard ASCII letters and ignores the locale, returning
1648 * all non-ASCII characters unchanged, even if they are lower case
1649 * letters in a particular character set. Also unlike the standard
1650 * library function, this takes and returns a char, not an int, so
1651 * don't call it on <literal>EOF</literal> but no need to worry about casting to #guchar
1652 * before passing a possibly non-ASCII character in.
1654 * Return value: the result of converting @c to lower case.
1655 * If @c is not an ASCII upper case letter,
1656 * @c is returned unchanged.
1659 g_ascii_tolower (gchar c)
1661 return g_ascii_isupper (c) ? c - 'A' + 'a' : c;
1666 * @c: any character.
1668 * Convert a character to ASCII upper case.
1670 * Unlike the standard C library toupper() function, this only
1671 * recognizes standard ASCII letters and ignores the locale, returning
1672 * all non-ASCII characters unchanged, even if they are upper case
1673 * letters in a particular character set. Also unlike the standard
1674 * library function, this takes and returns a char, not an int, so
1675 * don't call it on <literal>EOF</literal> but no need to worry about casting to #guchar
1676 * before passing a possibly non-ASCII character in.
1678 * Return value: the result of converting @c to upper case.
1679 * If @c is not an ASCII lower case letter,
1680 * @c is returned unchanged.
1683 g_ascii_toupper (gchar c)
1685 return g_ascii_islower (c) ? c - 'a' + 'A' : c;
1689 * g_ascii_digit_value:
1690 * @c: an ASCII character.
1692 * Determines the numeric value of a character as a decimal
1693 * digit. Differs from g_unichar_digit_value() because it takes
1694 * a char, so there's no worry about sign extension if characters
1697 * Return value: If @c is a decimal digit (according to
1698 * g_ascii_isdigit()), its numeric value. Otherwise, -1.
1701 g_ascii_digit_value (gchar c)
1703 if (g_ascii_isdigit (c))
1709 * g_ascii_xdigit_value:
1710 * @c: an ASCII character.
1712 * Determines the numeric value of a character as a hexidecimal
1713 * digit. Differs from g_unichar_xdigit_value() because it takes
1714 * a char, so there's no worry about sign extension if characters
1717 * Return value: If @c is a hex digit (according to
1718 * g_ascii_isxdigit()), its numeric value. Otherwise, -1.
1721 g_ascii_xdigit_value (gchar c)
1723 if (c >= 'A' && c <= 'F')
1724 return c - 'A' + 10;
1725 if (c >= 'a' && c <= 'f')
1726 return c - 'a' + 10;
1727 return g_ascii_digit_value (c);
1731 * g_ascii_strcasecmp:
1732 * @s1: string to compare with @s2.
1733 * @s2: string to compare with @s1.
1735 * Compare two strings, ignoring the case of ASCII characters.
1737 * Unlike the BSD strcasecmp() function, this only recognizes standard
1738 * ASCII letters and ignores the locale, treating all non-ASCII
1739 * bytes as if they are not letters.
1741 * This function should be used only on strings that are known to be
1742 * in encodings where the bytes corresponding to ASCII letters always
1743 * represent themselves. This includes UTF-8 and the ISO-8859-*
1744 * charsets, but not for instance double-byte encodings like the
1745 * Windows Codepage 932, where the trailing bytes of double-byte
1746 * characters include all ASCII letters. If you compare two CP932
1747 * strings using this function, you will get false matches.
1749 * Both @s1 and @s2 must be non-%NULL.
1751 * Return value: 0 if the strings match, a negative value if @s1 < @s2,
1752 * or a positive value if @s1 > @s2.
1755 g_ascii_strcasecmp (const gchar *s1,
1760 g_return_val_if_fail (s1 != NULL, 0);
1761 g_return_val_if_fail (s2 != NULL, 0);
1765 c1 = (gint)(guchar) TOLOWER (*s1);
1766 c2 = (gint)(guchar) TOLOWER (*s2);
1772 return (((gint)(guchar) *s1) - ((gint)(guchar) *s2));
1776 * g_ascii_strncasecmp:
1777 * @s1: string to compare with @s2.
1778 * @s2: string to compare with @s1.
1779 * @n: number of characters to compare.
1781 * Compare @s1 and @s2, ignoring the case of ASCII characters and any
1782 * characters after the first @n in each string.
1784 * Unlike the BSD strcasecmp() function, this only recognizes standard
1785 * ASCII letters and ignores the locale, treating all non-ASCII
1786 * characters as if they are not letters.
1788 * The same warning as in g_ascii_strcasecmp() applies: Use this
1789 * function only on strings known to be in encodings where bytes
1790 * corresponding to ASCII letters always represent themselves.
1792 * Return value: 0 if the strings match, a negative value if @s1 < @s2,
1793 * or a positive value if @s1 > @s2.
1796 g_ascii_strncasecmp (const gchar *s1,
1802 g_return_val_if_fail (s1 != NULL, 0);
1803 g_return_val_if_fail (s2 != NULL, 0);
1805 while (n && *s1 && *s2)
1808 c1 = (gint)(guchar) TOLOWER (*s1);
1809 c2 = (gint)(guchar) TOLOWER (*s2);
1816 return (((gint) (guchar) *s1) - ((gint) (guchar) *s2));
1824 * @s2: a string to compare with @s1.
1826 * A case-insensitive string comparison, corresponding to the standard
1827 * strcasecmp() function on platforms which support it.
1829 * Return value: 0 if the strings match, a negative value if @s1 < @s2,
1830 * or a positive value if @s1 > @s2.
1832 * Deprecated:2.2: See g_strncasecmp() for a discussion of why this function
1833 * is deprecated and how to replace it.
1836 g_strcasecmp (const gchar *s1,
1839 #ifdef HAVE_STRCASECMP
1840 g_return_val_if_fail (s1 != NULL, 0);
1841 g_return_val_if_fail (s2 != NULL, 0);
1843 return strcasecmp (s1, s2);
1847 g_return_val_if_fail (s1 != NULL, 0);
1848 g_return_val_if_fail (s2 != NULL, 0);
1852 /* According to A. Cox, some platforms have islower's that
1853 * don't work right on non-uppercase
1855 c1 = isupper ((guchar)*s1) ? tolower ((guchar)*s1) : *s1;
1856 c2 = isupper ((guchar)*s2) ? tolower ((guchar)*s2) : *s2;
1862 return (((gint)(guchar) *s1) - ((gint)(guchar) *s2));
1869 * @s2: a string to compare with @s1.
1870 * @n: the maximum number of characters to compare.
1872 * A case-insensitive string comparison, corresponding to the standard
1873 * strncasecmp() function on platforms which support it.
1874 * It is similar to g_strcasecmp() except it only compares the first @n
1875 * characters of the strings.
1877 * Return value: 0 if the strings match, a negative value if @s1 < @s2,
1878 * or a positive value if @s1 > @s2.
1880 * Deprecated:2.2: The problem with g_strncasecmp() is that it does the
1881 * comparison by calling toupper()/tolower(). These functions are
1882 * locale-specific and operate on single bytes. However, it is impossible
1883 * to handle things correctly from an I18N standpoint by operating on
1884 * bytes, since characters may be multibyte. Thus g_strncasecmp() is
1885 * broken if your string is guaranteed to be ASCII, since it's
1886 * locale-sensitive, and it's broken if your string is localized, since
1887 * it doesn't work on many encodings at all, including UTF-8, EUC-JP,
1890 * There are therefore two replacement techniques: g_ascii_strncasecmp(),
1891 * which only works on ASCII and is not locale-sensitive, and
1892 * g_utf8_casefold() followed by strcmp() on the resulting strings, which is
1893 * good for case-insensitive sorting of UTF-8.
1896 g_strncasecmp (const gchar *s1,
1900 #ifdef HAVE_STRNCASECMP
1901 return strncasecmp (s1, s2, n);
1905 g_return_val_if_fail (s1 != NULL, 0);
1906 g_return_val_if_fail (s2 != NULL, 0);
1908 while (n && *s1 && *s2)
1911 /* According to A. Cox, some platforms have islower's that
1912 * don't work right on non-uppercase
1914 c1 = isupper ((guchar)*s1) ? tolower ((guchar)*s1) : *s1;
1915 c2 = isupper ((guchar)*s2) ? tolower ((guchar)*s2) : *s2;
1922 return (((gint) (guchar) *s1) - ((gint) (guchar) *s2));
1930 * @string: the string to convert
1931 * @delimiters: (allow-none): a string containing the current delimiters, or %NULL
1932 * to use the standard delimiters defined in #G_STR_DELIMITERS
1933 * @new_delimiter: the new delimiter character
1935 * Converts any delimiter characters in @string to @new_delimiter.
1936 * Any characters in @string which are found in @delimiters are
1937 * changed to the @new_delimiter character. Modifies @string in place,
1938 * and returns @string itself, not a copy. The return value is to
1939 * allow nesting such as
1941 * g_ascii_strup (g_strdelimit (str, "abc", '?'))
1947 g_strdelimit (gchar *string,
1948 const gchar *delimiters,
1953 g_return_val_if_fail (string != NULL, NULL);
1956 delimiters = G_STR_DELIMITERS;
1958 for (c = string; *c; c++)
1960 if (strchr (delimiters, *c))
1969 * @string: a nul-terminated array of bytes
1970 * @valid_chars: bytes permitted in @string
1971 * @substitutor: replacement character for disallowed bytes
1973 * For each character in @string, if the character is not in
1974 * @valid_chars, replaces the character with @substitutor.
1975 * Modifies @string in place, and return @string itself, not
1976 * a copy. The return value is to allow nesting such as
1978 * g_ascii_strup (g_strcanon (str, "abc", '?'))
1984 g_strcanon (gchar *string,
1985 const gchar *valid_chars,
1990 g_return_val_if_fail (string != NULL, NULL);
1991 g_return_val_if_fail (valid_chars != NULL, NULL);
1993 for (c = string; *c; c++)
1995 if (!strchr (valid_chars, *c))
2004 * @source: a string to compress
2006 * Replaces all escaped characters with their one byte equivalent.
2008 * This function does the reverse conversion of g_strescape().
2010 * Returns: a newly-allocated copy of @source with all escaped
2011 * character compressed
2014 g_strcompress (const gchar *source)
2016 const gchar *p = source, *octal;
2020 g_return_val_if_fail (source != NULL, NULL);
2022 dest = g_malloc (strlen (source) + 1);
2033 g_warning ("g_strcompress: trailing \\");
2035 case '0': case '1': case '2': case '3': case '4':
2036 case '5': case '6': case '7':
2039 while ((p < octal + 3) && (*p >= '0') && (*p <= '7'))
2041 *q = (*q * 8) + (*p - '0');
2065 default: /* Also handles \" and \\ */
2082 * @source: a string to escape
2083 * @exceptions: a string of characters not to escape in @source
2085 * Escapes the special characters '\b', '\f', '\n', '\r', '\t', '\v', '\'
2086 * and '"' in the string @source by inserting a '\' before
2087 * them. Additionally all characters in the range 0x01-0x1F (everything
2088 * below SPACE) and in the range 0x7F-0xFF (all non-ASCII chars) are
2089 * replaced with a '\' followed by their octal representation.
2090 * Characters supplied in @exceptions are not escaped.
2092 * g_strcompress() does the reverse conversion.
2094 * Returns: a newly-allocated copy of @source with certain
2095 * characters escaped. See above.
2098 g_strescape (const gchar *source,
2099 const gchar *exceptions)
2106 g_return_val_if_fail (source != NULL, NULL);
2108 p = (guchar *) source;
2109 /* Each source byte needs maximally four destination chars (\777) */
2110 q = dest = g_malloc (strlen (source) * 4 + 1);
2112 memset (excmap, 0, 256);
2115 guchar *e = (guchar *) exceptions;
2165 if ((*p < ' ') || (*p >= 0177))
2168 *q++ = '0' + (((*p) >> 6) & 07);
2169 *q++ = '0' + (((*p) >> 3) & 07);
2170 *q++ = '0' + ((*p) & 07);
2185 * @string: a string to remove the leading whitespace from
2187 * Removes leading whitespace from a string, by moving the rest
2188 * of the characters forward.
2190 * This function doesn't allocate or reallocate any memory;
2191 * it modifies @string in place. Therefore, it cannot be used on
2192 * statically allocated strings.
2194 * The pointer to @string is returned to allow the nesting of functions.
2196 * Also see g_strchomp() and g_strstrip().
2201 g_strchug (gchar *string)
2205 g_return_val_if_fail (string != NULL, NULL);
2207 for (start = (guchar*) string; *start && g_ascii_isspace (*start); start++)
2210 memmove (string, start, strlen ((gchar *) start) + 1);
2217 * @string: a string to remove the trailing whitespace from
2219 * Removes trailing whitespace from a string.
2221 * This function doesn't allocate or reallocate any memory;
2222 * it modifies @string in place. Therefore, it cannot be used
2223 * on statically allocated strings.
2225 * The pointer to @string is returned to allow the nesting of functions.
2227 * Also see g_strchug() and g_strstrip().
2232 g_strchomp (gchar *string)
2236 g_return_val_if_fail (string != NULL, NULL);
2238 len = strlen (string);
2241 if (g_ascii_isspace ((guchar) string[len]))
2252 * @string: a string to split
2253 * @delimiter: a string which specifies the places at which to split
2254 * the string. The delimiter is not included in any of the resulting
2255 * strings, unless @max_tokens is reached.
2256 * @max_tokens: the maximum number of pieces to split @string into.
2257 * If this is less than 1, the string is split completely.
2259 * Splits a string into a maximum of @max_tokens pieces, using the given
2260 * @delimiter. If @max_tokens is reached, the remainder of @string is
2261 * appended to the last token.
2263 * As a special case, the result of splitting the empty string "" is an empty
2264 * vector, not a vector containing a single string. The reason for this
2265 * special case is that being able to represent a empty vector is typically
2266 * more useful than consistent handling of empty elements. If you do need
2267 * to represent empty elements, you'll need to check for the empty string
2268 * before calling g_strsplit().
2270 * Return value: a newly-allocated %NULL-terminated array of strings. Use
2271 * g_strfreev() to free it.
2274 g_strsplit (const gchar *string,
2275 const gchar *delimiter,
2278 GSList *string_list = NULL, *slist;
2279 gchar **str_array, *s;
2281 const gchar *remainder;
2283 g_return_val_if_fail (string != NULL, NULL);
2284 g_return_val_if_fail (delimiter != NULL, NULL);
2285 g_return_val_if_fail (delimiter[0] != '\0', NULL);
2288 max_tokens = G_MAXINT;
2291 s = strstr (remainder, delimiter);
2294 gsize delimiter_len = strlen (delimiter);
2296 while (--max_tokens && s)
2300 len = s - remainder;
2301 string_list = g_slist_prepend (string_list,
2302 g_strndup (remainder, len));
2304 remainder = s + delimiter_len;
2305 s = strstr (remainder, delimiter);
2311 string_list = g_slist_prepend (string_list, g_strdup (remainder));
2314 str_array = g_new (gchar*, n + 1);
2316 str_array[n--] = NULL;
2317 for (slist = string_list; slist; slist = slist->next)
2318 str_array[n--] = slist->data;
2320 g_slist_free (string_list);
2327 * @string: The string to be tokenized
2328 * @delimiters: A nul-terminated string containing bytes that are used
2329 * to split the string.
2330 * @max_tokens: The maximum number of tokens to split @string into.
2331 * If this is less than 1, the string is split completely
2333 * Splits @string into a number of tokens not containing any of the characters
2334 * in @delimiter. A token is the (possibly empty) longest string that does not
2335 * contain any of the characters in @delimiters. If @max_tokens is reached, the
2336 * remainder is appended to the last token.
2338 * For example the result of g_strsplit_set ("abc:def/ghi", ":/", -1) is a
2339 * %NULL-terminated vector containing the three strings "abc", "def",
2342 * The result if g_strsplit_set (":def/ghi:", ":/", -1) is a %NULL-terminated
2343 * vector containing the four strings "", "def", "ghi", and "".
2345 * As a special case, the result of splitting the empty string "" is an empty
2346 * vector, not a vector containing a single string. The reason for this
2347 * special case is that being able to represent a empty vector is typically
2348 * more useful than consistent handling of empty elements. If you do need
2349 * to represent empty elements, you'll need to check for the empty string
2350 * before calling g_strsplit_set().
2352 * Note that this function works on bytes not characters, so it can't be used
2353 * to delimit UTF-8 strings for anything but ASCII characters.
2355 * Return value: a newly-allocated %NULL-terminated array of strings. Use
2356 * g_strfreev() to free it.
2361 g_strsplit_set (const gchar *string,
2362 const gchar *delimiters,
2365 gboolean delim_table[256];
2366 GSList *tokens, *list;
2369 const gchar *current;
2373 g_return_val_if_fail (string != NULL, NULL);
2374 g_return_val_if_fail (delimiters != NULL, NULL);
2377 max_tokens = G_MAXINT;
2379 if (*string == '\0')
2381 result = g_new (char *, 1);
2386 memset (delim_table, FALSE, sizeof (delim_table));
2387 for (s = delimiters; *s != '\0'; ++s)
2388 delim_table[*(guchar *)s] = TRUE;
2393 s = current = string;
2396 if (delim_table[*(guchar *)s] && n_tokens + 1 < max_tokens)
2398 token = g_strndup (current, s - current);
2399 tokens = g_slist_prepend (tokens, token);
2408 token = g_strndup (current, s - current);
2409 tokens = g_slist_prepend (tokens, token);
2412 result = g_new (gchar *, n_tokens + 1);
2414 result[n_tokens] = NULL;
2415 for (list = tokens; list != NULL; list = list->next)
2416 result[--n_tokens] = list->data;
2418 g_slist_free (tokens);
2425 * @str_array: a %NULL-terminated array of strings to free
2427 * Frees a %NULL-terminated array of strings, and the array itself.
2428 * If called on a %NULL value, g_strfreev() simply returns.
2431 g_strfreev (gchar **str_array)
2437 for (i = 0; str_array[i] != NULL; i++)
2438 g_free (str_array[i]);
2446 * @str_array: a %NULL-terminated array of strings
2448 * Copies %NULL-terminated array of strings. The copy is a deep copy;
2449 * the new array should be freed by first freeing each string, then
2450 * the array itself. g_strfreev() does this for you. If called
2451 * on a %NULL value, g_strdupv() simply returns %NULL.
2453 * Return value: a new %NULL-terminated array of strings.
2456 g_strdupv (gchar **str_array)
2464 while (str_array[i])
2467 retval = g_new (gchar*, i + 1);
2470 while (str_array[i])
2472 retval[i] = g_strdup (str_array[i]);
2485 * @separator: (allow-none): a string to insert between each of the strings, or %NULL
2486 * @str_array: a %NULL-terminated array of strings to join
2488 * Joins a number of strings together to form one long string, with the
2489 * optional @separator inserted between each of them. The returned string
2490 * should be freed with g_free().
2492 * Returns: a newly-allocated string containing all of the strings joined
2493 * together, with @separator between them
2496 g_strjoinv (const gchar *separator,
2502 g_return_val_if_fail (str_array != NULL, NULL);
2504 if (separator == NULL)
2511 gsize separator_len;
2513 separator_len = strlen (separator);
2514 /* First part, getting length */
2515 len = 1 + strlen (str_array[0]);
2516 for (i = 1; str_array[i] != NULL; i++)
2517 len += strlen (str_array[i]);
2518 len += separator_len * (i - 1);
2520 /* Second part, building string */
2521 string = g_new (gchar, len);
2522 ptr = g_stpcpy (string, *str_array);
2523 for (i = 1; str_array[i] != NULL; i++)
2525 ptr = g_stpcpy (ptr, separator);
2526 ptr = g_stpcpy (ptr, str_array[i]);
2530 string = g_strdup ("");
2537 * @separator: (allow-none): a string to insert between each of the strings, or %NULL
2538 * @...: a %NULL-terminated list of strings to join
2540 * Joins a number of strings together to form one long string, with the
2541 * optional @separator inserted between each of them. The returned string
2542 * should be freed with g_free().
2544 * Returns: a newly-allocated string containing all of the strings joined
2545 * together, with @separator between them
2548 g_strjoin (const gchar *separator,
2554 gsize separator_len;
2557 if (separator == NULL)
2560 separator_len = strlen (separator);
2562 va_start (args, separator);
2564 s = va_arg (args, gchar*);
2568 /* First part, getting length */
2569 len = 1 + strlen (s);
2571 s = va_arg (args, gchar*);
2574 len += separator_len + strlen (s);
2575 s = va_arg (args, gchar*);
2579 /* Second part, building string */
2580 string = g_new (gchar, len);
2582 va_start (args, separator);
2584 s = va_arg (args, gchar*);
2585 ptr = g_stpcpy (string, s);
2587 s = va_arg (args, gchar*);
2590 ptr = g_stpcpy (ptr, separator);
2591 ptr = g_stpcpy (ptr, s);
2592 s = va_arg (args, gchar*);
2596 string = g_strdup ("");
2606 * @haystack: a string
2607 * @haystack_len: the maximum length of @haystack. Note that -1 is
2608 * a valid length, if @haystack is nul-terminated, meaning it will
2609 * search through the whole string.
2610 * @needle: the string to search for
2612 * Searches the string @haystack for the first occurrence
2613 * of the string @needle, limiting the length of the search
2616 * Return value: a pointer to the found occurrence, or
2617 * %NULL if not found.
2620 g_strstr_len (const gchar *haystack,
2621 gssize haystack_len,
2622 const gchar *needle)
2624 g_return_val_if_fail (haystack != NULL, NULL);
2625 g_return_val_if_fail (needle != NULL, NULL);
2627 if (haystack_len < 0)
2628 return strstr (haystack, needle);
2631 const gchar *p = haystack;
2632 gsize needle_len = strlen (needle);
2636 if (needle_len == 0)
2637 return (gchar *)haystack;
2639 if (haystack_len < needle_len)
2642 end = haystack + haystack_len - needle_len;
2644 while (p <= end && *p)
2646 for (i = 0; i < needle_len; i++)
2647 if (p[i] != needle[i])
2662 * @haystack: a nul-terminated string
2663 * @needle: the nul-terminated string to search for
2665 * Searches the string @haystack for the last occurrence
2666 * of the string @needle.
2668 * Return value: a pointer to the found occurrence, or
2669 * %NULL if not found.
2672 g_strrstr (const gchar *haystack,
2673 const gchar *needle)
2680 g_return_val_if_fail (haystack != NULL, NULL);
2681 g_return_val_if_fail (needle != NULL, NULL);
2683 needle_len = strlen (needle);
2684 haystack_len = strlen (haystack);
2686 if (needle_len == 0)
2687 return (gchar *)haystack;
2689 if (haystack_len < needle_len)
2692 p = haystack + haystack_len - needle_len;
2694 while (p >= haystack)
2696 for (i = 0; i < needle_len; i++)
2697 if (p[i] != needle[i])
2711 * @haystack: a nul-terminated string
2712 * @haystack_len: the maximum length of @haystack
2713 * @needle: the nul-terminated string to search for
2715 * Searches the string @haystack for the last occurrence
2716 * of the string @needle, limiting the length of the search
2719 * Return value: a pointer to the found occurrence, or
2720 * %NULL if not found.
2723 g_strrstr_len (const gchar *haystack,
2724 gssize haystack_len,
2725 const gchar *needle)
2727 g_return_val_if_fail (haystack != NULL, NULL);
2728 g_return_val_if_fail (needle != NULL, NULL);
2730 if (haystack_len < 0)
2731 return g_strrstr (haystack, needle);
2734 gsize needle_len = strlen (needle);
2735 const gchar *haystack_max = haystack + haystack_len;
2736 const gchar *p = haystack;
2739 while (p < haystack_max && *p)
2742 if (p < haystack + needle_len)
2747 while (p >= haystack)
2749 for (i = 0; i < needle_len; i++)
2750 if (p[i] != needle[i])
2766 * @str: a nul-terminated string
2767 * @suffix: the nul-terminated suffix to look for
2769 * Looks whether the string @str ends with @suffix.
2771 * Return value: %TRUE if @str end with @suffix, %FALSE otherwise.
2776 g_str_has_suffix (const gchar *str,
2777 const gchar *suffix)
2782 g_return_val_if_fail (str != NULL, FALSE);
2783 g_return_val_if_fail (suffix != NULL, FALSE);
2785 str_len = strlen (str);
2786 suffix_len = strlen (suffix);
2788 if (str_len < suffix_len)
2791 return strcmp (str + str_len - suffix_len, suffix) == 0;
2796 * @str: a nul-terminated string
2797 * @prefix: the nul-terminated prefix to look for
2799 * Looks whether the string @str begins with @prefix.
2801 * Return value: %TRUE if @str begins with @prefix, %FALSE otherwise.
2806 g_str_has_prefix (const gchar *str,
2807 const gchar *prefix)
2812 g_return_val_if_fail (str != NULL, FALSE);
2813 g_return_val_if_fail (prefix != NULL, FALSE);
2815 str_len = strlen (str);
2816 prefix_len = strlen (prefix);
2818 if (str_len < prefix_len)
2821 return strncmp (str, prefix, prefix_len) == 0;
2826 * @str_array: a %NULL-terminated array of strings
2828 * Returns the length of the given %NULL-terminated
2829 * string array @str_array.
2831 * Return value: length of @str_array.
2836 g_strv_length (gchar **str_array)
2840 g_return_val_if_fail (str_array != NULL, 0);
2842 while (str_array[i])
2849 index_add_folded (GPtrArray *array,
2855 normal = g_utf8_normalize (start, end - start, G_NORMALIZE_ALL_COMPOSE);
2857 /* TODO: Invent time machine. Converse with Mustafa Ataturk... */
2858 if (strstr (normal, "ı") || strstr (normal, "İ"))
2863 tmp = g_string_new (NULL);
2869 i = strstr (s, "ı");
2870 I = strstr (s, "İ");
2883 g_string_append_len (tmp, s, e - s);
2884 g_string_append_c (tmp, 'i');
2885 s = g_utf8_next_char (e);
2888 g_string_append (tmp, s);
2890 normal = g_string_free (tmp, FALSE);
2893 g_ptr_array_add (array, g_utf8_casefold (normal, -1));
2898 split_words (const gchar *value)
2900 const gchar *start = NULL;
2904 result = g_ptr_array_new ();
2906 for (s = value; *s; s = g_utf8_next_char (s))
2908 gunichar c = g_utf8_get_char (s);
2912 if (g_unichar_isalnum (c) || g_unichar_ismark (c))
2917 if (!g_unichar_isalnum (c) && !g_unichar_ismark (c))
2919 index_add_folded (result, start, s);
2926 index_add_folded (result, start, s);
2928 g_ptr_array_add (result, NULL);
2930 return (gchar **) g_ptr_array_free (result, FALSE);
2934 * g_str_tokenize_and_fold:
2936 * @translit_locale: (allow-none): the language code (like 'de' or
2937 * 'en_GB') from which @string originates
2938 * @ascii_alternates: (out) (transfer full) (array zero-terminated=1): a
2939 * return location for ASCII alternates
2941 * Tokenises @string and performs folding on each token.
2943 * A token is a non-empty sequence of alphanumeric characters in the
2944 * source string, separated by non-alphanumeric characters. An
2945 * "alphanumeric" character for this purpose is one that matches
2946 * g_unichar_isalnum() or g_unichar_ismark().
2948 * Each token is then (Unicode) normalised and case-folded. If
2949 * @ascii_alternates is non-%NULL and some of the returned tokens
2950 * contain non-ASCII characters, ASCII alternatives will be generated.
2952 * The number of ASCII alternatives that are generated and the method
2953 * for doing so is unspecified, but @translit_locale (if specified) may
2954 * improve the transliteration if the language of the source string is
2957 * Returns: (transfer full) (array zero-terminated=1): the folded tokens
2962 g_str_tokenize_and_fold (const gchar *string,
2963 const gchar *translit_locale,
2964 gchar ***ascii_alternates)
2968 if (ascii_alternates && g_str_is_ascii (string))
2970 *ascii_alternates = g_new0 (gchar *, 0 + 1);
2971 ascii_alternates = NULL;
2974 result = split_words (string);
2976 /* TODO: proper iconv transliteration (locale-dependent) */
2977 if (ascii_alternates)
2981 n = g_strv_length (result);
2982 *ascii_alternates = g_new (gchar *, n + 1);
2985 for (i = 0; i < n; i++)
2987 if (!g_str_is_ascii (result[i]))
2994 decomposed = g_utf8_normalize (result[i], -1, G_NORMALIZE_ALL);
2995 ascii = g_malloc (strlen (decomposed) + 1);
2997 for (k = 0; decomposed[k]; k++)
2998 if (~decomposed[k] & 0x80)
2999 ascii[l++] = decomposed[k];
3002 (*ascii_alternates)[j++] = ascii;
3003 g_free (decomposed);
3007 (*ascii_alternates)[j] = NULL;
3014 * g_str_match_string:
3015 * @search_term: the search term from the user
3016 * @potential_hit: the text that may be a hit
3017 * @accept_alternates: %TRUE to accept ASCII alternates
3019 * Checks if a search conducted for @search_term should match
3022 * This function calls g_str_tokenize_and_fold() on both
3023 * @search_term and @potential_hit. ASCII alternates are never taken
3024 * for @search_term but will be taken for @potential_hit according to
3025 * the value of @accept_alternates.
3027 * A hit occurs when each folded token in @search_term is a prefix of a
3028 * folded token from @potential_hit.
3030 * Depending on how you're performing the search, it will typically be
3031 * faster to call g_str_tokenize_and_fold() on each string in
3032 * your corpus and build an index on the returned folded tokens, then
3033 * call g_str_tokenize_and_fold() on the search term and
3034 * perform lookups into that index.
3036 * As some examples, searching for "fred" would match the potential hit
3037 * "Smith, Fred" and also "Frédéric". Searching for "Fréd" would match
3038 * "Frédéric" but not "Frederic" (due to the one-directional nature of
3039 * accent matching). Searching "fo" would match "Foo" and "Bar Foo
3040 * Baz", but not "SFO" (because no word as "fo" as a prefix).
3042 * Returns: %TRUE if @potential_hit is a hit
3047 g_str_match_string (const gchar *search_term,
3048 const gchar *potential_hit,
3049 gboolean accept_alternates)
3051 gchar **alternates = NULL;
3052 gchar **term_tokens;
3057 term_tokens = g_str_tokenize_and_fold (search_term, NULL, NULL);
3058 hit_tokens = g_str_tokenize_and_fold (potential_hit, NULL, accept_alternates ? &alternates : NULL);
3062 for (i = 0; term_tokens[i]; i++)
3064 for (j = 0; hit_tokens[j]; j++)
3065 if (g_str_has_prefix (hit_tokens[j], term_tokens[i]))
3068 if (accept_alternates)
3069 for (j = 0; alternates[j]; j++)
3070 if (g_str_has_prefix (alternates[j], term_tokens[i]))
3080 g_strfreev (term_tokens);
3081 g_strfreev (hit_tokens);
3082 g_strfreev (alternates);